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