r24809: Consolidate the use of temporary talloc contexts.
[Samba.git] / source / smbd / server.c
blob72eeb7ee6a8f20c46aabc0b6ca4253a74df0d274
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 Copyright (C) James Peach 2007
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
25 static_decl_rpc;
27 static int am_parent = 1;
29 /* the last message the was processed */
30 int last_message = -1;
32 /* a useful macro to debug the last message processed */
33 #define LAST_MESSAGE() smb_fn_name(last_message)
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 static SIG_ATOMIC_T got_sig_cld;
41 #ifdef WITH_DFS
42 extern int dcelogin_atmost_once;
43 #endif /* WITH_DFS */
45 /* really we should have a top level context structure that has the
46 client file descriptor as an element. That would require a major rewrite :(
48 the following 2 functions are an alternative - they make the file
49 descriptor private to smbd
51 static int server_fd = -1;
53 int smbd_server_fd(void)
55 return server_fd;
58 static void smbd_set_server_fd(int fd)
60 server_fd = fd;
61 client_setfd(fd);
64 struct event_context *smbd_event_context(void)
66 static struct event_context *ctx;
68 if (!ctx && !(ctx = event_context_init(NULL))) {
69 smb_panic("Could not init smbd event context");
71 return ctx;
74 struct messaging_context *smbd_messaging_context(void)
76 static struct messaging_context *ctx;
78 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
79 smbd_event_context()))) {
80 smb_panic("Could not init smbd messaging context");
82 return ctx;
85 /*******************************************************************
86 What to do when smb.conf is updated.
87 ********************************************************************/
89 static void smb_conf_updated(struct messaging_context *msg,
90 void *private_data,
91 uint32_t msg_type,
92 struct server_id server_id,
93 DATA_BLOB *data)
95 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
96 "updated. Reloading.\n"));
97 reload_services(False);
101 /*******************************************************************
102 Delete a statcache entry.
103 ********************************************************************/
105 static void smb_stat_cache_delete(struct messaging_context *msg,
106 void *private_data,
107 uint32_t msg_tnype,
108 struct server_id server_id,
109 DATA_BLOB *data)
111 const char *name = (const char *)data->data;
112 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
113 stat_cache_delete(name);
116 /****************************************************************************
117 Terminate signal.
118 ****************************************************************************/
120 static void sig_term(void)
122 got_sig_term = 1;
123 sys_select_signal(SIGTERM);
126 /****************************************************************************
127 Catch a sighup.
128 ****************************************************************************/
130 static void sig_hup(int sig)
132 reload_after_sighup = 1;
133 sys_select_signal(SIGHUP);
136 /****************************************************************************
137 Catch a sigcld
138 ****************************************************************************/
139 static void sig_cld(int sig)
141 got_sig_cld = 1;
142 sys_select_signal(SIGCLD);
145 /****************************************************************************
146 Send a SIGTERM to our process group.
147 *****************************************************************************/
149 static void killkids(void)
151 if(am_parent) kill(0,SIGTERM);
154 /****************************************************************************
155 Process a sam sync message - not sure whether to do this here or
156 somewhere else.
157 ****************************************************************************/
159 static void msg_sam_sync(struct messaging_context *msg,
160 void *private_data,
161 uint32_t msg_type,
162 struct server_id server_id,
163 DATA_BLOB *data)
165 DEBUG(10, ("** sam sync message received, ignoring\n"));
169 /****************************************************************************
170 Open the socket communication - inetd.
171 ****************************************************************************/
173 static BOOL open_sockets_inetd(void)
175 /* Started from inetd. fd 0 is the socket. */
176 /* We will abort gracefully when the client or remote system
177 goes away */
178 smbd_set_server_fd(dup(0));
180 /* close our standard file descriptors */
181 close_low_fds(False); /* Don't close stderr */
183 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
184 set_socket_options(smbd_server_fd(), user_socket_options);
186 return True;
189 static void msg_exit_server(struct messaging_context *msg,
190 void *private_data,
191 uint32_t msg_type,
192 struct server_id server_id,
193 DATA_BLOB *data)
195 DEBUG(3, ("got a SHUTDOWN message\n"));
196 exit_server_cleanly(NULL);
199 #ifdef DEVELOPER
200 static void msg_inject_fault(struct messaging_context *msg,
201 void *private_data,
202 uint32_t msg_type,
203 struct server_id src,
204 DATA_BLOB *data)
206 int sig;
208 if (data->length != sizeof(sig)) {
210 DEBUG(0, ("Process %s sent bogus signal injection request\n",
211 procid_str_static(&src)));
212 return;
215 sig = *(int *)data->data;
216 if (sig == -1) {
217 exit_server("internal error injected");
218 return;
221 #if HAVE_STRSIGNAL
222 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
223 procid_str_static(&src), sig, strsignal(sig)));
224 #else
225 DEBUG(0, ("Process %s requested injection of signal %d\n",
226 procid_str_static(&src), sig));
227 #endif
229 kill(sys_getpid(), sig);
231 #endif /* DEVELOPER */
233 struct child_pid {
234 struct child_pid *prev, *next;
235 pid_t pid;
238 static struct child_pid *children;
239 static int num_children;
241 static void add_child_pid(pid_t pid)
243 struct child_pid *child;
245 if (lp_max_smbd_processes() == 0) {
246 /* Don't bother with the child list if we don't care anyway */
247 return;
250 child = SMB_MALLOC_P(struct child_pid);
251 if (child == NULL) {
252 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
253 return;
255 child->pid = pid;
256 DLIST_ADD(children, child);
257 num_children += 1;
260 static void remove_child_pid(pid_t pid)
262 struct child_pid *child;
264 if (lp_max_smbd_processes() == 0) {
265 /* Don't bother with the child list if we don't care anyway */
266 return;
269 for (child = children; child != NULL; child = child->next) {
270 if (child->pid == pid) {
271 struct child_pid *tmp = child;
272 DLIST_REMOVE(children, child);
273 SAFE_FREE(tmp);
274 num_children -= 1;
275 return;
279 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
282 /****************************************************************************
283 Have we reached the process limit ?
284 ****************************************************************************/
286 static BOOL allowable_number_of_smbd_processes(void)
288 int max_processes = lp_max_smbd_processes();
290 if (!max_processes)
291 return True;
293 return num_children < max_processes;
296 /****************************************************************************
297 Are we idle enough that we could safely exit?
298 ****************************************************************************/
300 static BOOL smbd_is_idle(void)
302 /* Currently we define "idle" as having no client connections. */
303 return count_all_current_connections() == 0;
306 /****************************************************************************
307 Open the socket communication.
308 ****************************************************************************/
310 static BOOL open_sockets_smbd(enum smb_server_mode server_mode, const char *smb_ports)
312 int num_sockets = 0;
313 int fd_listenset[FD_SETSIZE];
314 fd_set listen_set;
315 int s;
316 int maxfd = 0;
317 int i;
318 struct timeval idle_timeout = timeval_zero();
320 if (server_mode == SERVER_MODE_INETD) {
321 return open_sockets_inetd();
324 #ifdef HAVE_ATEXIT
326 static int atexit_set;
327 if(atexit_set == 0) {
328 atexit_set=1;
329 atexit(killkids);
332 #endif
334 /* Stop zombies */
335 CatchSignal(SIGCLD, sig_cld);
337 FD_ZERO(&listen_set);
339 /* At this point, it doesn't matter what daemon mode we are in, we
340 * need some sockets to listen on.
342 num_sockets = smbd_sockinit(smb_ports, fd_listenset, &idle_timeout);
343 if (num_sockets == 0) {
344 return False;
347 for (i = 0; i < num_sockets; ++i) {
348 FD_SET(fd_listenset[i], &listen_set);
349 maxfd = MAX(maxfd, fd_listenset[i]);
353 /* Setup the main smbd so that we can get messages. Note that
354 do this after starting listening. This is needed as when in
355 clustered mode, ctdb won't allow us to start doing database
356 operations until it has gone thru a full startup, which
357 includes checking to see that smbd is listening. */
358 claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
360 /* Listen to messages */
362 messaging_register(smbd_messaging_context(), NULL,
363 MSG_SMB_SAM_SYNC, msg_sam_sync);
364 messaging_register(smbd_messaging_context(), NULL,
365 MSG_SHUTDOWN, msg_exit_server);
366 messaging_register(smbd_messaging_context(), NULL,
367 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
368 messaging_register(smbd_messaging_context(), NULL,
369 MSG_SMB_CONF_UPDATED, smb_conf_updated);
370 messaging_register(smbd_messaging_context(), NULL,
371 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
372 brl_register_msgs(smbd_messaging_context());
374 #ifdef DEVELOPER
375 messaging_register(smbd_messaging_context(), NULL,
376 MSG_SMB_INJECT_FAULT, msg_inject_fault);
377 #endif
379 /* now accept incoming connections - forking a new process
380 for each incoming connection */
381 DEBUG(2,("waiting for a connection\n"));
382 while (1) {
383 struct timeval now;
384 fd_set r_fds, w_fds;
385 int num;
387 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
388 message_dispatch(smbd_messaging_context());
390 if (got_sig_cld) {
391 pid_t pid;
392 got_sig_cld = False;
394 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
395 remove_child_pid(pid);
399 memcpy((char *)&r_fds, (char *)&listen_set,
400 sizeof(listen_set));
401 FD_ZERO(&w_fds);
402 GetTimeOfDay(&now);
404 event_add_to_select_args(smbd_event_context(), &now,
405 &r_fds, &w_fds, &idle_timeout,
406 &maxfd);
408 if (timeval_is_zero(&idle_timeout)) {
409 num = sys_select(maxfd + 1, &r_fds, &w_fds,
410 NULL, NULL);
411 } else {
412 num = sys_select(maxfd + 1, &r_fds, &w_fds,
413 NULL, &idle_timeout);
415 /* If the idle timeout fired and we are idle, exit
416 * gracefully. We expect to be running under a process
417 * controller that will restart us if necessry.
419 if (num == 0 && smbd_is_idle()) {
420 exit_server_cleanly("idle timeout");
424 if (num == -1 && errno == EINTR) {
425 if (got_sig_term) {
426 exit_server_cleanly(NULL);
429 /* check for sighup processing */
430 if (reload_after_sighup) {
431 change_to_root_user();
432 DEBUG(1,("Reloading services after SIGHUP\n"));
433 reload_services(False);
434 reload_after_sighup = 0;
437 continue;
440 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
441 continue;
444 /* check if we need to reload services */
445 check_reload(time(NULL));
447 /* Find the sockets that are read-ready -
448 accept on these. */
449 for( ; num > 0; num--) {
450 struct sockaddr addr;
451 socklen_t in_addrlen = sizeof(addr);
452 pid_t child = 0;
454 s = -1;
455 for(i = 0; i < num_sockets; i++) {
456 if(FD_ISSET(fd_listenset[i],&r_fds)) {
457 s = fd_listenset[i];
458 /* Clear this so we don't look
459 at it again. */
460 FD_CLR(fd_listenset[i],&r_fds);
461 break;
465 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
467 if (smbd_server_fd() == -1 && errno == EINTR)
468 continue;
470 if (smbd_server_fd() == -1) {
471 DEBUG(0,("open_sockets_smbd: accept: %s\n",
472 strerror(errno)));
473 continue;
476 /* Ensure child is set to blocking mode */
477 set_blocking(smbd_server_fd(),True);
479 /* In interactive mode, return with a connected socket.
480 * Foreground and daemon modes should fork worker
481 * processes.
483 if (server_mode == SERVER_MODE_INTERACTIVE) {
484 return True;
487 if (allowable_number_of_smbd_processes() &&
488 smbd_server_fd() != -1 &&
489 ((child = sys_fork())==0)) {
490 /* Child code ... */
492 /* Stop zombies, the parent explicitly handles
493 * them, counting worker smbds. */
494 CatchChild();
496 /* close the listening socket(s) */
497 for(i = 0; i < num_sockets; i++)
498 close(fd_listenset[i]);
500 /* close our standard file
501 descriptors */
502 close_low_fds(False);
503 am_parent = 0;
505 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
506 set_socket_options(smbd_server_fd(),user_socket_options);
508 /* this is needed so that we get decent entries
509 in smbstatus for port 445 connects */
510 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
511 False);
513 /* Reset the state of the random
514 * number generation system, so
515 * children do not get the same random
516 * numbers as each other */
518 set_need_random_reseed();
519 /* tdb needs special fork handling - remove
520 * CLEAR_IF_FIRST flags */
521 if (tdb_reopen_all(1) == -1) {
522 DEBUG(0,("tdb_reopen_all failed.\n"));
523 smb_panic("tdb_reopen_all failed");
526 return True;
528 /* The parent doesn't need this socket */
529 close(smbd_server_fd());
531 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
532 Clear the closed fd info out of server_fd --
533 and more importantly, out of client_fd in
534 util_sock.c, to avoid a possible
535 getpeername failure if we reopen the logs
536 and use %I in the filename.
539 smbd_set_server_fd(-1);
541 if (child != 0) {
542 add_child_pid(child);
545 /* Force parent to check log size after
546 * spawning child. Fix from
547 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
548 * parent smbd will log to logserver.smb. It
549 * writes only two messages for each child
550 * started/finished. But each child writes,
551 * say, 50 messages also in logserver.smb,
552 * begining with the debug_count of the
553 * parent, before the child opens its own log
554 * file logserver.client. In a worst case
555 * scenario the size of logserver.smb would be
556 * checked after about 50*50=2500 messages
557 * (ca. 100kb).
558 * */
559 force_check_log_size();
561 } /* end for num */
562 } /* end while 1 */
564 /* NOTREACHED return True; */
567 /****************************************************************************
568 Reload printers
569 **************************************************************************/
570 void reload_printers(void)
572 int snum;
573 int n_services = lp_numservices();
574 int pnum = lp_servicenumber(PRINTERS_NAME);
575 const char *pname;
577 pcap_cache_reload();
579 /* remove stale printers */
580 for (snum = 0; snum < n_services; snum++) {
581 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
582 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
583 lp_autoloaded(snum)))
584 continue;
586 pname = lp_printername(snum);
587 if (!pcap_printername_ok(pname)) {
588 DEBUG(3, ("removing stale printer %s\n", pname));
590 if (is_printer_published(NULL, snum, NULL))
591 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
592 del_a_printer(pname);
593 lp_killservice(snum);
597 load_printers();
600 /****************************************************************************
601 Reload the services file.
602 **************************************************************************/
604 BOOL reload_services(BOOL test)
606 BOOL ret;
608 if (lp_loaded()) {
609 pstring fname;
610 pstrcpy(fname,lp_configfile());
611 if (file_exist(fname, NULL) &&
612 !strcsequal(fname, dyn_CONFIGFILE)) {
613 pstrcpy(dyn_CONFIGFILE, fname);
614 test = False;
618 reopen_logs();
620 if (test && !lp_file_list_changed())
621 return(True);
623 lp_killunused(conn_snum_used);
625 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
627 reload_printers();
629 /* perhaps the config filename is now set */
630 if (!test)
631 reload_services(True);
633 reopen_logs();
635 load_interfaces();
637 if (smbd_server_fd() != -1) {
638 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
639 set_socket_options(smbd_server_fd(), user_socket_options);
642 mangle_reset_cache();
643 reset_stat_cache();
645 /* this forces service parameters to be flushed */
646 set_current_service(NULL,0,True);
648 return(ret);
651 /****************************************************************************
652 Exit the server.
653 ****************************************************************************/
655 /* Reasons for shutting down a server process. */
656 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
658 static void exit_server_common(enum server_exit_reason how,
659 const char *const reason) NORETURN_ATTRIBUTE;
661 static void exit_server_common(enum server_exit_reason how,
662 const char *const reason)
664 static int firsttime=1;
666 if (!firsttime)
667 exit(0);
668 firsttime = 0;
670 change_to_root_user();
672 if (negprot_global_auth_context) {
673 (negprot_global_auth_context->free)(&negprot_global_auth_context);
676 conn_close_all();
678 invalidate_all_vuids();
680 /* 3 second timeout. */
681 print_notify_send_messages(smbd_messaging_context(), 3);
683 /* delete our entry in the connections database. */
684 yield_connection(NULL,"");
686 respond_to_all_remaining_local_messages();
688 #ifdef WITH_DFS
689 if (dcelogin_atmost_once) {
690 dfs_unlogin();
692 #endif
694 locking_end();
695 printing_end();
697 server_encryption_shutdown();
699 if (how != SERVER_EXIT_NORMAL) {
700 int oldlevel = DEBUGLEVEL;
702 DEBUGLEVEL = 10;
704 DEBUGSEP(0);
705 DEBUG(0,("Abnormal server exit: %s\n",
706 reason ? reason : "no explanation provided"));
707 DEBUGSEP(0);
709 log_stack_trace();
711 DEBUGLEVEL = oldlevel;
712 dump_core();
714 } else {
715 DEBUG(3,("Server exit (%s)\n",
716 (reason ? reason : "normal exit")));
719 exit(0);
722 void exit_server(const char *const explanation)
724 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
727 void exit_server_cleanly(const char *const explanation)
729 exit_server_common(SERVER_EXIT_NORMAL, explanation);
732 void exit_server_fault(void)
734 exit_server("critical server fault");
737 /****************************************************************************
738 Initialise connect, service and file structs.
739 ****************************************************************************/
741 static BOOL init_structs(void )
744 * Set the machine NETBIOS name if not already
745 * set from the config file.
748 if (!init_names())
749 return False;
751 conn_init();
753 file_init();
755 /* for RPC pipes */
756 init_rpc_pipe_hnd();
758 init_dptrs();
760 secrets_init();
762 return True;
766 * Send keepalive packets to our client
768 static BOOL keepalive_fn(const struct timeval *now, void *private_data)
770 if (!send_keepalive(smbd_server_fd())) {
771 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
772 return False;
774 return True;
778 * Do the recurring check if we're idle
780 static BOOL deadtime_fn(const struct timeval *now, void *private_data)
782 if ((conn_num_open() == 0)
783 || (conn_idle_all(now->tv_sec))) {
784 DEBUG( 2, ( "Closing idle connection\n" ) );
785 messaging_send(smbd_messaging_context(), procid_self(),
786 MSG_SHUTDOWN, &data_blob_null);
787 return False;
790 return True;
794 /****************************************************************************
795 main program.
796 ****************************************************************************/
798 /* Declare prototype for build_options() to avoid having to run it through
799 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
800 prototype generation system is too complicated. */
802 extern void build_options(BOOL screen);
804 int main(int argc,const char *argv[])
806 /* shall I run as a daemon */
807 BOOL no_process_group = False;
808 BOOL log_stdout = False;
809 const char *ports = NULL;
810 const char *profile_level = NULL;
811 int opt;
812 poptContext pc;
813 BOOL print_build_options = False;
815 enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
817 struct poptOption long_options[] = {
818 POPT_AUTOHELP
819 {"daemon", 'D', POPT_ARG_VAL, &server_mode, SERVER_MODE_DAEMON,
820 "Become a daemon (default)" },
821 {"interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE,
822 "Run interactive (not a daemon)"},
823 {"foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND,
824 "Run daemon in foreground (for daemontools, etc.)" },
825 {"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True,
826 "Don't create a new process group" },
827 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
828 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
829 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
830 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
831 POPT_COMMON_SAMBA
832 POPT_COMMON_DYNCONFIG
833 POPT_TABLEEND
836 load_case_tables();
838 TimeInit();
840 #ifdef HAVE_SET_AUTH_PARAMETERS
841 set_auth_parameters(argc,argv);
842 #endif
844 pc = poptGetContext("smbd", argc, argv, long_options, 0);
845 while((opt = poptGetNextOpt(pc)) != -1) {
846 switch (opt) {
847 case 'b':
848 print_build_options = True;
849 break;
850 default:
851 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
852 poptBadOption(pc, 0), poptStrerror(opt));
853 poptPrintUsage(pc, stderr, 0);
854 exit(1);
857 poptFreeContext(pc);
859 if (print_build_options) {
860 build_options(True); /* Display output to screen as well as debug */
861 exit(0);
864 #ifdef HAVE_SETLUID
865 /* needed for SecureWare on SCO */
866 setluid(0);
867 #endif
869 sec_init();
871 set_remote_machine_name("smbd", False);
873 if (server_mode == SERVER_MODE_INTERACTIVE) {
874 log_stdout = True;
875 if (DEBUGLEVEL >= 9) {
876 talloc_enable_leak_report();
880 if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
881 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
882 exit(1);
885 setup_logging(argv[0],log_stdout);
887 /* we want to re-seed early to prevent time delays causing
888 client problems at a later date. (tridge) */
889 generate_random_buffer(NULL, 0);
891 /* make absolutely sure we run as root - to handle cases where people
892 are crazy enough to have it setuid */
894 gain_root_privilege();
895 gain_root_group_privilege();
897 fault_setup((void (*)(void *))exit_server_fault);
898 dump_core_setup("smbd");
900 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
901 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
903 /* we are never interested in SIGPIPE */
904 BlockSignals(True,SIGPIPE);
906 #if defined(SIGFPE)
907 /* we are never interested in SIGFPE */
908 BlockSignals(True,SIGFPE);
909 #endif
911 #if defined(SIGUSR2)
912 /* We are no longer interested in USR2 */
913 BlockSignals(True,SIGUSR2);
914 #endif
916 /* POSIX demands that signals are inherited. If the invoking process has
917 * these signals masked, we will have problems, as we won't recieve them. */
918 BlockSignals(False, SIGHUP);
919 BlockSignals(False, SIGUSR1);
920 BlockSignals(False, SIGTERM);
922 /* we want total control over the permissions on created files,
923 so set our umask to 0 */
924 umask(0);
926 init_sec_ctx();
928 reopen_logs();
930 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
931 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
933 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
934 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
936 /* Output the build options to the debug log */
937 build_options(False);
939 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
940 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
941 exit(1);
945 * Do this before reload_services.
948 if (!reload_services(False))
949 return(-1);
951 init_structs();
953 #ifdef WITH_PROFILE
954 if (!profile_setup(smbd_messaging_context(), False)) {
955 DEBUG(0,("ERROR: failed to setup profiling\n"));
956 return -1;
958 if (profile_level != NULL) {
959 int pl = atoi(profile_level);
960 struct server_id src;
962 DEBUG(1, ("setting profiling level: %s\n",profile_level));
963 src.pid = getpid();
964 set_profile_level(pl, src);
966 #endif
968 DEBUG(3,( "loaded services\n"));
970 if (is_a_socket(0)) {
971 if (server_mode == SERVER_MODE_DAEMON) {
972 DEBUG(0,("standard input is a socket, "
973 "assuming -F option\n"));
975 server_mode = SERVER_MODE_INETD;
978 if (server_mode == SERVER_MODE_DAEMON) {
979 DEBUG( 3, ( "Becoming a daemon.\n" ) );
980 become_daemon(True, no_process_group);
981 } else if (server_mode == SERVER_MODE_FOREGROUND) {
982 become_daemon(False, no_process_group);
985 #if HAVE_SETPGID
987 * If we're interactive we want to set our own process group for
988 * signal management.
990 if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
991 setpgid( (pid_t)0, (pid_t)0);
993 #endif
995 if (!directory_exist(lp_lockdir(), NULL))
996 mkdir(lp_lockdir(), 0755);
998 if (server_mode != SERVER_MODE_INETD &&
999 server_mode != SERVER_MODE_INTERACTIVE) {
1000 pidfile_create("smbd");
1003 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1005 if (smbd_messaging_context() == NULL)
1006 exit(1);
1008 /* Initialise the password backed before the global_sam_sid
1009 to ensure that we fetch from ldap before we make a domain sid up */
1011 if(!initialize_password_db(False, smbd_event_context()))
1012 exit(1);
1014 if (!secrets_init()) {
1015 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1016 exit(1);
1019 if(!get_global_sam_sid()) {
1020 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1021 exit(1);
1024 if (!session_init())
1025 exit(1);
1027 if (!connections_init(True))
1028 exit(1);
1030 if (!locking_init(0))
1031 exit(1);
1033 namecache_enable();
1035 if (!init_registry())
1036 exit(1);
1038 #if 0
1039 if (!init_svcctl_db())
1040 exit(1);
1041 #endif
1043 if (!print_backend_init(smbd_messaging_context()))
1044 exit(1);
1046 if (!init_guest_info()) {
1047 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1048 return -1;
1051 /* only start the background queue daemon if we are
1052 running as a daemon -- bad things will happen if
1053 smbd is launched via inetd and we fork a copy of
1054 ourselves here */
1055 if (server_mode != SERVER_MODE_INETD &&
1056 server_mode != SERVER_MODE_INTERACTIVE) {
1057 start_background_queue();
1060 /* Always attempt to initialize DMAPI. We will only use it later if
1061 * lp_dmapi_support is set on the share, but we need a single global
1062 * session to work with.
1064 dmapi_init_session();
1066 if (!open_sockets_smbd(server_mode, ports)) {
1067 exit(1);
1071 * everything after this point is run after the fork()
1074 static_init_rpc;
1076 init_modules();
1078 /* Possibly reload the services file. Only worth doing in
1079 * daemon mode. In inetd mode, we know we only just loaded this.
1081 if (server_mode != SERVER_MODE_INETD &&
1082 server_mode != SERVER_MODE_INTERACTIVE) {
1083 reload_services(True);
1086 if (!init_account_policy()) {
1087 DEBUG(0,("Could not open account policy tdb.\n"));
1088 exit(1);
1091 if (*lp_rootdir()) {
1092 if (sys_chroot(lp_rootdir()) == 0)
1093 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1096 /* Setup oplocks */
1097 if (!init_oplocks(smbd_messaging_context()))
1098 exit(1);
1100 /* Setup aio signal handler. */
1101 initialize_async_io_handler();
1104 * For clustering, we need to re-init our ctdbd connection after the
1105 * fork
1107 if (!NT_STATUS_IS_OK(messaging_reinit(smbd_messaging_context())))
1108 exit(1);
1110 /* register our message handlers */
1111 messaging_register(smbd_messaging_context(), NULL,
1112 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1114 if ((lp_keepalive() != 0)
1115 && !(event_add_idle(smbd_event_context(), NULL,
1116 timeval_set(lp_keepalive(), 0),
1117 "keepalive", keepalive_fn,
1118 NULL))) {
1119 DEBUG(0, ("Could not add keepalive event\n"));
1120 exit(1);
1123 if (!(event_add_idle(smbd_event_context(), NULL,
1124 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1125 "deadtime", deadtime_fn, NULL))) {
1126 DEBUG(0, ("Could not add deadtime event\n"));
1127 exit(1);
1130 smbd_process();
1132 namecache_shutdown();
1134 exit_server_cleanly(NULL);
1135 return(0);