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