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