r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[samba.git] / source3 / smbd / server.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Andrew Tridgell                1992-1998
5    Copyright (C) Martin Pool                    2002
6    Copyright (C) Jelmer Vernooij                2002-2003
7    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         /* Listen to messages */
353
354         messaging_register(smbd_messaging_context(), NULL,
355                            MSG_SMB_SAM_SYNC, msg_sam_sync);
356         messaging_register(smbd_messaging_context(), NULL,
357                            MSG_SHUTDOWN, msg_exit_server);
358         messaging_register(smbd_messaging_context(), NULL,
359                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
360         messaging_register(smbd_messaging_context(), NULL,
361                            MSG_SMB_CONF_UPDATED, smb_conf_updated); 
362         messaging_register(smbd_messaging_context(), NULL,
363                            MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
364         brl_register_msgs(smbd_messaging_context());
365
366 #ifdef DEVELOPER
367         messaging_register(smbd_messaging_context(), NULL,
368                            MSG_SMB_INJECT_FAULT, msg_inject_fault);
369 #endif
370
371         /* now accept incoming connections - forking a new process
372            for each incoming connection */
373         DEBUG(2,("waiting for a connection\n"));
374         while (1) {
375                 struct timeval now;
376                 fd_set r_fds, w_fds;
377                 int num;
378                 
379                 /* Free up temporary memory from the main smbd. */
380                 lp_TALLOC_FREE();
381
382                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
383                 message_dispatch(smbd_messaging_context());
384
385                 if (got_sig_cld) {
386                         pid_t pid;
387                         got_sig_cld = False;
388
389                         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
390                                 remove_child_pid(pid);
391                         }
392                 }
393
394                 memcpy((char *)&r_fds, (char *)&listen_set, 
395                        sizeof(listen_set));
396                 FD_ZERO(&w_fds);
397                 GetTimeOfDay(&now);
398
399                 event_add_to_select_args(smbd_event_context(), &now,
400                                          &r_fds, &w_fds, &idle_timeout,
401                                          &maxfd);
402
403                 if (timeval_is_zero(&idle_timeout)) {
404                         num = sys_select(maxfd + 1, &r_fds, &w_fds,
405                                         NULL, NULL);
406                 } else {
407                         num = sys_select(maxfd + 1, &r_fds, &w_fds,
408                                         NULL, &idle_timeout);
409
410                         /* If the idle timeout fired and we are idle, exit
411                          * gracefully. We expect to be running under a process
412                          * controller that will restart us if necessry.
413                          */
414                         if (num == 0 && smbd_is_idle()) {
415                                 exit_server_cleanly("idle timeout");
416                         }
417                 }
418
419                 if (num == -1 && errno == EINTR) {
420                         if (got_sig_term) {
421                                 exit_server_cleanly(NULL);
422                         }
423
424                         /* check for sighup processing */
425                         if (reload_after_sighup) {
426                                 change_to_root_user();
427                                 DEBUG(1,("Reloading services after SIGHUP\n"));
428                                 reload_services(False);
429                                 reload_after_sighup = 0;
430                         }
431
432                         continue;
433                 }
434
435                 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
436                         continue;
437                 }
438
439                 /* check if we need to reload services */
440                 check_reload(time(NULL));
441
442                 /* Find the sockets that are read-ready -
443                    accept on these. */
444                 for( ; num > 0; num--) {
445                         struct sockaddr addr;
446                         socklen_t in_addrlen = sizeof(addr);
447                         pid_t child = 0;
448
449                         s = -1;
450                         for(i = 0; i < num_sockets; i++) {
451                                 if(FD_ISSET(fd_listenset[i],&r_fds)) {
452                                         s = fd_listenset[i];
453                                         /* Clear this so we don't look
454                                            at it again. */
455                                         FD_CLR(fd_listenset[i],&r_fds);
456                                         break;
457                                 }
458                         }
459
460                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
461                         
462                         if (smbd_server_fd() == -1 && errno == EINTR)
463                                 continue;
464                         
465                         if (smbd_server_fd() == -1) {
466                                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
467                                          strerror(errno)));
468                                 continue;
469                         }
470
471                         /* Ensure child is set to blocking mode */
472                         set_blocking(smbd_server_fd(),True);
473
474                         /* In interactive mode, return with a connected socket.
475                          * Foreground and daemon modes should fork worker
476                          * processes.
477                          */
478                         if (server_mode == SERVER_MODE_INTERACTIVE) {
479                                 return True;
480                         }
481                         
482                         if (allowable_number_of_smbd_processes() &&
483                             smbd_server_fd() != -1 &&
484                             ((child = sys_fork())==0)) {
485                                 /* Child code ... */
486
487                                 /* Stop zombies, the parent explicitly handles
488                                  * them, counting worker smbds. */
489                                 CatchChild();
490                                 
491                                 /* close the listening socket(s) */
492                                 for(i = 0; i < num_sockets; i++)
493                                         close(fd_listenset[i]);
494                                 
495                                 /* close our standard file
496                                    descriptors */
497                                 close_low_fds(False);
498                                 am_parent = 0;
499                                 
500                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
501                                 set_socket_options(smbd_server_fd(),user_socket_options);
502                                 
503                                 /* this is needed so that we get decent entries
504                                    in smbstatus for port 445 connects */
505                                 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
506                                                         False);
507                                 
508                                 /* Reset the state of the random
509                                  * number generation system, so
510                                  * children do not get the same random
511                                  * numbers as each other */
512
513                                 set_need_random_reseed();
514                                 /* tdb needs special fork handling - remove
515                                  * CLEAR_IF_FIRST flags */
516                                 if (tdb_reopen_all(1) == -1) {
517                                         DEBUG(0,("tdb_reopen_all failed.\n"));
518                                         smb_panic("tdb_reopen_all failed");
519                                 }
520
521                                 return True; 
522                         }
523                         /* The parent doesn't need this socket */
524                         close(smbd_server_fd()); 
525
526                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
527                                 Clear the closed fd info out of server_fd --
528                                 and more importantly, out of client_fd in
529                                 util_sock.c, to avoid a possible
530                                 getpeername failure if we reopen the logs
531                                 and use %I in the filename.
532                         */
533
534                         smbd_set_server_fd(-1);
535
536                         if (child != 0) {
537                                 add_child_pid(child);
538                         }
539
540                         /* Force parent to check log size after
541                          * spawning child.  Fix from
542                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
543                          * parent smbd will log to logserver.smb.  It
544                          * writes only two messages for each child
545                          * started/finished. But each child writes,
546                          * say, 50 messages also in logserver.smb,
547                          * begining with the debug_count of the
548                          * parent, before the child opens its own log
549                          * file logserver.client. In a worst case
550                          * scenario the size of logserver.smb would be
551                          * checked after about 50*50=2500 messages
552                          * (ca. 100kb).
553                          * */
554                         force_check_log_size();
555  
556                 } /* end for num */
557         } /* end while 1 */
558
559 /* NOTREACHED   return True; */
560 }
561
562 /****************************************************************************
563  Reload printers
564 **************************************************************************/
565 void reload_printers(void)
566 {
567         int snum;
568         int n_services = lp_numservices();
569         int pnum = lp_servicenumber(PRINTERS_NAME);
570         const char *pname;
571
572         pcap_cache_reload();
573
574         /* remove stale printers */
575         for (snum = 0; snum < n_services; snum++) {
576                 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
577                 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
578                                       lp_autoloaded(snum)))
579                         continue;
580
581                 pname = lp_printername(snum);
582                 if (!pcap_printername_ok(pname)) {
583                         DEBUG(3, ("removing stale printer %s\n", pname));
584
585                         if (is_printer_published(NULL, snum, NULL))
586                                 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
587                         del_a_printer(pname);
588                         lp_killservice(snum);
589                 }
590         }
591
592         load_printers();
593 }
594
595 /****************************************************************************
596  Reload the services file.
597 **************************************************************************/
598
599 BOOL reload_services(BOOL test)
600 {
601         BOOL ret;
602         
603         if (lp_loaded()) {
604                 pstring fname;
605                 pstrcpy(fname,lp_configfile());
606                 if (file_exist(fname, NULL) &&
607                     !strcsequal(fname, dyn_CONFIGFILE)) {
608                         pstrcpy(dyn_CONFIGFILE, fname);
609                         test = False;
610                 }
611         }
612
613         reopen_logs();
614
615         if (test && !lp_file_list_changed())
616                 return(True);
617
618         lp_killunused(conn_snum_used);
619
620         ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
621
622         reload_printers();
623
624         /* perhaps the config filename is now set */
625         if (!test)
626                 reload_services(True);
627
628         reopen_logs();
629
630         load_interfaces();
631
632         if (smbd_server_fd() != -1) {      
633                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
634                 set_socket_options(smbd_server_fd(), user_socket_options);
635         }
636
637         mangle_reset_cache();
638         reset_stat_cache();
639
640         /* this forces service parameters to be flushed */
641         set_current_service(NULL,0,True);
642
643         return(ret);
644 }
645
646 /****************************************************************************
647  Exit the server.
648 ****************************************************************************/
649
650 /* Reasons for shutting down a server process. */
651 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
652
653 static void exit_server_common(enum server_exit_reason how,
654         const char *const reason) NORETURN_ATTRIBUTE;
655
656 static void exit_server_common(enum server_exit_reason how,
657         const char *const reason)
658 {
659         static int firsttime=1;
660
661         if (!firsttime)
662                 exit(0);
663         firsttime = 0;
664
665         change_to_root_user();
666
667         if (negprot_global_auth_context) {
668                 (negprot_global_auth_context->free)(&negprot_global_auth_context);
669         }
670
671         conn_close_all();
672
673         invalidate_all_vuids();
674
675         /* 3 second timeout. */
676         print_notify_send_messages(smbd_messaging_context(), 3);
677
678         /* delete our entry in the connections database. */
679         yield_connection(NULL,"");
680
681         respond_to_all_remaining_local_messages();
682
683 #ifdef WITH_DFS
684         if (dcelogin_atmost_once) {
685                 dfs_unlogin();
686         }
687 #endif
688
689         locking_end();
690         printing_end();
691
692         server_encryption_shutdown();
693
694         if (how != SERVER_EXIT_NORMAL) {
695                 int oldlevel = DEBUGLEVEL;
696                 char *last_inbuf = get_InBuffer();
697
698                 DEBUGLEVEL = 10;
699
700                 DEBUGSEP(0);
701                 DEBUG(0,("Abnormal server exit: %s\n",
702                         reason ? reason : "no explanation provided"));
703                 DEBUGSEP(0);
704
705                 log_stack_trace();
706                 if (last_inbuf) {
707                         DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
708                         show_msg(last_inbuf);
709                 }
710
711                 DEBUGLEVEL = oldlevel;
712                 dump_core();
713
714         } else {    
715                 DEBUG(3,("Server exit (%s)\n",
716                         (reason ? reason : "normal exit")));
717         }
718
719         exit(0);
720 }
721
722 void exit_server(const char *const explanation)
723 {
724         exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
725 }
726
727 void exit_server_cleanly(const char *const explanation)
728 {
729         exit_server_common(SERVER_EXIT_NORMAL, explanation);
730 }
731
732 void exit_server_fault(void)
733 {
734         exit_server("critical server fault");
735 }
736
737 /****************************************************************************
738  Initialise connect, service and file structs.
739 ****************************************************************************/
740
741 static BOOL init_structs(void )
742 {
743         /*
744          * Set the machine NETBIOS name if not already
745          * set from the config file.
746          */
747
748         if (!init_names())
749                 return False;
750
751         conn_init();
752
753         file_init();
754
755         /* for RPC pipes */
756         init_rpc_pipe_hnd();
757
758         init_dptrs();
759
760         secrets_init();
761
762         return True;
763 }
764
765 /*
766  * Send keepalive packets to our client
767  */
768 static BOOL keepalive_fn(const struct timeval *now, void *private_data)
769 {
770         if (!send_keepalive(smbd_server_fd())) {
771                 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
772                 return False;
773         }
774         return True;
775 }
776
777 /*
778  * Do the recurring check if we're idle
779  */
780 static BOOL deadtime_fn(const struct timeval *now, void *private_data)
781 {
782         if ((conn_num_open() == 0)
783             || (conn_idle_all(now->tv_sec))) {
784                 DEBUG( 2, ( "Closing idle connection\n" ) );
785                 messaging_send(smbd_messaging_context(), procid_self(),
786                                MSG_SHUTDOWN, &data_blob_null);
787                 return False;
788         }
789
790         return True;
791 }
792
793
794 /****************************************************************************
795  main program.
796 ****************************************************************************/
797
798 /* Declare prototype for build_options() to avoid having to run it through
799    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
800    prototype generation system is too complicated. */
801
802 extern void build_options(BOOL screen);
803
804  int main(int argc,const char *argv[])
805 {
806         /* shall I run as a daemon */
807         BOOL no_process_group = False;
808         BOOL log_stdout = False;
809         const char *ports = NULL;
810         const char *profile_level = NULL;
811         int opt;
812         poptContext pc;
813
814         enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
815
816         struct poptOption long_options[] = {
817         POPT_AUTOHELP
818         {"daemon", 'D', POPT_ARG_VAL, &server_mode, SERVER_MODE_DAEMON,
819                 "Become a daemon (default)" },
820         {"interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE,
821                 "Run interactive (not a daemon)"},
822         {"foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND,
823                 "Run daemon in foreground (for daemontools, etc.)" },
824         {"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True,
825                 "Don't create a new process group" },
826         {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
827         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
828         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
829         {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
830         POPT_COMMON_SAMBA
831         POPT_COMMON_DYNCONFIG
832         POPT_TABLEEND
833         };
834
835         load_case_tables();
836
837         TimeInit();
838
839 #ifdef HAVE_SET_AUTH_PARAMETERS
840         set_auth_parameters(argc,argv);
841 #endif
842
843         pc = poptGetContext("smbd", argc, argv, long_options, 0);
844         
845         while((opt = poptGetNextOpt(pc)) != -1) {
846                 switch (opt)  {
847                 case 'b':
848                         build_options(True); /* Display output to screen as well as debug */ 
849                         exit(0);
850                         break;
851                 }
852         }
853
854         poptFreeContext(pc);
855
856 #ifdef HAVE_SETLUID
857         /* needed for SecureWare on SCO */
858         setluid(0);
859 #endif
860
861         sec_init();
862
863         set_remote_machine_name("smbd", False);
864
865         if (server_mode == SERVER_MODE_INTERACTIVE) {
866                 log_stdout = True;
867                 if (DEBUGLEVEL >= 9) {
868                         talloc_enable_leak_report();
869                 }
870         }
871
872         if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
873                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
874                 exit(1);
875         }
876
877         setup_logging(argv[0],log_stdout);
878
879         /* we want to re-seed early to prevent time delays causing
880            client problems at a later date. (tridge) */
881         generate_random_buffer(NULL, 0);
882
883         /* make absolutely sure we run as root - to handle cases where people
884            are crazy enough to have it setuid */
885
886         gain_root_privilege();
887         gain_root_group_privilege();
888
889         fault_setup((void (*)(void *))exit_server_fault);
890         dump_core_setup("smbd");
891
892         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
893         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
894         
895         /* we are never interested in SIGPIPE */
896         BlockSignals(True,SIGPIPE);
897
898 #if defined(SIGFPE)
899         /* we are never interested in SIGFPE */
900         BlockSignals(True,SIGFPE);
901 #endif
902
903 #if defined(SIGUSR2)
904         /* We are no longer interested in USR2 */
905         BlockSignals(True,SIGUSR2);
906 #endif
907
908         /* POSIX demands that signals are inherited. If the invoking process has
909          * these signals masked, we will have problems, as we won't recieve them. */
910         BlockSignals(False, SIGHUP);
911         BlockSignals(False, SIGUSR1);
912         BlockSignals(False, SIGTERM);
913
914         /* we want total control over the permissions on created files,
915            so set our umask to 0 */
916         umask(0);
917
918         init_sec_ctx();
919
920         reopen_logs();
921
922         DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
923         DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
924
925         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
926                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
927
928         /* Output the build options to the debug log */ 
929         build_options(False);
930
931         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
932                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
933                 exit(1);
934         }
935
936         /*
937          * Do this before reload_services.
938          */
939
940         if (!reload_services(False))
941                 return(-1);     
942
943         init_structs();
944
945 #ifdef WITH_PROFILE
946         if (!profile_setup(smbd_messaging_context(), False)) {
947                 DEBUG(0,("ERROR: failed to setup profiling\n"));
948                 return -1;
949         }
950         if (profile_level != NULL) {
951                 int pl = atoi(profile_level);
952                 struct server_id src;
953
954                 DEBUG(1, ("setting profiling level: %s\n",profile_level));
955                 src.pid = getpid();
956                 set_profile_level(pl, src);
957         }
958 #endif
959
960         DEBUG(3,( "loaded services\n"));
961
962         if (is_a_socket(0)) {
963                 if (server_mode == SERVER_MODE_DAEMON) {
964                         DEBUG(0,("standard input is a socket, "
965                                     "assuming -F option\n"));
966                 }
967                 server_mode = SERVER_MODE_INETD;
968         }
969
970         if (server_mode == SERVER_MODE_DAEMON) {
971                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
972                 become_daemon(True, no_process_group);
973         } else if (server_mode == SERVER_MODE_FOREGROUND) {
974                 become_daemon(False, no_process_group);
975         }
976
977 #if HAVE_SETPGID
978         /*
979          * If we're interactive we want to set our own process group for
980          * signal management.
981          */
982         if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
983                 setpgid( (pid_t)0, (pid_t)0);
984         }
985 #endif
986
987         if (!directory_exist(lp_lockdir(), NULL))
988                 mkdir(lp_lockdir(), 0755);
989
990         if (server_mode != SERVER_MODE_INETD &&
991             server_mode != SERVER_MODE_INTERACTIVE) {
992                 pidfile_create("smbd");
993         }
994
995         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
996
997         if (smbd_messaging_context() == NULL)
998                 exit(1);
999
1000         /* Initialise the password backed before the global_sam_sid
1001            to ensure that we fetch from ldap before we make a domain sid up */
1002
1003         if(!initialize_password_db(False, smbd_event_context()))
1004                 exit(1);
1005
1006         if (!secrets_init()) {
1007                 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1008                 exit(1);
1009         }
1010
1011         if(!get_global_sam_sid()) {
1012                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1013                 exit(1);
1014         }
1015
1016         if (!session_init())
1017                 exit(1);
1018
1019         if (!connections_init(True))
1020                 exit(1);
1021
1022         if (!locking_init(0))
1023                 exit(1);
1024
1025         namecache_enable();
1026
1027         if (!init_registry())
1028                 exit(1);
1029
1030 #if 0
1031         if (!init_svcctl_db())
1032                 exit(1);
1033 #endif
1034
1035         if (!print_backend_init(smbd_messaging_context()))
1036                 exit(1);
1037
1038         if (!init_guest_info()) {
1039                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1040                 return -1;
1041         }
1042
1043         /* Setup the main smbd so that we can get messages. */
1044         /* don't worry about general printing messages here */
1045
1046         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
1047
1048         /* only start the background queue daemon if we are 
1049            running as a daemon -- bad things will happen if
1050            smbd is launched via inetd and we fork a copy of 
1051            ourselves here */
1052         if (server_mode != SERVER_MODE_INETD &&
1053             server_mode != SERVER_MODE_INTERACTIVE) {
1054                 start_background_queue(); 
1055         }
1056
1057         /* Always attempt to initialize DMAPI. We will only use it later if
1058          * lp_dmapi_support is set on the share, but we need a single global
1059          * session to work with.
1060          */
1061         dmapi_init_session();
1062
1063         if (!open_sockets_smbd(server_mode, ports)) {
1064                 exit(1);
1065         }
1066
1067         /*
1068          * everything after this point is run after the fork()
1069          */ 
1070
1071         static_init_rpc;
1072
1073         init_modules();
1074
1075         /* Possibly reload the services file. Only worth doing in
1076          * daemon mode. In inetd mode, we know we only just loaded this.
1077          */
1078         if (server_mode != SERVER_MODE_INETD &&
1079             server_mode != SERVER_MODE_INTERACTIVE) {
1080                 reload_services(True);
1081         }
1082
1083         if (!init_account_policy()) {
1084                 DEBUG(0,("Could not open account policy tdb.\n"));
1085                 exit(1);
1086         }
1087
1088         if (*lp_rootdir()) {
1089                 if (sys_chroot(lp_rootdir()) == 0)
1090                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1091         }
1092
1093         /* Setup oplocks */
1094         if (!init_oplocks(smbd_messaging_context()))
1095                 exit(1);
1096         
1097         /* Setup aio signal handler. */
1098         initialize_async_io_handler();
1099
1100         /*
1101          * For clustering, we need to re-init our ctdbd connection after the
1102          * fork
1103          */
1104         if (!NT_STATUS_IS_OK(messaging_reinit(smbd_messaging_context())))
1105                 exit(1);
1106
1107         /* register our message handlers */
1108         messaging_register(smbd_messaging_context(), NULL,
1109                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
1110
1111         if ((lp_keepalive() != 0)
1112             && !(event_add_idle(smbd_event_context(), NULL,
1113                                 timeval_set(lp_keepalive(), 0),
1114                                 "keepalive", keepalive_fn,
1115                                 NULL))) {
1116                 DEBUG(0, ("Could not add keepalive event\n"));
1117                 exit(1);
1118         }
1119
1120         if (!(event_add_idle(smbd_event_context(), NULL,
1121                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1122                              "deadtime", deadtime_fn, NULL))) {
1123                 DEBUG(0, ("Could not add deadtime event\n"));
1124                 exit(1);
1125         }
1126
1127         smbd_process();
1128
1129         namecache_shutdown();
1130
1131         exit_server_cleanly(NULL);
1132         return(0);
1133 }