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