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