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