r925: add changes frpm trunk (r841 and r842) -- enable background queue update proces...
[tprouty/samba.git] / source / smbd / server.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Andrew Tridgell                1992-1998
5    Copyright (C) Martin Pool                    2002
6    Copyright (C) Jelmer Vernooij                2002-2003
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 static int am_parent = 1;
26
27 /* the last message the was processed */
28 int last_message = -1;
29
30 /* a useful macro to debug the last message processed */
31 #define LAST_MESSAGE() smb_fn_name(last_message)
32
33 extern pstring user_socket_options;
34 extern SIG_ATOMIC_T got_sig_term;
35 extern SIG_ATOMIC_T reload_after_sighup;
36
37 #ifdef WITH_DFS
38 extern int dcelogin_atmost_once;
39 #endif /* WITH_DFS */
40
41 /* really we should have a top level context structure that has the
42    client file descriptor as an element. That would require a major rewrite :(
43
44    the following 2 functions are an alternative - they make the file
45    descriptor private to smbd
46  */
47 static int server_fd = -1;
48
49 int smbd_server_fd(void)
50 {
51         return server_fd;
52 }
53
54 static void smbd_set_server_fd(int fd)
55 {
56         server_fd = fd;
57         client_setfd(fd);
58 }
59
60 /****************************************************************************
61  Terminate signal.
62 ****************************************************************************/
63
64 static void sig_term(void)
65 {
66         got_sig_term = 1;
67         sys_select_signal();
68 }
69
70 /****************************************************************************
71  Catch a sighup.
72 ****************************************************************************/
73
74 static void sig_hup(int sig)
75 {
76         reload_after_sighup = 1;
77         sys_select_signal();
78 }
79
80 /****************************************************************************
81   Send a SIGTERM to our process group.
82 *****************************************************************************/
83
84 static void  killkids(void)
85 {
86         if(am_parent) kill(0,SIGTERM);
87 }
88
89 /****************************************************************************
90  Process a sam sync message - not sure whether to do this here or
91  somewhere else.
92 ****************************************************************************/
93
94 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
95                          void *UNUSED(buf), size_t UNUSED(len))
96 {
97         DEBUG(10, ("** sam sync message received, ignoring\n"));
98 }
99
100 /****************************************************************************
101  Process a sam sync replicate message - not sure whether to do this here or
102  somewhere else.
103 ****************************************************************************/
104
105 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
106 {
107         uint32 low_serial;
108
109         if (len != sizeof(uint32))
110                 return;
111
112         low_serial = *((uint32 *)buf);
113
114         DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
115                   low_serial));
116 }
117
118 /****************************************************************************
119  Open the socket communication - inetd.
120 ****************************************************************************/
121
122 static BOOL open_sockets_inetd(void)
123 {
124         /* Started from inetd. fd 0 is the socket. */
125         /* We will abort gracefully when the client or remote system 
126            goes away */
127         smbd_set_server_fd(dup(0));
128         
129         /* close our standard file descriptors */
130         close_low_fds(False); /* Don't close stderr */
131         
132         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
133         set_socket_options(smbd_server_fd(), user_socket_options);
134
135         return True;
136 }
137
138 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
139 {
140         exit_server("Got a SHUTDOWN message");
141 }
142
143
144 /****************************************************************************
145  Have we reached the process limit ?
146 ****************************************************************************/
147
148 static BOOL allowable_number_of_smbd_processes(void)
149 {
150         int max_processes = lp_max_smbd_processes();
151
152         if (!max_processes)
153                 return True;
154
155         {
156                 TDB_CONTEXT *tdb = conn_tdb_ctx();
157                 int32 val;
158                 if (!tdb) {
159                         DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
160                         return False;
161                 }
162
163                 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
164                 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
165                         DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
166                                 tdb_errorstr(tdb) ));
167                         return False;
168                 }
169                 if (val > max_processes) {
170                         DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
171                                 val, max_processes ));
172                         return False;
173                 }
174         }
175         return True;
176 }
177
178 /****************************************************************************
179  Open the socket communication.
180 ****************************************************************************/
181
182 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
183 {
184         int num_interfaces = iface_count();
185         int num_sockets = 0;
186         int fd_listenset[FD_SETSIZE];
187         fd_set listen_set;
188         int s;
189         int i;
190         char *ports;
191
192         if (!is_daemon) {
193                 return open_sockets_inetd();
194         }
195
196                 
197 #ifdef HAVE_ATEXIT
198         {
199                 static int atexit_set;
200                 if(atexit_set == 0) {
201                         atexit_set=1;
202                         atexit(killkids);
203                 }
204         }
205 #endif
206
207         /* Stop zombies */
208         CatchChild();
209                                 
210         FD_ZERO(&listen_set);
211
212         /* use a reasonable default set of ports - listing on 445 and 139 */
213         if (!smb_ports) {
214                 ports = lp_smb_ports();
215                 if (!ports || !*ports) {
216                         ports = smb_xstrdup(SMB_PORTS);
217                 } else {
218                         ports = smb_xstrdup(ports);
219                 }
220         } else {
221                 ports = smb_xstrdup(smb_ports);
222         }
223
224         if (lp_interfaces() && lp_bind_interfaces_only()) {
225                 /* We have been given an interfaces line, and been 
226                    told to only bind to those interfaces. Create a
227                    socket per interface and bind to only these.
228                 */
229                 
230                 /* Now open a listen socket for each of the
231                    interfaces. */
232                 for(i = 0; i < num_interfaces; i++) {
233                         struct in_addr *ifip = iface_n_ip(i);
234                         fstring tok;
235                         const char *ptr;
236
237                         if(ifip == NULL) {
238                                 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
239                                 continue;
240                         }
241
242                         for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
243                                 unsigned port = atoi(tok);
244                                 if (port == 0) continue;
245                                 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
246                                 if(s == -1)
247                                         return False;
248
249                                 /* ready to listen */
250                                 set_socket_options(s,"SO_KEEPALIVE"); 
251                                 set_socket_options(s,user_socket_options);
252      
253                                 /* Set server socket to non-blocking for the accept. */
254                                 set_blocking(s,False); 
255  
256                                 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
257                                         DEBUG(0,("listen: %s\n",strerror(errno)));
258                                         close(s);
259                                         return False;
260                                 }
261                                 FD_SET(s,&listen_set);
262
263                                 num_sockets++;
264                                 if (num_sockets >= FD_SETSIZE) {
265                                         DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
266                                         return False;
267                                 }
268                         }
269                 }
270         } else {
271                 /* Just bind to 0.0.0.0 - accept connections
272                    from anywhere. */
273
274                 fstring tok;
275                 const char *ptr;
276
277                 num_interfaces = 1;
278                 
279                 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
280                         unsigned port = atoi(tok);
281                         if (port == 0) continue;
282                         /* open an incoming socket */
283                         s = open_socket_in(SOCK_STREAM, port, 0,
284                                            interpret_addr(lp_socket_address()),True);
285                         if (s == -1)
286                                 return(False);
287                 
288                         /* ready to listen */
289                         set_socket_options(s,"SO_KEEPALIVE"); 
290                         set_socket_options(s,user_socket_options);
291                         
292                         /* Set server socket to non-blocking for the accept. */
293                         set_blocking(s,False); 
294  
295                         if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
296                                 DEBUG(0,("open_sockets_smbd: listen: %s\n",
297                                          strerror(errno)));
298                                 close(s);
299                                 return False;
300                         }
301
302                         fd_listenset[num_sockets] = s;
303                         FD_SET(s,&listen_set);
304
305                         num_sockets++;
306
307                         if (num_sockets >= FD_SETSIZE) {
308                                 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
309                                 return False;
310                         }
311                 }
312         } 
313
314         SAFE_FREE(ports);
315
316         /* Listen to messages */
317
318         message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
319         message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
320         message_register(MSG_SHUTDOWN, msg_exit_server);
321
322         /* now accept incoming connections - forking a new process
323            for each incoming connection */
324         DEBUG(2,("waiting for a connection\n"));
325         while (1) {
326                 fd_set lfds;
327                 int num;
328                 
329                 /* Free up temporary memory from the main smbd. */
330                 lp_talloc_free();
331
332                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
333                 message_dispatch();
334
335                 memcpy((char *)&lfds, (char *)&listen_set, 
336                        sizeof(listen_set));
337                 
338                 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
339                 
340                 if (num == -1 && errno == EINTR) {
341                         if (got_sig_term) {
342                                 exit_server("Caught TERM signal");
343                         }
344
345                         /* check for sighup processing */
346                         if (reload_after_sighup) {
347                                 change_to_root_user();
348                                 DEBUG(1,("Reloading services after SIGHUP\n"));
349                                 reload_services(False);
350                                 reload_after_sighup = 0;
351                         }
352
353                         continue;
354                 }
355                 
356                 /* check if we need to reload services */
357                 check_reload(time(NULL));
358
359                 /* Find the sockets that are read-ready -
360                    accept on these. */
361                 for( ; num > 0; num--) {
362                         struct sockaddr addr;
363                         socklen_t in_addrlen = sizeof(addr);
364
365                         s = -1;
366                         for(i = 0; i < num_sockets; i++) {
367                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
368                                         s = fd_listenset[i];
369                                         /* Clear this so we don't look
370                                            at it again. */
371                                         FD_CLR(fd_listenset[i],&lfds);
372                                         break;
373                                 }
374                         }
375
376                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
377                         
378                         if (smbd_server_fd() == -1 && errno == EINTR)
379                                 continue;
380                         
381                         if (smbd_server_fd() == -1) {
382                                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
383                                          strerror(errno)));
384                                 continue;
385                         }
386
387                         /* Ensure child is set to blocking mode */
388                         set_blocking(smbd_server_fd(),True);
389
390                         if (smbd_server_fd() != -1 && interactive)
391                                 return True;
392                         
393                         if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
394                                 /* Child code ... */
395                                 
396                                 /* close the listening socket(s) */
397                                 for(i = 0; i < num_sockets; i++)
398                                         close(fd_listenset[i]);
399                                 
400                                 /* close our standard file
401                                    descriptors */
402                                 close_low_fds(False);
403                                 am_parent = 0;
404                                 
405                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
406                                 set_socket_options(smbd_server_fd(),user_socket_options);
407                                 
408                                 /* this is needed so that we get decent entries
409                                    in smbstatus for port 445 connects */
410                                 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
411                                 
412                                 /* Reset global variables in util.c so
413                                    that client substitutions will be
414                                    done correctly in the process.  */
415                                 reset_globals_after_fork();
416
417                                 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
418                                 if (tdb_reopen_all() == -1) {
419                                         DEBUG(0,("tdb_reopen_all failed.\n"));
420                                         smb_panic("tdb_reopen_all failed.");
421                                 }
422
423                                 return True; 
424                         }
425                         /* The parent doesn't need this socket */
426                         close(smbd_server_fd()); 
427
428                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
429                                 Clear the closed fd info out of server_fd --
430                                 and more importantly, out of client_fd in
431                                 util_sock.c, to avoid a possible
432                                 getpeername failure if we reopen the logs
433                                 and use %I in the filename.
434                         */
435
436                         smbd_set_server_fd(-1);
437
438                         /* Force parent to check log size after
439                          * spawning child.  Fix from
440                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
441                          * parent smbd will log to logserver.smb.  It
442                          * writes only two messages for each child
443                          * started/finished. But each child writes,
444                          * say, 50 messages also in logserver.smb,
445                          * begining with the debug_count of the
446                          * parent, before the child opens its own log
447                          * file logserver.client. In a worst case
448                          * scenario the size of logserver.smb would be
449                          * checked after about 50*50=2500 messages
450                          * (ca. 100kb).
451                          * */
452                         force_check_log_size();
453  
454                 } /* end for num */
455         } /* end while 1 */
456
457 /* NOTREACHED   return True; */
458 }
459
460 /****************************************************************************
461  Reload the services file.
462 **************************************************************************/
463
464 BOOL reload_services(BOOL test)
465 {
466         BOOL ret;
467         
468         if (lp_loaded()) {
469                 pstring fname;
470                 pstrcpy(fname,lp_configfile());
471                 if (file_exist(fname, NULL) &&
472                     !strcsequal(fname, dyn_CONFIGFILE)) {
473                         pstrcpy(dyn_CONFIGFILE, fname);
474                         test = False;
475                 }
476         }
477
478         reopen_logs();
479
480         if (test && !lp_file_list_changed())
481                 return(True);
482
483         lp_killunused(conn_snum_used);
484         
485         ret = lp_load(dyn_CONFIGFILE, False, False, True);
486
487         load_printers();
488
489         /* perhaps the config filename is now set */
490         if (!test)
491                 reload_services(True);
492
493         reopen_logs();
494
495         load_interfaces();
496
497         {
498                 if (smbd_server_fd() != -1) {      
499                         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
500                         set_socket_options(smbd_server_fd(), user_socket_options);
501                 }
502         }
503
504         mangle_reset_cache();
505         reset_stat_cache();
506
507         /* this forces service parameters to be flushed */
508         set_current_service(NULL,True);
509
510         return(ret);
511 }
512
513
514 #if DUMP_CORE
515 /*******************************************************************
516 prepare to dump a core file - carefully!
517 ********************************************************************/
518 static BOOL dump_core(void)
519 {
520         char *p;
521         pstring dname;
522         
523         pstrcpy(dname,lp_logfile());
524         if ((p=strrchr_m(dname,'/'))) *p=0;
525         pstrcat(dname,"/corefiles");
526         mkdir(dname,0700);
527         sys_chown(dname,getuid(),getgid());
528         chmod(dname,0700);
529         if (chdir(dname)) return(False);
530         umask(~(0700));
531
532 #ifdef HAVE_GETRLIMIT
533 #ifdef RLIMIT_CORE
534         {
535                 struct rlimit rlp;
536                 getrlimit(RLIMIT_CORE, &rlp);
537                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
538                 setrlimit(RLIMIT_CORE, &rlp);
539                 getrlimit(RLIMIT_CORE, &rlp);
540                 DEBUG(3,("Core limits now %d %d\n",
541                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
542         }
543 #endif
544 #endif
545
546
547         DEBUG(0,("Dumping core in %s\n", dname));
548         /* Ensure we don't have a signal handler for abort. */
549 #ifdef SIGABRT
550         CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
551 #endif
552         abort();
553         return(True);
554 }
555 #endif
556
557 /****************************************************************************
558  Exit the server.
559 ****************************************************************************/
560
561 void exit_server(const char *reason)
562 {
563         static int firsttime=1;
564         extern char *last_inbuf;
565         extern struct auth_context *negprot_global_auth_context;
566
567         if (!firsttime)
568                 exit(0);
569         firsttime = 0;
570
571         change_to_root_user();
572         DEBUG(2,("Closing connections\n"));
573
574         if (negprot_global_auth_context) {
575                 (negprot_global_auth_context->free)(&negprot_global_auth_context);
576         }
577
578         conn_close_all();
579
580         invalidate_all_vuids();
581
582         print_notify_send_messages(3); /* 3 second timeout. */
583
584         /* run all registered exit events */
585         smb_run_exit_events();
586
587         /* delete our entry in the connections database. */
588         yield_connection(NULL,"");
589
590         respond_to_all_remaining_local_messages();
591         decrement_smbd_process_count();
592
593 #ifdef WITH_DFS
594         if (dcelogin_atmost_once) {
595                 dfs_unlogin();
596         }
597 #endif
598
599         if (!reason) {   
600                 int oldlevel = DEBUGLEVEL;
601                 DEBUGLEVEL = 10;
602                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
603                 if (last_inbuf)
604                         show_msg(last_inbuf);
605                 DEBUGLEVEL = oldlevel;
606                 DEBUG(0,("===============================================================\n"));
607 #if DUMP_CORE
608                 if (dump_core()) return;
609 #endif
610         }    
611
612         locking_end();
613         printing_end();
614
615         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
616         exit(0);
617 }
618
619 /****************************************************************************
620  Initialise connect, service and file structs.
621 ****************************************************************************/
622
623 static BOOL init_structs(void )
624 {
625         /*
626          * Set the machine NETBIOS name if not already
627          * set from the config file.
628          */
629
630         if (!init_names())
631                 return False;
632
633         conn_init();
634
635         file_init();
636
637         /* for RPC pipes */
638         init_rpc_pipe_hnd();
639
640         init_dptrs();
641
642         secrets_init();
643
644         return True;
645 }
646
647 /****************************************************************************
648  main program.
649 ****************************************************************************/
650
651 /* Declare prototype for build_options() to avoid having to run it through
652    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
653    prototype generation system is too complicated. */
654
655 void build_options(BOOL screen);
656
657  int main(int argc,const char *argv[])
658 {
659         /* shall I run as a daemon */
660         static BOOL is_daemon = False;
661         static BOOL interactive = False;
662         static BOOL Fork = True;
663         static BOOL log_stdout = False;
664         static char *ports = NULL;
665         int opt;
666         poptContext pc;
667
668         struct poptOption long_options[] = {
669                 POPT_AUTOHELP
670         {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
671         {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
672         {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
673         {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
674         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
675         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
676         POPT_COMMON_SAMBA
677         { NULL }
678         };
679
680 #ifdef HAVE_SET_AUTH_PARAMETERS
681         set_auth_parameters(argc,argv);
682 #endif
683
684         pc = poptGetContext("smbd", argc, argv, long_options, 0);
685         
686         while((opt = poptGetNextOpt(pc)) != -1) {
687                 switch (opt)  {
688                 case 'b':
689                         build_options(True); /* Display output to screen as well as debug */ 
690                         exit(0);
691                         break;
692                 }
693         }
694
695         poptFreeContext(pc);
696
697 #ifdef HAVE_SETLUID
698         /* needed for SecureWare on SCO */
699         setluid(0);
700 #endif
701
702         sec_init();
703
704         load_case_tables();
705
706         set_remote_machine_name("smbd", False);
707
708         if (interactive) {
709                 Fork = False;
710                 log_stdout = True;
711         }
712
713         if (log_stdout && Fork) {
714                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
715                 exit(1);
716         }
717
718         setup_logging(argv[0],log_stdout);
719
720         /* we want to re-seed early to prevent time delays causing
721            client problems at a later date. (tridge) */
722         generate_random_buffer(NULL, 0, False);
723
724         /* make absolutely sure we run as root - to handle cases where people
725            are crazy enough to have it setuid */
726
727         gain_root_privilege();
728         gain_root_group_privilege();
729
730         fault_setup((void (*)(void *))exit_server);
731         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
732         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
733         
734         /* we are never interested in SIGPIPE */
735         BlockSignals(True,SIGPIPE);
736
737 #if defined(SIGFPE)
738         /* we are never interested in SIGFPE */
739         BlockSignals(True,SIGFPE);
740 #endif
741
742 #if defined(SIGUSR2)
743         /* We are no longer interested in USR2 */
744         BlockSignals(True,SIGUSR2);
745 #endif
746
747         /* POSIX demands that signals are inherited. If the invoking process has
748          * these signals masked, we will have problems, as we won't recieve them. */
749         BlockSignals(False, SIGHUP);
750         BlockSignals(False, SIGUSR1);
751         BlockSignals(False, SIGTERM);
752
753         /* we want total control over the permissions on created files,
754            so set our umask to 0 */
755         umask(0);
756
757         init_sec_ctx();
758
759         reopen_logs();
760
761         DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
762         DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2004\n"));
763
764         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
765                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
766
767         /* Output the build options to the debug log */ 
768         build_options(False);
769
770         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
771                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
772                 exit(1);
773         }
774
775         /*
776          * Do this before reload_services.
777          */
778
779         if (!reload_services(False))
780                 return(-1);     
781
782         init_structs();
783
784 #ifdef WITH_PROFILE
785         if (!profile_setup(False)) {
786                 DEBUG(0,("ERROR: failed to setup profiling\n"));
787                 return -1;
788         }
789 #endif
790
791         DEBUG(3,( "loaded services\n"));
792
793         if (!is_daemon && !is_a_socket(0)) {
794                 if (!interactive)
795                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
796
797                 /*
798                  * Setting is_daemon here prevents us from eventually calling
799                  * the open_sockets_inetd()
800                  */
801
802                 is_daemon = True;
803         }
804
805         if (is_daemon && !interactive) {
806                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
807                 become_daemon(Fork);
808         }
809
810 #if HAVE_SETPGID
811         /*
812          * If we're interactive we want to set our own process group for
813          * signal management.
814          */
815         if (interactive)
816                 setpgid( (pid_t)0, (pid_t)0);
817 #endif
818
819         if (!directory_exist(lp_lockdir(), NULL))
820                 mkdir(lp_lockdir(), 0755);
821
822         if (is_daemon)
823                 pidfile_create("smbd");
824
825         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
826         if (!message_init())
827                 exit(1);
828
829         if (!session_init())
830                 exit(1);
831
832         if (conn_tdb_ctx() == NULL)
833                 exit(1);
834
835         if (!locking_init(0))
836                 exit(1);
837
838         if (!share_info_db_init())
839                 exit(1);
840
841         namecache_enable();
842
843         if (!init_registry())
844                 exit(1);
845
846         if (!print_backend_init())
847                 exit(1);
848
849         /* Setup the main smbd so that we can get messages. */
850         claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
851
852         /* only start the background queue daemon if we are 
853            running as a daemon -- bad things will happen if
854            smbd is launched via inetd and we fork a copy of 
855            ourselves here */
856
857         if ( is_daemon )
858                 start_background_queue(); 
859
860         if (!open_sockets_smbd(is_daemon, interactive, ports))
861                 exit(1);
862
863         /*
864          * everything after this point is run after the fork()
865          */ 
866
867         /* Initialise the password backed before the global_sam_sid
868            to ensure that we fetch from ldap before we make a domain sid up */
869
870         if(!initialize_password_db(False))
871                 exit(1);
872
873         if(!get_global_sam_sid()) {
874                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
875                 exit(1);
876         }
877
878         static_init_rpc;
879
880         init_modules();
881
882         /* possibly reload the services file. */
883         reload_services(True);
884
885         if (!init_account_policy()) {
886                 DEBUG(0,("Could not open account policy tdb.\n"));
887                 exit(1);
888         }
889
890         if (*lp_rootdir()) {
891                 if (sys_chroot(lp_rootdir()) == 0)
892                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
893         }
894
895         /* Setup oplocks */
896         if (!init_oplocks())
897                 exit(1);
898         
899         /* Setup change notify */
900         if (!init_change_notify())
901                 exit(1);
902
903         /* re-initialise the timezone */
904         TimeInit();
905
906         /* register our message handlers */
907         message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
908
909         smbd_process();
910         
911         namecache_shutdown();
912         exit_server("normal exit");
913         return(0);
914 }