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