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