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