r14898: This change is an attempt to improve the quality of the information that
[sfrench/samba-autobuild/.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 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();
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();
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) {
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(void)
685 {
686         exit_server_common(SERVER_EXIT_NORMAL, NULL);
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         extern BOOL in_server;
735         /* shall I run as a daemon */
736         static BOOL is_daemon = False;
737         static BOOL interactive = False;
738         static BOOL Fork = True;
739         static BOOL no_process_group = False;
740         static BOOL log_stdout = False;
741         static char *ports = NULL;
742         int opt;
743         poptContext pc;
744
745         struct poptOption long_options[] = {
746                 POPT_AUTOHELP
747         {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
748         {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
749         {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
750         {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
751         {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
752         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
753         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
754         POPT_COMMON_SAMBA
755         { NULL }
756         };
757
758         in_server = True;
759
760         load_case_tables();
761
762 #ifdef HAVE_SET_AUTH_PARAMETERS
763         set_auth_parameters(argc,argv);
764 #endif
765
766         pc = poptGetContext("smbd", argc, argv, long_options, 0);
767         
768         while((opt = poptGetNextOpt(pc)) != -1) {
769                 switch (opt)  {
770                 case 'b':
771                         build_options(True); /* Display output to screen as well as debug */ 
772                         exit(0);
773                         break;
774                 }
775         }
776
777         poptFreeContext(pc);
778
779 #ifdef HAVE_SETLUID
780         /* needed for SecureWare on SCO */
781         setluid(0);
782 #endif
783
784         sec_init();
785
786         set_remote_machine_name("smbd", False);
787
788         if (interactive) {
789                 Fork = False;
790                 log_stdout = True;
791         }
792
793         if (interactive && (DEBUGLEVEL >= 9)) {
794                 talloc_enable_leak_report();
795         }
796
797         if (log_stdout && Fork) {
798                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
799                 exit(1);
800         }
801
802         setup_logging(argv[0],log_stdout);
803
804         /* we want to re-seed early to prevent time delays causing
805            client problems at a later date. (tridge) */
806         generate_random_buffer(NULL, 0);
807
808         /* make absolutely sure we run as root - to handle cases where people
809            are crazy enough to have it setuid */
810
811         gain_root_privilege();
812         gain_root_group_privilege();
813
814         fault_setup((void (*)(void *))exit_server_fault);
815         dump_core_setup("smbd");
816
817         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
818         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
819         
820         /* we are never interested in SIGPIPE */
821         BlockSignals(True,SIGPIPE);
822
823 #if defined(SIGFPE)
824         /* we are never interested in SIGFPE */
825         BlockSignals(True,SIGFPE);
826 #endif
827
828 #if defined(SIGUSR2)
829         /* We are no longer interested in USR2 */
830         BlockSignals(True,SIGUSR2);
831 #endif
832
833         /* POSIX demands that signals are inherited. If the invoking process has
834          * these signals masked, we will have problems, as we won't recieve them. */
835         BlockSignals(False, SIGHUP);
836         BlockSignals(False, SIGUSR1);
837         BlockSignals(False, SIGTERM);
838
839         /* we want total control over the permissions on created files,
840            so set our umask to 0 */
841         umask(0);
842
843         init_sec_ctx();
844
845         reopen_logs();
846
847         DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
848         DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
849
850         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
851                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
852
853         /* Output the build options to the debug log */ 
854         build_options(False);
855
856         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
857                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
858                 exit(1);
859         }
860
861         /*
862          * Do this before reload_services.
863          */
864
865         if (!reload_services(False))
866                 return(-1);     
867
868         init_structs();
869
870 #ifdef WITH_PROFILE
871         if (!profile_setup(False)) {
872                 DEBUG(0,("ERROR: failed to setup profiling\n"));
873                 return -1;
874         }
875 #endif
876
877         DEBUG(3,( "loaded services\n"));
878
879         if (!is_daemon && !is_a_socket(0)) {
880                 if (!interactive)
881                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
882
883                 /*
884                  * Setting is_daemon here prevents us from eventually calling
885                  * the open_sockets_inetd()
886                  */
887
888                 is_daemon = True;
889         }
890
891         if (is_daemon && !interactive) {
892                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
893                 become_daemon(Fork, no_process_group);
894         }
895
896 #if HAVE_SETPGID
897         /*
898          * If we're interactive we want to set our own process group for
899          * signal management.
900          */
901         if (interactive && !no_process_group) {
902                 setpgid( (pid_t)0, (pid_t)0);
903         }
904 #endif
905
906         if (!directory_exist(lp_lockdir(), NULL))
907                 mkdir(lp_lockdir(), 0755);
908
909         if (is_daemon)
910                 pidfile_create("smbd");
911
912         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
913         if (!message_init())
914                 exit(1);
915
916         if (!session_init())
917                 exit(1);
918
919         if (conn_tdb_ctx() == NULL)
920                 exit(1);
921
922         if (!locking_init(0))
923                 exit(1);
924
925         namecache_enable();
926
927         if (!init_registry())
928                 exit(1);
929
930 #if 0
931         if (!init_svcctl_db())
932                 exit(1);
933 #endif
934
935         if (!print_backend_init())
936                 exit(1);
937
938         if (!init_guest_info()) {
939                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
940                 return -1;
941         }
942
943         /* Setup the main smbd so that we can get messages. */
944         /* don't worry about general printing messages here */
945
946         claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
947
948         /* only start the background queue daemon if we are 
949            running as a daemon -- bad things will happen if
950            smbd is launched via inetd and we fork a copy of 
951            ourselves here */
952
953         if ( is_daemon && !interactive )
954                 start_background_queue(); 
955
956         /* Always attempt to initialize DMAPI. We will only use it later if
957          * lp_dmapi_support is set on the share, but we need a single global
958          * session to work with.
959          */
960         dmapi_init_session();
961
962         if (!open_sockets_smbd(is_daemon, interactive, ports))
963                 exit(1);
964
965         /*
966          * everything after this point is run after the fork()
967          */ 
968
969         /* Initialise the password backed before the global_sam_sid
970            to ensure that we fetch from ldap before we make a domain sid up */
971
972         if(!initialize_password_db(False))
973                 exit(1);
974
975         if(!get_global_sam_sid()) {
976                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
977                 exit(1);
978         }
979
980         static_init_rpc;
981
982         init_modules();
983
984         /* possibly reload the services file. */
985         reload_services(True);
986
987         if (!init_account_policy()) {
988                 DEBUG(0,("Could not open account policy tdb.\n"));
989                 exit(1);
990         }
991
992         if (*lp_rootdir()) {
993                 if (sys_chroot(lp_rootdir()) == 0)
994                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
995         }
996
997         /* Setup oplocks */
998         if (!init_oplocks())
999                 exit(1);
1000         
1001         /* Setup change notify */
1002         if (!init_change_notify())
1003                 exit(1);
1004
1005         /* Setup aio signal handler. */
1006         initialize_async_io_handler();
1007
1008         /* re-initialise the timezone */
1009         TimeInit();
1010
1011         /* register our message handlers */
1012         message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1013
1014         smbd_process();
1015
1016         namecache_shutdown();
1017
1018         exit_server_cleanly();
1019         return(0);
1020 }