Fix from Ed Boraas for not core dumping when out of connection structs.
[tprouty/samba.git] / source / smbd / service.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    service (connection) opening and closing
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 extern int DEBUGLEVEL;
25
26 extern struct timeval smb_last_time;
27 extern int case_default;
28 extern BOOL case_preserve;
29 extern BOOL short_case_preserve;
30 extern BOOL case_mangle;
31 extern BOOL case_sensitive;
32 extern BOOL use_mangled_map;
33 extern fstring remote_machine;
34 extern userdom_struct current_user_info;
35 extern fstring remote_machine;
36
37
38 /****************************************************************************
39 load parameters specific to a connection/service
40 ****************************************************************************/
41 BOOL become_service(connection_struct *conn,BOOL do_chdir)
42 {
43         extern char magic_char;
44         static connection_struct *last_conn;
45         int snum;
46
47         if (!conn)  {
48                 last_conn = NULL;
49                 return(False);
50         }
51
52         conn->lastused = smb_last_time.tv_sec;
53
54         snum = SNUM(conn);
55   
56         if (do_chdir &&
57             vfs_ChDir(conn,conn->connectpath) != 0 &&
58             vfs_ChDir(conn,conn->origpath) != 0) {
59                 DEBUG(0,("chdir (%s) failed\n",
60                          conn->connectpath));
61                 return(False);
62         }
63
64         if (conn == last_conn)
65                 return(True);
66
67         last_conn = conn;
68
69         case_default = lp_defaultcase(snum);
70         case_preserve = lp_preservecase(snum);
71         short_case_preserve = lp_shortpreservecase(snum);
72         case_mangle = lp_casemangle(snum);
73         case_sensitive = lp_casesensitive(snum);
74         magic_char = lp_magicchar(snum);
75         use_mangled_map = (*lp_mangled_map(snum) ? True:False);
76         return(True);
77 }
78
79 /****************************************************************************
80  Add a home service. Returns the new service number or -1 if fail.
81 ****************************************************************************/
82
83 int add_home_service(char *service, char *homedir)
84 {
85         int iHomeService;
86         int iService;
87         fstring new_service;
88         char *usr_p = NULL;
89
90         if (!service || !homedir)
91                 return -1;
92
93         if ((iHomeService = lp_servicenumber(HOMES_NAME)) < 0)
94                 return -1;
95
96         /*
97          * If this is a winbindd provided username, remove
98          * the domain component before adding the service.
99          * Log a warning if the "path=" parameter does not
100          * include any macros.
101          */
102
103         fstrcpy(new_service, service);
104
105         if ((usr_p = strchr(service,*lp_winbind_separator())) != NULL)
106                 fstrcpy(new_service, usr_p+1);
107
108         lp_add_home(new_service,iHomeService,homedir);
109         iService = lp_servicenumber(new_service);
110
111         if ((iService != -1) && usr_p && (strstr(lp_pathname(iService),"%D") == NULL))
112                 DEBUG(0,("find_service: Service %s added for user %s - contains non-local (Domain) user \
113 with non-domain parameterised path (%s). This may be cause the wrong directory to be seen.\n",
114                 new_service, service, lp_pathname(iService) ));
115
116         return iService;
117 }
118
119 /****************************************************************************
120  Find a service entry. service is always in dos codepage.
121 ****************************************************************************/
122
123 int find_service(char *service)
124 {
125    int iService;
126
127    all_string_sub(service,"\\","/",0);
128
129    iService = lp_servicenumber(service);
130
131    /* now handle the special case of a home directory */
132    if (iService < 0)
133    {
134       char *phome_dir = get_user_home_dir(service);
135
136       if(!phome_dir)
137       {
138         /*
139          * Try mapping the servicename, it may
140          * be a Windows to unix mapped user name.
141          */
142         if(map_username(service))
143           phome_dir = get_user_home_dir(service);
144       }
145
146       DEBUG(3,("checking for home directory %s gave %s\n",service,
147             phome_dir?phome_dir:"(NULL)"));
148
149       iService = add_home_service(service,phome_dir);
150    }
151
152    /* If we still don't have a service, attempt to add it as a printer. */
153    if (iService < 0)
154    {
155       int iPrinterService;
156
157       if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
158       {
159          char *pszTemp;
160
161          DEBUG(3,("checking whether %s is a valid printer name...\n", service));
162          pszTemp = PRINTCAP;
163          if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
164          {
165             DEBUG(3,("%s is a valid printer name\n", service));
166             DEBUG(3,("adding %s as a printer service\n", service));
167             lp_add_printer(service,iPrinterService);
168             iService = lp_servicenumber(service);
169             if (iService < 0)
170                DEBUG(0,("failed to add %s as a printer service!\n", service));
171          }
172          else
173             DEBUG(3,("%s is not a valid printer name\n", service));
174       }
175    }
176
177    /* Check for default vfs service?  Unsure whether to implement this */
178    if (iService < 0)
179    {
180    }
181
182    /* just possibly it's a default service? */
183    if (iService < 0) 
184    {
185      char *pdefservice = lp_defaultservice();
186      if (pdefservice && *pdefservice && 
187          !strequal(pdefservice,service) &&
188          !strstr(service,".."))
189      {
190        /*
191         * We need to do a local copy here as lp_defaultservice() 
192         * returns one of the rotating lp_string buffers that
193         * could get overwritten by the recursive find_service() call
194         * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
195         */
196        pstring defservice;
197        pstrcpy(defservice, pdefservice);
198        iService = find_service(defservice);
199        if (iService >= 0)
200        {
201          all_string_sub(service,"_","/",0);
202          iService = lp_add_service(service,iService);
203        }
204      }
205    }
206
207    if (iService >= 0)
208      if (!VALID_SNUM(iService))
209      {
210        DEBUG(0,("Invalid snum %d for %s\n",iService,service));
211        iService = -1;
212      }
213
214    if (iService < 0)
215      DEBUG(3,("find_service() failed to find service %s\n", service));
216
217    return (iService);
218 }
219
220
221 /****************************************************************************
222   make a connection to a service
223 ****************************************************************************/
224 connection_struct *make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid, int *ecode)
225 {
226         int snum;
227         struct passwd *pass = NULL;
228         BOOL guest = False;
229         BOOL force = False;
230         connection_struct *conn;
231         int ret;
232
233         strlower(service);
234
235         snum = find_service(service);
236         if (snum < 0) {
237                 if (strequal(service,"IPC$") || strequal(service,"ADMIN$")) {
238                         DEBUG(3,("refusing IPC connection\n"));
239                         *ecode = ERRnoipc;
240                         return NULL;
241                 }
242
243                 DEBUG(0,("%s (%s) couldn't find service %s\n",
244                          remote_machine, client_addr(), service));
245                 *ecode = ERRnosuchshare;
246                 return NULL;
247         }
248
249         if (strequal(service,HOMES_NAME)) {
250                 if (*user && Get_Pwnam(user,True)) {
251                         fstring dos_username;
252                         fstrcpy(dos_username, user);
253                         unix_to_dos(dos_username, True);
254                         return(make_connection(dos_username,user,password,
255                                                pwlen,dev,vuid,ecode));
256                 }
257
258                 if(lp_security() != SEC_SHARE) {
259                         if (validated_username(vuid)) {
260                                 fstring dos_username;
261                                 fstrcpy(user,validated_username(vuid));
262                                 fstrcpy(dos_username, user);
263                                 unix_to_dos(dos_username, True);
264                                 return(make_connection(dos_username,user,password,pwlen,dev,vuid,ecode));
265                         }
266                 } else {
267                         /* Security = share. Try with current_user_info.smb_name
268                          * as the username.  */
269                         if(*current_user_info.smb_name) {
270                                 fstring dos_username;
271                                 fstrcpy(user,current_user_info.smb_name);
272                                 fstrcpy(dos_username, user);
273                                 unix_to_dos(dos_username, True);
274                                 return(make_connection(dos_username,user,password,pwlen,dev,vuid,ecode));
275                         }
276                 }
277         }
278
279         if (!lp_snum_ok(snum) || 
280             !check_access(smbd_server_fd(), 
281                           lp_hostsallow(snum), lp_hostsdeny(snum))) {    
282                 *ecode = ERRaccess;
283                 return NULL;
284         }
285
286         /* you can only connect to the IPC$ service as an ipc device */
287         if (strequal(service,"IPC$") || strequal(service,"ADMIN$"))
288                 pstrcpy(dev,"IPC");
289         
290         if (*dev == '?' || !*dev) {
291                 if (lp_print_ok(snum)) {
292                         pstrcpy(dev,"LPT1:");
293                 } else {
294                         pstrcpy(dev,"A:");
295                 }
296         }
297
298         /* if the request is as a printer and you can't print then refuse */
299         strupper(dev);
300         if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
301                 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
302                 *ecode = ERRinvdevice;
303                 return NULL;
304         }
305
306         /* Behave as a printer if we are supposed to */
307         if (lp_print_ok(snum) && (strcmp(dev, "A:") == 0)) {
308                 pstrcpy(dev, "LPT1:");
309         }
310
311         /* lowercase the user name */
312         strlower(user);
313
314         /* add it as a possible user name if we 
315            are in share mode security */
316         if (lp_security() == SEC_SHARE) {
317                 add_session_user(service);
318         }
319
320         /* shall we let them in? */
321         if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid)) {
322                 DEBUG( 2, ( "Invalid username/password for %s [%s]\n", service, user ) );
323                 *ecode = ERRbadpw;
324                 return NULL;
325         }
326   
327         conn = conn_new();
328         if (!conn) {
329                 DEBUG(0,("Couldn't find free connection.\n"));
330                 *ecode = ERRnoresource;
331                 return NULL;
332         }
333
334         /* find out some info about the user */
335         pass = smb_getpwnam(user,True);
336
337         if (pass == NULL) {
338                 DEBUG(0,( "Couldn't find account %s\n",user));
339                 *ecode = ERRbaduid;
340                 conn_free(conn);
341                 return NULL;
342         }
343
344         conn->read_only = lp_readonly(snum);
345
346         {
347                 pstring list;
348                 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
349                 pstring_sub(list,"%S",service);
350
351                 if (user_in_list(user,list))
352                         conn->read_only = True;
353                 
354                 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
355                 pstring_sub(list,"%S",service);
356                 
357                 if (user_in_list(user,list))
358                         conn->read_only = False;    
359         }
360
361         /* admin user check */
362         
363         /* JRA - original code denied admin user if the share was
364            marked read_only. Changed as I don't think this is needed,
365            but old code left in case there is a problem here.
366         */
367         if (user_in_list(user,lp_admin_users(snum)) 
368 #if 0
369             && !conn->read_only
370 #endif
371             ) {
372                 conn->admin_user = True;
373                 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
374         } else {
375                 conn->admin_user = False;
376         }
377     
378         conn->force_user = force;
379         conn->vuid = vuid;
380         conn->uid = pass->pw_uid;
381         conn->gid = pass->pw_gid;
382         safe_strcpy(conn->client_address, client_addr(), sizeof(conn->client_address)-1);
383         conn->num_files_open = 0;
384         conn->lastused = time(NULL);
385         conn->service = snum;
386         conn->used = True;
387         conn->printer = (strncmp(dev,"LPT",3) == 0);
388         conn->ipc = ((strncmp(dev,"IPC",3) == 0) || strequal(dev,"ADMIN$"));
389         conn->dirptr = NULL;
390         conn->veto_list = NULL;
391         conn->hide_list = NULL;
392         conn->veto_oplock_list = NULL;
393         string_set(&conn->dirpath,"");
394         string_set(&conn->user,user);
395         conn->nt_user_token = NULL;
396         
397         /*
398          * If force user is true, then store the
399          * given userid and also the primary groupid
400          * of the user we're forcing.
401          */
402         
403         if (*lp_force_user(snum)) {
404                 struct passwd *pass2;
405                 pstring fuser;
406                 pstrcpy(fuser,lp_force_user(snum));
407
408                 /* Allow %S to be used by force user. */
409                 pstring_sub(fuser,"%S",service);
410
411                 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
412                 if (pass2) {
413                         conn->uid = pass2->pw_uid;
414                         conn->gid = pass2->pw_gid;
415                         string_set(&conn->user,fuser);
416                         fstrcpy(user,fuser);
417                         conn->force_user = True;
418                         DEBUG(3,("Forced user %s\n",fuser));      
419                 } else {
420                         DEBUG(1,("Couldn't find user %s\n",fuser));
421                 }
422         }
423
424         /* admin users always run as uid=0 */
425         if (conn->admin_user) {
426                 conn->uid = 0;
427         }
428
429 #ifdef HAVE_GETGRNAM 
430         /*
431          * If force group is true, then override
432          * any groupid stored for the connecting user.
433          */
434         
435         if (*lp_force_group(snum)) {
436                 gid_t gid;
437                 pstring gname;
438                 pstring tmp_gname;
439                 BOOL user_must_be_member = False;
440                 
441                 StrnCpy(tmp_gname,lp_force_group(snum),sizeof(pstring)-1);
442
443                 if (tmp_gname[0] == '+') {
444                         user_must_be_member = True;
445                         StrnCpy(gname,&tmp_gname[1],sizeof(pstring)-2);
446                 } else {
447                         StrnCpy(gname,tmp_gname,sizeof(pstring)-1);
448                 }
449                 /* default service may be a group name          */
450                 pstring_sub(gname,"%S",service);
451                 gid = nametogid(gname);
452                 
453                 if (gid != (gid_t)-1) {
454                         /*
455                          * If the user has been forced and the forced group starts
456                          * with a '+', then we only set the group to be the forced
457                          * group if the forced user is a member of that group.
458                          * Otherwise, the meaning of the '+' would be ignored.
459                          */
460                         if (conn->force_user && user_must_be_member) {
461                                 if (user_in_group_list( user, gname )) {
462                                                 conn->gid = gid;
463                                                 DEBUG(3,("Forced group %s for member %s\n",gname,user));
464                                 }
465                         } else {
466                                 conn->gid = gid;
467                                 DEBUG(3,("Forced group %s\n",gname));
468                         }
469                 } else {
470                         DEBUG(1,("Couldn't find group %s\n",gname));
471                 }
472         }
473 #endif /* HAVE_GETGRNAM */
474
475         {
476                 pstring s;
477                 pstrcpy(s,lp_pathname(snum));
478                 standard_sub_conn(conn,s);
479                 string_set(&conn->connectpath,s);
480                 DEBUG(3,("Connect path is %s\n",s));
481         }
482
483         /* groups stuff added by ih */
484         conn->ngroups = 0;
485         conn->groups = NULL;
486         
487         /* Find all the groups this uid is in and
488            store them. Used by become_user() */
489         initialise_groups(conn->user, conn->uid, conn->gid); 
490         get_current_groups(&conn->ngroups,&conn->groups);
491                 
492         /* check number of connections */
493         if (!claim_connection(conn,
494                               lp_servicename(SNUM(conn)),
495                               lp_max_connections(SNUM(conn)),
496                               False)) {
497                 DEBUG(1,("too many connections - rejected\n"));
498                 *ecode = ERRnoresource;
499                 conn_free(conn);
500                 return NULL;
501         }  
502                 
503         conn->nt_user_token = create_nt_token(conn->uid, conn->gid, 
504                                               conn->ngroups, conn->groups,
505                                               guest);
506
507         /* Initialise VFS function pointers */
508
509         if (*lp_vfsobj(SNUM(conn))) {
510
511 #ifdef HAVE_LIBDL
512
513             /* Loadable object file */
514
515             if (!vfs_init_custom(conn)) {
516                 DEBUG(0, ("vfs_init failed\n"));
517                     conn_free(conn);
518                         return NULL;
519             }
520 #else
521             DEBUG(0, ("No libdl present - cannot use VFS objects\n"));
522             conn_free(conn);
523             return NULL;
524 #endif
525
526         } else {
527
528             /* Normal share - initialise with disk access functions */
529
530             vfs_init_default(conn);
531         }
532
533         /* execute any "root preexec = " line */
534         if (*lp_rootpreexec(SNUM(conn))) {
535                 pstring cmd;
536                 pstrcpy(cmd,lp_rootpreexec(SNUM(conn)));
537                 standard_sub_conn(conn,cmd);
538                 DEBUG(5,("cmd=%s\n",cmd));
539                 ret = smbrun(cmd,NULL,False);
540                 if (ret != 0 && lp_rootpreexec_close(SNUM(conn))) {
541                         DEBUG(1,("preexec gave %d - failing connection\n", ret));
542                         conn_free(conn);
543                         *ecode = ERRsrverror;
544                         return NULL;
545                 }
546         }
547         
548         if (!become_user(conn, conn->vuid)) {
549                 DEBUG(0,("Can't become connected user!\n"));
550                 yield_connection(conn,
551                                  lp_servicename(SNUM(conn)),
552                                  lp_max_connections(SNUM(conn)));
553                 conn_free(conn);
554                 *ecode = ERRbadpw;
555                 return NULL;
556         }
557         
558         if (vfs_ChDir(conn,conn->connectpath) != 0) {
559                 DEBUG(0,("%s (%s) Can't change directory to %s (%s)\n",
560                          remote_machine, conn->client_address,
561                          conn->connectpath,strerror(errno)));
562                 unbecome_user();
563                 yield_connection(conn,
564                                  lp_servicename(SNUM(conn)),
565                                  lp_max_connections(SNUM(conn)));
566                 conn_free(conn);
567                 *ecode = ERRnosuchshare;
568                 return NULL;
569         }
570         
571         string_set(&conn->origpath,conn->connectpath);
572         
573 #if SOFTLINK_OPTIMISATION
574         /* resolve any soft links early */
575         {
576                 pstring s;
577                 pstrcpy(s,conn->connectpath);
578                 vfs_GetWd(conn,s);
579                 string_set(&conn->connectpath,s);
580                 vfs_ChDir(conn,conn->connectpath);
581         }
582 #endif
583         
584         add_session_user(user);
585                 
586         /* execute any "preexec = " line */
587         if (*lp_preexec(SNUM(conn))) {
588                 pstring cmd;
589                 pstrcpy(cmd,lp_preexec(SNUM(conn)));
590                 standard_sub_conn(conn,cmd);
591                 ret = smbrun(cmd,NULL,False);
592                 if (ret != 0 && lp_preexec_close(SNUM(conn))) {
593                         DEBUG(1,("preexec gave %d - failing connection\n", ret));
594                         conn_free(conn);
595                         *ecode = ERRsrverror;
596                         return NULL;
597                 }
598         }
599
600         /*
601          * Print out the 'connected as' stuff here as we need
602          * to know the effective uid and gid we will be using.
603          */
604
605         if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
606                 dbgtext( "%s (%s) ", remote_machine, conn->client_address );
607                 dbgtext( "connect to service %s ", lp_servicename(SNUM(conn)) );
608                 dbgtext( "as user %s ", user );
609                 dbgtext( "(uid=%d, gid=%d) ", (int)geteuid(), (int)getegid() );
610                 dbgtext( "(pid %d)\n", (int)sys_getpid() );
611         }
612         
613         /* we've finished with the sensitive stuff */
614         unbecome_user();
615         
616         /* Add veto/hide lists */
617         if (!IS_IPC(conn) && !IS_PRINT(conn)) {
618                 set_namearray( &conn->veto_list, lp_veto_files(SNUM(conn)));
619                 set_namearray( &conn->hide_list, lp_hide_files(SNUM(conn)));
620                 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(SNUM(conn)));
621         }
622         
623         /* Invoke VFS make connection hook */
624
625         if (conn->vfs_ops.connect) {
626                 if (conn->vfs_ops.connect(conn, service, user) < 0)
627                         return NULL;
628         }
629             
630         return(conn);
631 }
632
633
634 /****************************************************************************
635 close a cnum
636 ****************************************************************************/
637 void close_cnum(connection_struct *conn, uint16 vuid)
638 {
639         DirCacheFlush(SNUM(conn));
640
641         unbecome_user();
642
643         DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
644                                  remote_machine,conn->client_address,
645                                  lp_servicename(SNUM(conn))));
646
647         if (conn->vfs_ops.disconnect != NULL) {
648
649             /* Call VFS disconnect hook */
650             
651             conn->vfs_ops.disconnect(conn);
652             
653         }
654
655         yield_connection(conn,
656                          lp_servicename(SNUM(conn)),
657                          lp_max_connections(SNUM(conn)));
658
659         file_close_conn(conn);
660         dptr_closecnum(conn);
661
662         /* execute any "postexec = " line */
663         if (*lp_postexec(SNUM(conn)) && 
664             become_user(conn, vuid))  {
665                 pstring cmd;
666                 pstrcpy(cmd,lp_postexec(SNUM(conn)));
667                 standard_sub_conn(conn,cmd);
668                 smbrun(cmd,NULL,False);
669                 unbecome_user();
670         }
671
672         unbecome_user();
673         /* execute any "root postexec = " line */
674         if (*lp_rootpostexec(SNUM(conn)))  {
675                 pstring cmd;
676                 pstrcpy(cmd,lp_rootpostexec(SNUM(conn)));
677                 standard_sub_conn(conn,cmd);
678                 smbrun(cmd,NULL,False);
679         }
680         conn_free(conn);
681 }