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