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