Check for too many processes *before* the fork.
[nivanova/samba-autobuild/.git] / source3 / 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
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 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 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                                 if (listen(s, 5) == -1) {
254                                         DEBUG(0,("listen: %s\n",strerror(errno)));
255                                         close(s);
256                                         return False;
257                                 }
258                                 FD_SET(s,&listen_set);
259
260                                 num_sockets++;
261                                 if (num_sockets >= FD_SETSIZE) {
262                                         DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
263                                         return False;
264                                 }
265                         }
266                 }
267         } else {
268                 /* Just bind to 0.0.0.0 - accept connections
269                    from anywhere. */
270
271                 fstring tok;
272                 const char *ptr;
273
274                 num_interfaces = 1;
275                 
276                 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
277                         unsigned port = atoi(tok);
278                         if (port == 0) continue;
279                         /* open an incoming socket */
280                         s = open_socket_in(SOCK_STREAM, port, 0,
281                                            interpret_addr(lp_socket_address()),True);
282                         if (s == -1)
283                                 return(False);
284                 
285                         /* ready to listen */
286                         set_socket_options(s,"SO_KEEPALIVE"); 
287                         set_socket_options(s,user_socket_options);
288                         
289                         if (listen(s, 5) == -1) {
290                                 DEBUG(0,("open_sockets_smbd: listen: %s\n",
291                                          strerror(errno)));
292                                 close(s);
293                                 return False;
294                         }
295
296                         fd_listenset[num_sockets] = s;
297                         FD_SET(s,&listen_set);
298
299                         num_sockets++;
300
301                         if (num_sockets >= FD_SETSIZE) {
302                                 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
303                                 return False;
304                         }
305                 }
306         } 
307
308         SAFE_FREE(ports);
309
310         /* Listen to messages */
311
312         message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
313         message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
314         message_register(MSG_SHUTDOWN, msg_exit_server);
315
316         /* now accept incoming connections - forking a new process
317            for each incoming connection */
318         DEBUG(2,("waiting for a connection\n"));
319         while (1) {
320                 fd_set lfds;
321                 int num;
322                 
323                 /* Free up temporary memory from the main smbd. */
324                 lp_talloc_free();
325
326                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
327                 message_dispatch();
328
329                 memcpy((char *)&lfds, (char *)&listen_set, 
330                        sizeof(listen_set));
331                 
332                 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
333                 
334                 if (num == -1 && errno == EINTR) {
335                         if (got_sig_term) {
336                                 exit_server("Caught TERM signal");
337                         }
338
339                         /* check for sighup processing */
340                         if (reload_after_sighup) {
341                                 change_to_root_user();
342                                 DEBUG(1,("Reloading services after SIGHUP\n"));
343                                 reload_services(False);
344                                 reload_after_sighup = 0;
345                         }
346
347                         continue;
348                 }
349                 
350                 /* check if we need to reload services */
351                 check_reload(time(NULL));
352
353                 /* Find the sockets that are read-ready -
354                    accept on these. */
355                 for( ; num > 0; num--) {
356                         struct sockaddr addr;
357                         socklen_t in_addrlen = sizeof(addr);
358
359                         s = -1;
360                         for(i = 0; i < num_sockets; i++) {
361                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
362                                         s = fd_listenset[i];
363                                         /* Clear this so we don't look
364                                            at it again. */
365                                         FD_CLR(fd_listenset[i],&lfds);
366                                         break;
367                                 }
368                         }
369
370                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
371                         
372                         if (smbd_server_fd() == -1 && errno == EINTR)
373                                 continue;
374                         
375                         if (smbd_server_fd() == -1) {
376                                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
377                                          strerror(errno)));
378                                 continue;
379                         }
380
381                         if (smbd_server_fd() != -1 && interactive)
382                                 return True;
383                         
384                         if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
385                                 /* Child code ... */
386                                 
387                                 /* close the listening socket(s) */
388                                 for(i = 0; i < num_sockets; i++)
389                                         close(fd_listenset[i]);
390                                 
391                                 /* close our standard file
392                                    descriptors */
393                                 close_low_fds(False);
394                                 am_parent = 0;
395                                 
396                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
397                                 set_socket_options(smbd_server_fd(),user_socket_options);
398                                 
399                                 /* this is needed so that we get decent entries
400                                    in smbstatus for port 445 connects */
401                                 set_remote_machine_name(get_socket_addr(smbd_server_fd()));
402                                 
403                                 /* Reset global variables in util.c so
404                                    that client substitutions will be
405                                    done correctly in the process.  */
406                                 reset_globals_after_fork();
407
408                                 /* tdb needs special fork handling */
409                                 if (tdb_reopen_all() == -1) {
410                                         DEBUG(0,("tdb_reopen_all failed.\n"));
411                                         return False;
412                                 }
413
414                                 /* Load DSO's */
415                                 if(lp_modules()) 
416                                         smb_load_modules(lp_modules());
417
418                                 return True; 
419                         }
420                         /* The parent doesn't need this socket */
421                         close(smbd_server_fd()); 
422
423                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
424                                 Clear the closed fd info out of server_fd --
425                                 and more importantly, out of client_fd in
426                                 util_sock.c, to avoid a possible
427                                 getpeername failure if we reopen the logs
428                                 and use %I in the filename.
429                         */
430
431                         smbd_set_server_fd(-1);
432
433                         /* Force parent to check log size after
434                          * spawning child.  Fix from
435                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
436                          * parent smbd will log to logserver.smb.  It
437                          * writes only two messages for each child
438                          * started/finished. But each child writes,
439                          * say, 50 messages also in logserver.smb,
440                          * begining with the debug_count of the
441                          * parent, before the child opens its own log
442                          * file logserver.client. In a worst case
443                          * scenario the size of logserver.smb would be
444                          * checked after about 50*50=2500 messages
445                          * (ca. 100kb).
446                          * */
447                         force_check_log_size();
448  
449                 } /* end for num */
450         } /* end while 1 */
451
452 /* NOTREACHED   return True; */
453 }
454
455 /****************************************************************************
456  Reload the services file.
457 **************************************************************************/
458
459 BOOL reload_services(BOOL test)
460 {
461         BOOL ret;
462         
463         if (lp_loaded()) {
464                 pstring fname;
465                 pstrcpy(fname,lp_configfile());
466                 if (file_exist(fname, NULL) &&
467                     !strcsequal(fname, dyn_CONFIGFILE)) {
468                         pstrcpy(dyn_CONFIGFILE, fname);
469                         test = False;
470                 }
471         }
472
473         reopen_logs();
474
475         if (test && !lp_file_list_changed())
476                 return(True);
477
478         lp_killunused(conn_snum_used);
479         
480         ret = lp_load(dyn_CONFIGFILE, False, False, True);
481
482         load_printers();
483
484         /* perhaps the config filename is now set */
485         if (!test)
486                 reload_services(True);
487
488         reopen_logs();
489
490         load_interfaces();
491
492         {
493                 if (smbd_server_fd() != -1) {      
494                         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
495                         set_socket_options(smbd_server_fd(), user_socket_options);
496                 }
497         }
498
499         mangle_reset_cache();
500         reset_stat_cache();
501
502         /* this forces service parameters to be flushed */
503         set_current_service(NULL,True);
504
505         return(ret);
506 }
507
508 /*******************************************************************
509  Print out all talloc memory info.
510 ********************************************************************/
511
512 void return_all_talloc_info(int msg_type, pid_t src_pid, void *buf, size_t len)
513 {
514         TALLOC_CTX *ctx = talloc_init("info context");
515         char *info = NULL;
516
517         if (!ctx)
518                 return;
519
520         info = talloc_describe_all(ctx);
521         if (info)
522                 DEBUG(10,(info));
523         message_send_pid(src_pid, MSG_TALLOC_USAGE, info, info ? strlen(info) + 1 : 0, True);
524         talloc_destroy(ctx);
525 }
526
527 #if DUMP_CORE
528 /*******************************************************************
529 prepare to dump a core file - carefully!
530 ********************************************************************/
531 static BOOL dump_core(void)
532 {
533         char *p;
534         pstring dname;
535         
536         pstrcpy(dname,lp_logfile());
537         if ((p=strrchr_m(dname,'/'))) *p=0;
538         pstrcat(dname,"/corefiles");
539         mkdir(dname,0700);
540         sys_chown(dname,getuid(),getgid());
541         chmod(dname,0700);
542         if (chdir(dname)) return(False);
543         umask(~(0700));
544
545 #ifdef HAVE_GETRLIMIT
546 #ifdef RLIMIT_CORE
547         {
548                 struct rlimit rlp;
549                 getrlimit(RLIMIT_CORE, &rlp);
550                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
551                 setrlimit(RLIMIT_CORE, &rlp);
552                 getrlimit(RLIMIT_CORE, &rlp);
553                 DEBUG(3,("Core limits now %d %d\n",
554                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
555         }
556 #endif
557 #endif
558
559
560         DEBUG(0,("Dumping core in %s\n", dname));
561         abort();
562         return(True);
563 }
564 #endif
565
566 /****************************************************************************
567  Exit the server.
568 ****************************************************************************/
569
570 void exit_server(const char *reason)
571 {
572         static int firsttime=1;
573         extern char *last_inbuf;
574         extern struct auth_context *negprot_global_auth_context;
575
576         if (!firsttime)
577                 exit(0);
578         firsttime = 0;
579
580         change_to_root_user();
581         DEBUG(2,("Closing connections\n"));
582
583         if (negprot_global_auth_context) {
584                 (negprot_global_auth_context->free)(&negprot_global_auth_context);
585         }
586
587         conn_close_all();
588
589         invalidate_all_vuids();
590
591         print_notify_send_messages(3); /* 3 second timeout. */
592
593         /* delete our entry in the connections database. */
594         yield_connection(NULL,"");
595
596         respond_to_all_remaining_local_messages();
597         decrement_smbd_process_count();
598
599 #ifdef WITH_DFS
600         if (dcelogin_atmost_once) {
601                 dfs_unlogin();
602         }
603 #endif
604
605         if (!reason) {   
606                 int oldlevel = DEBUGLEVEL;
607                 DEBUGLEVEL = 10;
608                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
609                 if (last_inbuf)
610                         show_msg(last_inbuf);
611                 DEBUGLEVEL = oldlevel;
612                 DEBUG(0,("===============================================================\n"));
613 #if DUMP_CORE
614                 if (dump_core()) return;
615 #endif
616         }    
617
618         locking_end();
619         printing_end();
620
621         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
622         exit(0);
623 }
624
625 /****************************************************************************
626  Initialise connect, service and file structs.
627 ****************************************************************************/
628
629 static BOOL init_structs(void )
630 {
631         /*
632          * Set the machine NETBIOS name if not already
633          * set from the config file.
634          */
635
636         if (!init_names())
637                 return False;
638
639         conn_init();
640
641         file_init();
642
643         /* for RPC pipes */
644         init_rpc_pipe_hnd();
645
646         init_dptrs();
647
648         secrets_init();
649
650         return True;
651 }
652
653 /****************************************************************************
654  main program.
655 ****************************************************************************/
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         {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_debug},
677         {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_configfile},
678         {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_socket_options},
679         {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_log_base},
680         {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_version},
681         { NULL }
682         };
683
684 #ifdef HAVE_SET_AUTH_PARAMETERS
685         set_auth_parameters(argc,argv);
686 #endif
687
688         pc = poptGetContext("smbd", argc, argv, long_options, 0);
689         
690         while((opt = poptGetNextOpt(pc)) != -1) {
691                 switch (opt)  {
692                 case 'b':
693                         build_options(True); /* Display output to screen as well as debug */ 
694                         exit(0);
695                         break;
696                 }
697         }
698
699         poptFreeContext(pc);
700
701 #ifdef HAVE_SETLUID
702         /* needed for SecureWare on SCO */
703         setluid(0);
704 #endif
705
706         sec_init();
707
708         load_case_tables();
709
710         set_remote_machine_name("smbd");
711
712         if (interactive) {
713                 Fork = False;
714                 log_stdout = True;
715         }
716
717         if (log_stdout && Fork) {
718                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
719                 exit(1);
720         }
721
722         setup_logging(argv[0],log_stdout);
723
724         /* we want to re-seed early to prevent time delays causing
725            client problems at a later date. (tridge) */
726         generate_random_buffer(NULL, 0, False);
727
728         /* make absolutely sure we run as root - to handle cases where people
729            are crazy enough to have it setuid */
730
731         gain_root_privilege();
732         gain_root_group_privilege();
733
734         fault_setup((void (*)(void *))exit_server);
735         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
736         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
737         
738         /* we are never interested in SIGPIPE */
739         BlockSignals(True,SIGPIPE);
740
741 #if defined(SIGFPE)
742         /* we are never interested in SIGFPE */
743         BlockSignals(True,SIGFPE);
744 #endif
745
746 #if defined(SIGUSR2)
747         /* We are no longer interested in USR2 */
748         BlockSignals(True,SIGUSR2);
749 #endif
750
751         /* POSIX demands that signals are inherited. If the invoking process has
752          * these signals masked, we will have problems, as we won't recieve them. */
753         BlockSignals(False, SIGHUP);
754         BlockSignals(False, SIGUSR1);
755         BlockSignals(False, SIGTERM);
756
757         /* we want total control over the permissions on created files,
758            so set our umask to 0 */
759         umask(0);
760
761         init_sec_ctx();
762
763         reopen_logs();
764
765         DEBUG(0,( "smbd version %s started.\n", VERSION));
766         DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
767
768         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
769                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
770
771         /* Output the build options to the debug log */ 
772         build_options(False);
773
774         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
775                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
776                 exit(1);
777         }
778
779         /*
780          * Do this before reload_services.
781          */
782
783         if (!reload_services(False))
784                 return(-1);     
785
786         init_structs();
787
788 #ifdef WITH_PROFILE
789         if (!profile_setup(False)) {
790                 DEBUG(0,("ERROR: failed to setup profiling\n"));
791                 return -1;
792         }
793 #endif
794
795         DEBUG(3,( "loaded services\n"));
796
797         if (!is_daemon && !is_a_socket(0)) {
798                 if (!interactive)
799                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
800
801                 /*
802                  * Setting is_daemon here prevents us from eventually calling
803                  * the open_sockets_inetd()
804                  */
805
806                 is_daemon = True;
807         }
808
809         if (is_daemon && !interactive) {
810                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
811                 become_daemon(Fork);
812         }
813
814 #if HAVE_SETPGID
815         /*
816          * If we're interactive we want to set our own process group for
817          * signal management.
818          */
819         if (interactive)
820                 setpgid( (pid_t)0, (pid_t)0);
821 #endif
822
823         if (!directory_exist(lp_lockdir(), NULL))
824                 mkdir(lp_lockdir(), 0755);
825
826         if (is_daemon)
827                 pidfile_create("smbd");
828
829         if (!message_init())
830                 exit(1);
831
832         register_msg_pool_usage();
833         register_dmalloc_msgs();
834         message_register(MSG_REQ_TALLOC_USAGE, return_all_talloc_info);
835
836         if (!print_backend_init())
837                 exit(1);
838
839         /* Setup the main smbd so that we can get messages. */
840         claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
841
842         /* 
843            DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
844            THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF 
845            smbd PROCESSES THAT NEVER DIE
846            start_background_queue(); 
847         */
848
849         if (!open_sockets_smbd(is_daemon, interactive, ports))
850                 exit(1);
851
852         /*
853          * everything after this point is run after the fork()
854          */ 
855
856         namecache_enable();
857
858         if (!locking_init(0))
859                 exit(1);
860
861         if (!share_info_db_init())
862                 exit(1);
863
864         if (!init_registry())
865                 exit(1);
866
867         if(!initialize_password_db(False))
868                 exit(1);
869
870         uni_group_cache_init(); /* Non-critical */
871         
872         /* possibly reload the services file. */
873         reload_services(True);
874
875         if(!get_global_sam_sid()) {
876                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
877                 exit(1);
878         }
879
880         if (!init_account_policy()) {
881                 DEBUG(0,("Could not open account policy tdb.\n"));
882                 exit(1);
883         }
884
885         if (*lp_rootdir()) {
886                 if (sys_chroot(lp_rootdir()) == 0)
887                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
888         }
889
890         /* Setup oplocks */
891         if (!init_oplocks())
892                 exit(1);
893         
894         /* Setup change notify */
895         if (!init_change_notify())
896                 exit(1);
897
898         /* re-initialise the timezone */
899         TimeInit();
900
901         /* register our message handlers */
902         message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
903
904         smbd_process();
905         
906         uni_group_cache_shutdown();
907         namecache_shutdown();
908         exit_server("normal exit");
909         return(0);
910 }