reload_services needs to be called prior to init_files but after
[samba.git] / source3 / 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 fstring global_sam_name;
29 extern pstring global_myname;
30
31 int am_parent = 1;
32
33 /* the last message the was processed */
34 int last_message = -1;
35
36 /* a useful macro to debug the last message processed */
37 #define LAST_MESSAGE() smb_fn_name(last_message)
38
39 extern pstring scope;
40 extern int DEBUGLEVEL;
41
42 extern pstring user_socket_options;
43
44 #ifdef WITH_DFS
45 extern int dcelogin_atmost_once;
46 #endif /* WITH_DFS */
47
48
49 extern fstring remote_machine;
50 extern pstring OriginalDir;
51 extern pstring myhostname;
52
53 /****************************************************************************
54   when exiting, take the whole family
55 ****************************************************************************/
56 static void *dflt_sig(void)
57 {
58         exit_server("caught signal");
59         return NULL;
60 }
61
62 /****************************************************************************
63   Send a SIGTERM to our process group.
64 *****************************************************************************/
65 static void  killkids(void)
66 {
67         if(am_parent) kill(0,SIGTERM);
68 }
69
70
71 /****************************************************************************
72   open the socket communication
73 ****************************************************************************/
74 static BOOL open_sockets_inetd(void)
75 {
76         extern int Client;
77
78         /* Started from inetd. fd 0 is the socket. */
79         /* We will abort gracefully when the client or remote system 
80            goes away */
81         Client = dup(0);
82         
83         /* close our standard file descriptors */
84         close_low_fds();
85         
86         set_socket_options(Client,"SO_KEEPALIVE");
87         set_socket_options(Client,user_socket_options);
88
89         return True;
90 }
91
92
93 /****************************************************************************
94   open the socket communication
95 ****************************************************************************/
96 static BOOL open_sockets(BOOL is_daemon,int port)
97 {
98         extern int Client;
99         int num_interfaces = iface_count();
100         int fd_listenset[FD_SETSIZE];
101         fd_set listen_set;
102         int s;
103         int i;
104
105         if (!is_daemon) {
106                 return open_sockets_inetd();
107         }
108
109                 
110 #ifdef HAVE_ATEXIT
111         {
112                 static int atexit_set;
113                 if(atexit_set == 0) {
114                         atexit_set=1;
115                         atexit(killkids);
116                 }
117         }
118 #endif
119
120         /* Stop zombies */
121         CatchChild();
122                 
123                 
124         FD_ZERO(&listen_set);
125
126         if(lp_interfaces() && lp_bind_interfaces_only()) {
127                 /* We have been given an interfaces line, and been 
128                    told to only bind to those interfaces. Create a
129                    socket per interface and bind to only these.
130                 */
131                 
132                 if(num_interfaces > FD_SETSIZE) {
133                         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
134 max can be %d\n", 
135                                  num_interfaces, FD_SETSIZE));
136                         return False;
137                 }
138                 
139                 /* Now open a listen socket for each of the
140                    interfaces. */
141                 for(i = 0; i < num_interfaces; i++) {
142                         struct in_addr *ifip = iface_n_ip(i);
143                         
144                         if(ifip == NULL) {
145                                 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
146                                 continue;
147                         }
148                         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
149                         if(s == -1)
150                                 return False;
151                                 /* ready to listen */
152                         if (listen(s, 5) == -1) {
153                                 DEBUG(0,("listen: %s\n",strerror(errno)));
154                                 close(s);
155                                 return False;
156                         }
157                         FD_SET(s,&listen_set);
158                 }
159         } else {
160                 /* Just bind to 0.0.0.0 - accept connections
161                    from anywhere. */
162                 num_interfaces = 1;
163                 
164                 /* open an incoming socket */
165                 s = open_socket_in(SOCK_STREAM, port, 0,
166                                    interpret_addr(lp_socket_address()));
167                 if (s == -1)
168                         return(False);
169                 
170                 /* ready to listen */
171                 if (listen(s, 5) == -1) {
172                         DEBUG(0,("open_sockets: listen: %s\n",
173                                  strerror(errno)));
174                         close(s);
175                         return False;
176                 }
177                 
178                 fd_listenset[0] = s;
179                 FD_SET(s,&listen_set);
180         } 
181
182         /* now accept incoming connections - forking a new process
183            for each incoming connection */
184         DEBUG(2,("waiting for a connection\n"));
185         while (1) {
186                 fd_set lfds;
187                 int num;
188                 
189                 memcpy((char *)&lfds, (char *)&listen_set, 
190                        sizeof(listen_set));
191                 
192                 num = sys_select(256,&lfds,NULL);
193                 
194                 if (num == -1 && errno == EINTR)
195                         continue;
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
286         if (lp_loaded()) {
287                 pstring fname;
288                 pstrcpy(fname,lp_configfile());
289                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
290                         pstrcpy(servicesf,fname);
291                         test = False;
292                 }
293         }
294
295         reopen_logs();
296
297         if (test && !lp_file_list_changed())
298                 return(True);
299
300         lp_killunused(conn_snum_used);
301
302         ret = lp_load(servicesf,False,False,True);
303
304         load_printers();
305
306         /* perhaps the config filename is now set */
307         if (!test)
308                 reload_services(True);
309
310         reopen_logs();
311
312         load_interfaces();
313
314         {
315                 extern int Client;
316                 if (Client != -1) {      
317                         set_socket_options(Client,"SO_KEEPALIVE");
318                         set_socket_options(Client,user_socket_options);
319                 }
320         }
321
322         reset_mangled_cache();
323
324         /* this forces service parameters to be flushed */
325         become_service(NULL,True);
326
327         return(ret);
328 }
329
330
331
332 /****************************************************************************
333 this prevents zombie child processes
334 ****************************************************************************/
335 BOOL reload_after_sighup = False;
336
337 static void sig_hup(int sig)
338 {
339         BlockSignals(True,SIGHUP);
340         DEBUG(0,("Got SIGHUP\n"));
341
342         /*
343          * Fix from <branko.cibej@hermes.si> here.
344          * We used to reload in the signal handler - this
345          * is a *BIG* no-no.
346          */
347
348         reload_after_sighup = True;
349         BlockSignals(False,SIGHUP);
350 }
351
352
353
354 #if DUMP_CORE
355 /*******************************************************************
356 prepare to dump a core file - carefully!
357 ********************************************************************/
358 static BOOL dump_core(void)
359 {
360         char *p;
361         pstring dname;
362         pstrcpy(dname,debugf);
363         if ((p=strrchr(dname,'/'))) *p=0;
364         pstrcat(dname,"/corefiles");
365         mkdir(dname,0700);
366         sys_chown(dname,getuid(),getgid());
367         chmod(dname,0700);
368         if (chdir(dname)) return(False);
369         umask(~(0700));
370
371 #ifdef HAVE_GETRLIMIT
372 #ifdef RLIMIT_CORE
373         {
374                 struct rlimit rlp;
375                 getrlimit(RLIMIT_CORE, &rlp);
376                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
377                 setrlimit(RLIMIT_CORE, &rlp);
378                 getrlimit(RLIMIT_CORE, &rlp);
379                 DEBUG(3,("Core limits now %d %d\n",
380                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
381         }
382 #endif
383 #endif
384
385
386         DEBUG(0,("Dumping core in %s\n",dname));
387         abort();
388         return(True);
389 }
390 #endif
391
392
393 /****************************************************************************
394 exit the server
395 ****************************************************************************/
396 void exit_server(char *reason)
397 {
398         static int firsttime=1;
399         extern char *last_inbuf;
400
401
402         if (!firsttime) exit(0);
403         firsttime = 0;
404
405         unbecome_user();
406         DEBUG(2,("Closing connections\n"));
407
408         conn_close_all();
409
410 #ifdef WITH_DFS
411         if (dcelogin_atmost_once) {
412                 dfs_unlogin();
413         }
414 #endif
415
416         if (!reason) {   
417                 int oldlevel = DEBUGLEVEL;
418                 DEBUGLEVEL = 10;
419                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
420                 if (last_inbuf)
421                         show_msg(last_inbuf);
422                 DEBUGLEVEL = oldlevel;
423                 DEBUG(0,("===============================================================\n"));
424 #if DUMP_CORE
425                 if (dump_core()) return;
426 #endif
427         }    
428
429         locking_end();
430
431         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
432 #ifdef MEM_MAN
433         {
434                 extern FILE *dbf;
435                 smb_mem_write_verbose(dbf);
436                 dbgflush();
437         }
438 #endif
439         exit(0);
440 }
441
442
443
444 /****************************************************************************
445   initialise connect, service and file structs
446 ****************************************************************************/
447 static void init_structs(void)
448 {
449         conn_init();
450         file_init();
451         init_rpc_pipe_hnd(); /* for RPC pipes */
452         init_lsa_policy_hnd(); /* for LSA handles */
453         init_dptrs();
454 }
455
456 /****************************************************************************
457 usage on the program
458 ****************************************************************************/
459 static void usage(char *pname)
460 {
461         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
462
463         printf("Usage: %s [-D] [-p port] [-d debuglevel] ", pname);
464         printf("[-l log basename] [-s services file]\n" );
465         printf("Version %s\n",VERSION);
466         printf("\t-D                    become a daemon\n");
467         printf("\t-p port               listen on the specified port\n");
468         printf("\t-d debuglevel         set the debuglevel\n");
469         printf("\t-l log basename.      Basename for log/debug files\n");
470         printf("\t-s services file.     Filename of services file\n");
471         printf("\t-P                    passive only\n");
472         printf("\t-a                    append to log file (default)\n");
473         printf("\t-o                    overwrite log file, don't append\n");
474         printf("\t-i scope              NetBIOS scope to use (default none)\n");
475         printf("\n");
476 }
477
478
479 /****************************************************************************
480   main program
481 ****************************************************************************/
482  int main(int argc,char *argv[])
483 {
484         extern BOOL append_log;
485         /* shall I run as a daemon */
486         BOOL is_daemon = False;
487         int port = SMB_PORT;
488         int opt;
489         extern char *optarg;
490         
491 #ifdef HAVE_SET_AUTH_PARAMETERS
492         set_auth_parameters(argc,argv);
493 #endif
494
495 #ifdef HAVE_SETLUID
496         /* needed for SecureWare on SCO */
497         setluid(0);
498 #endif
499
500         append_log = True;
501
502         TimeInit();
503
504         pstrcpy(debugf,SMBLOGFILE);  
505
506         pstrcpy(remote_machine, "smb");
507
508         setup_logging(argv[0],False);
509
510         charset_initialise();
511
512         /* make absolutely sure we run as root - to handle cases where people
513            are crazy enough to have it setuid */
514 #ifdef HAVE_SETRESUID
515         setresuid(0,0,0);
516 #else
517         setuid(0);
518         seteuid(0);
519         setuid(0);
520         seteuid(0);
521 #endif
522
523         fault_setup((void (*)(void *))exit_server);
524         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
525
526         /* we are never interested in SIGPIPE */
527         BlockSignals(True,SIGPIPE);
528
529         /* we want total control over the permissions on created files,
530            so set our umask to 0 */
531         umask(0);
532
533         dos_GetWd(OriginalDir);
534
535         init_uid();
536
537         /* this is for people who can't start the program correctly */
538         while (argc > 1 && (*argv[1] != '-')) {
539                 argv++;
540                 argc--;
541         }
542
543         while ( EOF != (opt = getopt(argc, argv, "O:i:l:s:d:Dp:h?Paof:")) )
544                 switch (opt)  {
545                 case 'O':
546                         pstrcpy(user_socket_options,optarg);
547                         break;
548
549                 case 'i':
550                         pstrcpy(scope,optarg);
551                         break;
552
553                 case 'P':
554                         {
555                                 extern BOOL passive;
556                                 passive = True;
557                         }
558                         break;  
559
560                 case 's':
561                         pstrcpy(servicesf,optarg);
562                         break;
563
564                 case 'l':
565                         pstrcpy(debugf,optarg);
566                         break;
567
568                 case 'a':
569                         append_log = True;
570                         break;
571
572                 case 'o':
573                         append_log = False;
574                         break;
575
576                 case 'D':
577                         is_daemon = True;
578                         break;
579
580                 case 'd':
581                         if (*optarg == 'A')
582                                 DEBUGLEVEL = 10000;
583                         else
584                                 DEBUGLEVEL = atoi(optarg);
585                         break;
586
587                 case 'p':
588                         port = atoi(optarg);
589                         break;
590
591                 case 'h':
592                 case '?':
593                         usage(argv[0]);
594                         exit(0);
595                         break;
596
597                 default:
598                         usage(argv[0]);
599                         exit(1);
600                 }
601
602         reopen_logs();
603
604         DEBUG(1,( "smbd version %s started.\n", VERSION));
605         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
606
607         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
608                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
609
610         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
611                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
612                 exit(1);
613         }
614
615         get_myname(myhostname,NULL);
616
617         if (!reload_services(False))
618                 return(-1);     
619
620         init_structs();
621         
622         /*
623          * Set the machine NETBIOS name if not already
624          * set from the config file.
625          */
626         if (!*global_myname)
627         {
628                 fstrcpy(global_myname, dns_to_netbios_name(myhostname));
629         }
630         strupper(global_myname);
631
632 #ifdef WITH_SSL
633         {
634                 extern BOOL sslEnabled;
635                 sslEnabled = lp_ssl_enabled();
636                 if(sslEnabled)
637                         sslutil_init(True);
638         }
639 #endif        /* WITH_SSL */
640
641         codepage_initialise(lp_client_code_page());
642
643         if (!pwdb_initialise(True))
644         {
645                 exit(1);
646         }
647
648         if(!initialise_sam_password_db())
649         {
650                 exit(1);
651         }
652
653         if(!initialise_passgrp_db())
654         {
655                 exit(1);
656         }
657
658         if(!initialise_group_db())
659         {
660                 exit(1);
661         }
662
663         if(!initialise_alias_db())
664         {
665                 exit(1);
666         }
667
668         if(!initialise_builtin_db())
669         {
670                 exit(1);
671         }
672
673         if (!get_member_domain_sid())
674         {
675                 DEBUG(0,("ERROR: Samba cannot obtain PDC SID from PDC(s) %s.\n",
676                           lp_passwordserver()));
677                 exit(1);
678         }
679
680         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
681         
682         /* Setup the signals that allow the debug log level
683            to by dynamically changed. */
684  
685         /* If we are using the malloc debug code we can't use
686            SIGUSR1 and SIGUSR2 to do debug level changes. */
687         
688 #ifndef MEM_MAN
689 #if defined(SIGUSR1)
690         CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
691 #endif /* SIGUSR1 */
692    
693 #if defined(SIGUSR2)
694         CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
695 #endif /* SIGUSR2 */
696 #endif /* MEM_MAN */
697
698         DEBUG(3,( "loaded services\n"));
699
700         if (!is_daemon && !is_a_socket(0)) {
701                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
702                 is_daemon = True;
703         }
704
705         if (is_daemon) {
706                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
707                 become_daemon();
708         }
709
710         check_kernel_oplocks();
711
712         if (!directory_exist(lp_lockdir(), NULL)) {
713                 mkdir(lp_lockdir(), 0755);
714         }
715
716         if (is_daemon) {
717                 pidfile_create("smbd");
718         }
719
720         if (!open_sockets(is_daemon,port))
721                 exit(1);
722
723         if (!locking_init(0))
724                 exit(1);
725
726         /* possibly reload the services file. */
727         reload_services(True);
728         
729         if (*lp_rootdir()) {
730                 if (sys_chroot(lp_rootdir()) == 0)
731                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
732         }
733
734         /* Setup the oplock IPC socket. */
735         if( !open_oplock_ipc() )
736                 exit(1);
737
738         smbd_process();
739         close_sockets();
740         
741         exit_server("normal exit");
742         return(0);
743 }