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