dded Microsoft Dfs services.
[import/samba-cvsimport.git] / source / smbd / server.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Main SMB server routines
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 #include "trans2.h"
24
25 pstring servicesf = CONFIGFILE;
26 extern pstring debugf;
27 extern fstring global_myworkgroup;
28 extern pstring global_myname;
29
30 int am_parent = 1;
31
32 /* the last message the was processed */
33 int last_message = -1;
34
35 /* a useful macro to debug the last message processed */
36 #define LAST_MESSAGE() smb_fn_name(last_message)
37
38 extern int DEBUGLEVEL;
39
40 extern pstring user_socket_options;
41
42 #ifdef WITH_DFS
43 extern int dcelogin_atmost_once;
44 #endif /* WITH_DFS */
45
46
47 extern fstring remote_machine;
48 extern pstring OriginalDir;
49
50 /****************************************************************************
51   when exiting, take the whole family
52 ****************************************************************************/
53 static void *dflt_sig(void)
54 {
55         exit_server("caught signal");
56         return NULL;
57 }
58
59 /****************************************************************************
60   Send a SIGTERM to our process group.
61 *****************************************************************************/
62 static void  killkids(void)
63 {
64         if(am_parent) kill(0,SIGTERM);
65 }
66
67
68 /****************************************************************************
69   open the socket communication
70 ****************************************************************************/
71 static BOOL open_sockets_inetd(void)
72 {
73         extern int Client;
74
75         /* Started from inetd. fd 0 is the socket. */
76         /* We will abort gracefully when the client or remote system 
77            goes away */
78         Client = dup(0);
79         
80         /* close our standard file descriptors */
81         close_low_fds();
82         
83         set_socket_options(Client,"SO_KEEPALIVE");
84         set_socket_options(Client,user_socket_options);
85
86         return True;
87 }
88
89
90 /****************************************************************************
91   open the socket communication
92 ****************************************************************************/
93 static BOOL open_sockets(BOOL is_daemon,int port)
94 {
95         extern int Client;
96         int num_interfaces = iface_count();
97         int fd_listenset[FD_SETSIZE];
98         fd_set listen_set;
99         int s;
100         int i;
101
102         if (!is_daemon) {
103                 return open_sockets_inetd();
104         }
105
106                 
107 #ifdef HAVE_ATEXIT
108         {
109                 static int atexit_set;
110                 if(atexit_set == 0) {
111                         atexit_set=1;
112                         atexit(killkids);
113                 }
114         }
115 #endif
116
117         /* Stop zombies */
118         CatchChild();
119                 
120                 
121         FD_ZERO(&listen_set);
122
123         if(lp_interfaces() && lp_bind_interfaces_only()) {
124                 /* We have been given an interfaces line, and been 
125                    told to only bind to those interfaces. Create a
126                    socket per interface and bind to only these.
127                 */
128                 
129                 if(num_interfaces > FD_SETSIZE) {
130                         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
131 max can be %d\n", 
132                                  num_interfaces, FD_SETSIZE));
133                         return False;
134                 }
135                 
136                 /* Now open a listen socket for each of the
137                    interfaces. */
138                 for(i = 0; i < num_interfaces; i++) {
139                         struct in_addr *ifip = iface_n_ip(i);
140                         
141                         if(ifip == NULL) {
142                                 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
143                                 continue;
144                         }
145                         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
146                         if(s == -1)
147                                 return False;
148                                 /* ready to listen */
149                         if (listen(s, 5) == -1) {
150                                 DEBUG(0,("listen: %s\n",strerror(errno)));
151                                 close(s);
152                                 return False;
153                         }
154                         FD_SET(s,&listen_set);
155                 }
156         } else {
157                 /* Just bind to 0.0.0.0 - accept connections
158                    from anywhere. */
159                 num_interfaces = 1;
160                 
161                 /* open an incoming socket */
162                 s = open_socket_in(SOCK_STREAM, port, 0,
163                                    interpret_addr(lp_socket_address()),True);
164                 if (s == -1)
165                         return(False);
166                 
167                 /* ready to listen */
168                 if (listen(s, 5) == -1) {
169                         DEBUG(0,("open_sockets: listen: %s\n",
170                                  strerror(errno)));
171                         close(s);
172                         return False;
173                 }
174                 
175                 fd_listenset[0] = s;
176                 FD_SET(s,&listen_set);
177         } 
178
179         /* now accept incoming connections - forking a new process
180            for each incoming connection */
181         DEBUG(2,("waiting for a connection\n"));
182         while (1) {
183                 fd_set lfds;
184                 int num;
185                 
186                 memcpy((char *)&lfds, (char *)&listen_set, 
187                        sizeof(listen_set));
188                 
189                 num = sys_select(FD_SETSIZE,&lfds,NULL);
190                 
191                 if (num == -1 && errno == EINTR)
192                         continue;
193                 
194                 /* check if we need to reload services */
195                 check_reload(time(NULL));
196
197                 /* Find the sockets that are read-ready -
198                    accept on these. */
199                 for( ; num > 0; num--) {
200                         struct sockaddr addr;
201                         int in_addrlen = sizeof(addr);
202                         
203                         s = -1;
204                         for(i = 0; i < num_interfaces; i++) {
205                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
206                                         s = fd_listenset[i];
207                                         /* Clear this so we don't look
208                                            at it again. */
209                                         FD_CLR(fd_listenset[i],&lfds);
210                                         break;
211                                 }
212                         }
213
214                         Client = accept(s,&addr,&in_addrlen);
215                         
216                         if (Client == -1 && errno == EINTR)
217                                 continue;
218                         
219                         if (Client == -1) {
220                                 DEBUG(0,("open_sockets: accept: %s\n",
221                                          strerror(errno)));
222                                 continue;
223                         }
224                         
225                         if (Client != -1 && fork()==0) {
226                                 /* Child code ... */
227                                 
228                                 /* close the listening socket(s) */
229                                 for(i = 0; i < num_interfaces; i++)
230                                         close(fd_listenset[i]);
231                                 
232                                 /* close our standard file
233                                    descriptors */
234                                 close_low_fds();
235                                 am_parent = 0;
236                                 
237                                 set_socket_options(Client,"SO_KEEPALIVE");
238                                 set_socket_options(Client,user_socket_options);
239                                 
240                                 /* Reset global variables in util.c so
241                                    that client substitutions will be
242                                    done correctly in the process.  */
243                                 reset_globals_after_fork();
244
245                 /*
246                  * Ensure this child has kernel oplock
247                  * capabilities, but not it's children.
248                  */
249                 set_process_capability(KERNEL_OPLOCK_CAPABILITY, True);
250                 set_inherited_process_capability(KERNEL_OPLOCK_CAPABILITY, False);
251
252                                 return True; 
253                         }
254                         /* The parent doesn't need this socket */
255                         close(Client); 
256
257                         /* Force parent to check log size after
258                          * spawning child.  Fix from
259                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
260                          * parent smbd will log to logserver.smb.  It
261                          * writes only two messages for each child
262                          * started/finished. But each child writes,
263                          * say, 50 messages also in logserver.smb,
264                          * begining with the debug_count of the
265                          * parent, before the child opens its own log
266                          * file logserver.client. In a worst case
267                          * scenario the size of logserver.smb would be
268                          * checked after about 50*50=2500 messages
269                          * (ca. 100kb).
270                          * */
271                         force_check_log_size();
272  
273                 } /* end for num */
274         } /* end while 1 */
275
276 /* NOTREACHED   return True; */
277 }
278
279 /****************************************************************************
280   reload the services file
281   **************************************************************************/
282 BOOL reload_services(BOOL test)
283 {
284         BOOL ret;
285         int i=0;
286         
287         if (lp_loaded()) {
288                 pstring fname;
289                 pstrcpy(fname,lp_configfile());
290                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
291                         pstrcpy(servicesf,fname);
292                         test = False;
293                 }
294         }
295
296         reopen_logs();
297
298         if (test && !lp_file_list_changed())
299                 return(True);
300
301         lp_killunused(conn_snum_used);
302         
303         ret = lp_load(servicesf,False,False,True);
304
305         /* load the dfs maps of all the services having 
306            a dfs_map parameter 
307            we don't want to do this in lp_load because we want just the smbd
308            server to load up the dfs maps into msdfds.tdb. not nmbd, swat etc*/
309         load_dfsmaps();
310
311         load_printers();
312
313         /* perhaps the config filename is now set */
314         if (!test)
315                 reload_services(True);
316
317         reopen_logs();
318
319         load_interfaces();
320
321         {
322                 extern int Client;
323                 if (Client != -1) {      
324                         set_socket_options(Client,"SO_KEEPALIVE");
325                         set_socket_options(Client,user_socket_options);
326                 }
327         }
328
329         reset_mangled_cache();
330     reset_stat_cache();
331
332         /* this forces service parameters to be flushed */
333         become_service(NULL,True);
334
335         return(ret);
336 }
337
338
339
340 /****************************************************************************
341  Catch a sighup.
342 ****************************************************************************/
343
344 VOLATILE SIG_ATOMIC_T reload_after_sighup = False;
345
346 static void sig_hup(int sig)
347 {
348         BlockSignals(True,SIGHUP);
349         DEBUG(0,("Got SIGHUP\n"));
350
351         /*
352          * Fix from <branko.cibej@hermes.si> here.
353          * We used to reload in the signal handler - this
354          * is a *BIG* no-no.
355          */
356
357         reload_after_sighup = True;
358         BlockSignals(False,SIGHUP);
359 }
360
361
362
363 #if DUMP_CORE
364 /*******************************************************************
365 prepare to dump a core file - carefully!
366 ********************************************************************/
367 static BOOL dump_core(void)
368 {
369         char *p;
370         pstring dname;
371         pstrcpy(dname,debugf);
372         if ((p=strrchr(dname,'/'))) *p=0;
373         pstrcat(dname,"/corefiles");
374         mkdir(dname,0700);
375         sys_chown(dname,getuid(),getgid());
376         chmod(dname,0700);
377         if (chdir(dname)) return(False);
378         umask(~(0700));
379
380 #ifdef HAVE_GETRLIMIT
381 #ifdef RLIMIT_CORE
382         {
383                 struct rlimit rlp;
384                 getrlimit(RLIMIT_CORE, &rlp);
385                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
386                 setrlimit(RLIMIT_CORE, &rlp);
387                 getrlimit(RLIMIT_CORE, &rlp);
388                 DEBUG(3,("Core limits now %d %d\n",
389                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
390         }
391 #endif
392 #endif
393
394
395         DEBUG(0,("Dumping core in %s\n",dname));
396         abort();
397         return(True);
398 }
399 #endif
400
401
402 /****************************************************************************
403 exit the server
404 ****************************************************************************/
405 void exit_server(char *reason)
406 {
407         static int firsttime=1;
408         extern char *last_inbuf;
409
410
411         if (!firsttime) exit(0);
412         firsttime = 0;
413
414         unbecome_user();
415         DEBUG(2,("Closing connections\n"));
416
417         conn_close_all();
418
419     respond_to_all_remaining_local_messages();
420
421 #ifdef WITH_DFS
422         if (dcelogin_atmost_once) {
423                 dfs_unlogin();
424         }
425 #endif
426
427         if (!reason) {   
428                 int oldlevel = DEBUGLEVEL;
429                 DEBUGLEVEL = 10;
430                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
431                 if (last_inbuf)
432                         show_msg(last_inbuf);
433                 DEBUGLEVEL = oldlevel;
434                 DEBUG(0,("===============================================================\n"));
435 #if DUMP_CORE
436                 if (dump_core()) return;
437 #endif
438         }    
439
440         locking_end();
441 #ifdef MS_DFS
442         msdfs_end();
443 #endif
444
445         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
446         exit(0);
447 }
448
449
450
451 /****************************************************************************
452   initialise connect, service and file structs
453 ****************************************************************************/
454 static void init_structs(void )
455 {
456         /*
457          * Set the machine NETBIOS name if not already
458          * set from the config file.
459          */
460
461         if (!*global_myname) {
462                 char *p;
463                 fstrcpy( global_myname, myhostname() );
464                 p = strchr( global_myname, '.' );
465                 if (p) 
466                         *p = 0;
467         }
468
469         strupper( global_myname );
470
471         conn_init();
472
473         file_init();
474
475         /* for RPC pipes */
476         init_rpc_pipe_hnd();
477
478         /* for LSA handles */
479         init_lsa_policy_hnd();
480
481         /* for SPOOLSS handles */
482         init_printer_hnd();
483         
484         init_dptrs();
485 }
486
487 /****************************************************************************
488 usage on the program
489 ****************************************************************************/
490 static void usage(char *pname)
491 {
492
493         printf("Usage: %s [-DaoPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
494         printf("       [-O socket options] [-s services file]\n");
495         printf("\t-D                    Become a daemon\n");
496         printf("\t-a                    Append to log file (default)\n");
497         printf("\t-o                    Overwrite log file, don't append\n");
498         printf("\t-P                    Passive only\n");
499         printf("\t-h                    Print usage\n");
500         printf("\t-?                    Print usage\n");
501         printf("\t-V                    Print version\n");
502         printf("\t-d debuglevel         Set the debuglevel\n");
503         printf("\t-l log basename.      Basename for log/debug files\n");
504         printf("\t-p port               Listen on the specified port\n");
505         printf("\t-O socket options     Socket options\n");
506         printf("\t-s services file.     Filename of services file\n");
507         printf("\n");
508 }
509
510
511 /****************************************************************************
512   main program
513 ****************************************************************************/
514  int main(int argc,char *argv[])
515 {
516         fstring sam_name;
517
518         extern BOOL append_log;
519         /* shall I run as a daemon */
520         BOOL is_daemon = False;
521         BOOL specified_logfile = False;
522         int port = SMB_PORT;
523         int opt;
524         extern char *optarg;
525         
526 #ifdef HAVE_SET_AUTH_PARAMETERS
527         set_auth_parameters(argc,argv);
528 #endif
529
530         /* this is for people who can't start the program correctly */
531         while (argc > 1 && (*argv[1] != '-')) {
532                 argv++;
533                 argc--;
534         }
535
536         while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?VPaof:")) )
537                 switch (opt)  {
538                 case 'O':
539                         pstrcpy(user_socket_options,optarg);
540                         break;
541
542                 case 'P':
543                         {
544                                 extern BOOL passive;
545                                 passive = True;
546                         }
547                         break;  
548
549                 case 's':
550                         pstrcpy(servicesf,optarg);
551                         break;
552
553                 case 'l':
554                         specified_logfile = True;
555                         pstrcpy(debugf,optarg);
556                         break;
557
558                 case 'a':
559                         append_log = True;
560                         break;
561
562                 case 'o':
563                         append_log = False;
564                         break;
565
566                 case 'D':
567                         is_daemon = True;
568                         break;
569
570                 case 'd':
571                         if (*optarg == 'A')
572                                 DEBUGLEVEL = 10000;
573                         else
574                                 DEBUGLEVEL = atoi(optarg);
575                         break;
576
577                 case 'p':
578                         port = atoi(optarg);
579                         break;
580
581                 case 'h':
582                 case '?':
583                         usage(argv[0]);
584                         exit(0);
585                         break;
586
587                 case 'V':
588                         printf("Version %s\n",VERSION);
589                         exit(0);
590                         break;
591                 default:
592                         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
593                         usage(argv[0]);
594                         exit(1);
595                 }
596
597 #ifdef HAVE_SETLUID
598         /* needed for SecureWare on SCO */
599         setluid(0);
600 #endif
601
602         /*
603          * gain_root_privilege uses an assert than will cause a core
604          * dump if euid != 0. Ensure this is the case.
605          */
606
607         if(geteuid() != (uid_t)0) {
608                 fprintf(stderr, "%s: Version %s : Must have effective user id of zero to run.\n", argv[0], VERSION);
609                 exit(1);
610         }
611
612         append_log = True;
613
614         TimeInit();
615
616         if(!specified_logfile)
617                 pstrcpy(debugf,SMBLOGFILE);  
618
619         pstrcpy(remote_machine, "smb");
620
621         setup_logging(argv[0],False);
622
623         charset_initialise();
624
625         /* we want to re-seed early to prevent time delays causing
626            client problems at a later date. (tridge) */
627         generate_random_buffer(NULL, 0, False);
628
629         /* make absolutely sure we run as root - to handle cases where people
630            are crazy enough to have it setuid */
631
632         gain_root_privilege();
633         gain_root_group_privilege();
634
635         fault_setup((void (*)(void *))exit_server);
636         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
637
638         /* we are never interested in SIGPIPE */
639         BlockSignals(True,SIGPIPE);
640
641 #if defined(SIGFPE)
642         /* we are never interested in SIGFPE */
643         BlockSignals(True,SIGFPE);
644 #endif
645
646         /* we want total control over the permissions on created files,
647            so set our umask to 0 */
648         umask(0);
649
650         dos_GetWd(OriginalDir);
651
652         init_uid();
653
654         reopen_logs();
655
656         DEBUG(1,( "smbd version %s started.\n", VERSION));
657         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
658
659         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
660                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
661
662         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
663                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
664                 exit(1);
665         }
666
667         /*
668          * Do this before reload_services.
669          */
670
671         if (!reload_services(False))
672                 return(-1);     
673
674         init_structs();
675         
676 #ifdef WITH_PROFILE
677         if (!profile_setup(False)) {
678                 DEBUG(0,("ERROR: failed to setup profiling\n"));
679                 return -1;
680         }
681 #endif
682
683 #ifdef WITH_SSL
684         {
685                 extern BOOL sslEnabled;
686                 sslEnabled = lp_ssl_enabled();
687                 if(sslEnabled)
688                         sslutil_init(True);
689         }
690 #endif        /* WITH_SSL */
691
692         codepage_initialise(lp_client_code_page());
693
694         fstrcpy(global_myworkgroup, lp_workgroup());
695
696         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
697         
698         /* Setup the signals that allow the debug log level
699            to by dynamically changed. */
700  
701         /* If we are using the malloc debug code we can't use
702            SIGUSR1 and SIGUSR2 to do debug level changes. */
703         
704 #if defined(SIGUSR1)
705         CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
706 #endif /* SIGUSR1 */
707    
708 #if defined(SIGUSR2)
709         CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
710 #endif /* SIGUSR2 */
711
712         DEBUG(3,( "loaded services\n"));
713
714         if (!is_daemon && !is_a_socket(0)) {
715                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
716                 is_daemon = True;
717         }
718
719         if (is_daemon) {
720                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
721                 become_daemon();
722         }
723
724         check_kernel_oplocks();
725
726         if (!directory_exist(lp_lockdir(), NULL)) {
727                 mkdir(lp_lockdir(), 0755);
728         }
729
730         if (is_daemon) {
731                 pidfile_create("smbd");
732         }
733
734         if (!open_sockets(is_daemon,port))
735                 exit(1);
736
737         /*
738          * Note that this call should be done after the fork() call
739          * in open_sockets(), as some versions of the locking shared
740          * memory code register openers in a flat file.
741          */ 
742
743         if (!locking_init(0))
744                 exit(1);
745
746         if(!initialize_password_db())
747                 exit(1);
748
749         /* possibly reload the services file. */
750         reload_services(True);
751
752         /* obtain or create a SAM SID */
753         if (lp_domain_logons())
754         {
755                 fstrcpy(sam_name, global_myworkgroup);
756         }
757         else
758         {
759                 fstrcpy(sam_name, global_myname);
760         }
761
762         if(!pdb_generate_sam_sid(sam_name, NULL))
763         {
764                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
765                 exit(1);
766         }
767
768         if (*lp_rootdir()) {
769                 if (sys_chroot(lp_rootdir()) == 0)
770                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
771         }
772
773         /* Setup the oplock IPC socket. */
774         if( !open_oplock_ipc() )
775                 exit(1);
776
777         smbd_process();
778         close_sockets();
779         
780         exit_server("normal exit");
781         return(0);
782 }