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