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