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