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) Volker Lendecke 1993-2007
8 Copyright (C) Jeremy Allison 1993-2007
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "smbd/globals.h"
26 #include "librpc/gen_ndr/messaging.h"
32 extern int dcelogin_atmost_once;
35 int smbd_server_fd(void)
40 static void smbd_set_server_fd(int fd)
45 int get_client_fd(void)
50 struct event_context *smbd_event_context(void)
52 if (!smbd_event_ctx) {
53 smbd_event_ctx = event_context_init(talloc_autofree_context());
55 if (!smbd_event_ctx) {
56 smb_panic("Could not init smbd event context");
58 return smbd_event_ctx;
61 struct messaging_context *smbd_messaging_context(void)
63 if (smbd_msg_ctx == NULL) {
64 smbd_msg_ctx = messaging_init(talloc_autofree_context(),
66 smbd_event_context());
68 if (smbd_msg_ctx == NULL) {
69 DEBUG(0, ("Could not init smbd messaging context.\n"));
74 struct memcache *smbd_memcache(void)
76 if (!smbd_memcache_ctx) {
77 smbd_memcache_ctx = memcache_init(talloc_autofree_context(),
78 lp_max_stat_cache_size()*1024);
80 if (!smbd_memcache_ctx) {
81 smb_panic("Could not init smbd memcache");
84 return smbd_memcache_ctx;
87 /*******************************************************************
88 What to do when smb.conf is updated.
89 ********************************************************************/
91 static void smb_conf_updated(struct messaging_context *msg,
94 struct server_id server_id,
97 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
98 "updated. Reloading.\n"));
99 change_to_root_user();
100 reload_services(False);
104 /*******************************************************************
105 Delete a statcache entry.
106 ********************************************************************/
108 static void smb_stat_cache_delete(struct messaging_context *msg,
111 struct server_id server_id,
114 const char *name = (const char *)data->data;
115 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
116 stat_cache_delete(name);
119 /****************************************************************************
120 Send a SIGTERM to our process group.
121 *****************************************************************************/
123 static void killkids(void)
125 if(am_parent) kill(0,SIGTERM);
128 /****************************************************************************
129 Process a sam sync message - not sure whether to do this here or
131 ****************************************************************************/
133 static void msg_sam_sync(struct messaging_context *msg,
136 struct server_id server_id,
139 DEBUG(10, ("** sam sync message received, ignoring\n"));
142 static void msg_exit_server(struct messaging_context *msg,
145 struct server_id server_id,
148 DEBUG(3, ("got a SHUTDOWN message\n"));
149 exit_server_cleanly(NULL);
153 static void msg_inject_fault(struct messaging_context *msg,
156 struct server_id src,
161 if (data->length != sizeof(sig)) {
162 DEBUG(0, ("Process %s sent bogus signal injection request\n",
163 procid_str_static(&src)));
167 sig = *(int *)data->data;
169 exit_server("internal error injected");
174 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
175 procid_str_static(&src), sig, strsignal(sig)));
177 DEBUG(0, ("Process %s requested injection of signal %d\n",
178 procid_str_static(&src), sig));
181 kill(sys_getpid(), sig);
183 #endif /* DEVELOPER */
186 * Parent smbd process sets its own debug level first and then
187 * sends a message to all the smbd children to adjust their debug
188 * level to that of the parent.
191 static void smbd_msg_debug(struct messaging_context *msg_ctx,
194 struct server_id server_id,
197 struct child_pid *child;
199 debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
201 for (child = children; child != NULL; child = child->next) {
202 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
205 strlen((char *) data->data) + 1);
209 static void add_child_pid(pid_t pid)
211 struct child_pid *child;
213 child = SMB_MALLOC_P(struct child_pid);
215 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
219 DLIST_ADD(children, child);
224 at most every smbd:cleanuptime seconds (default 20), we scan the BRL
225 and locking database for entries to cleanup. As a side effect this
226 also cleans up dead entries in the connections database (due to the
227 traversal in message_send_all()
229 Using a timer for this prevents a flood of traversals when a large
230 number of clients disconnect at the same time (perhaps due to a
234 static void cleanup_timeout_fn(struct event_context *event_ctx,
235 struct timed_event *te,
239 struct timed_event **cleanup_te = (struct timed_event **)private_data;
241 DEBUG(1,("Cleaning up brl and lock database after unclean shutdown\n"));
242 message_send_all(smbd_messaging_context(), MSG_SMB_UNLOCK, NULL, 0, NULL);
243 messaging_send_buf(smbd_messaging_context(), procid_self(),
244 MSG_SMB_BRL_VALIDATE, NULL, 0);
245 /* mark the cleanup as having been done */
246 (*cleanup_te) = NULL;
249 static void remove_child_pid(pid_t pid, bool unclean_shutdown)
251 struct child_pid *child;
252 static struct timed_event *cleanup_te;
253 struct server_id child_id;
255 if (unclean_shutdown) {
256 /* a child terminated uncleanly so tickle all
257 processes to see if they can grab any of the
260 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n",
263 /* call the cleanup timer, but not too often */
264 int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
265 cleanup_te = event_add_timed(smbd_event_context(), NULL,
266 timeval_current_ofs(cleanup_time, 0),
269 DEBUG(1,("Scheduled cleanup of brl and lock database after unclean shutdown\n"));
273 child_id = procid_self(); /* Just initialize pid and potentially vnn */
276 if (!serverid_deregister(&child_id)) {
277 DEBUG(1, ("Could not remove pid %d from serverid.tdb\n",
281 for (child = children; child != NULL; child = child->next) {
282 if (child->pid == pid) {
283 struct child_pid *tmp = child;
284 DLIST_REMOVE(children, child);
291 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
294 /****************************************************************************
295 Have we reached the process limit ?
296 ****************************************************************************/
298 static bool allowable_number_of_smbd_processes(void)
300 int max_processes = lp_max_smbd_processes();
305 return num_children < max_processes;
308 static void smbd_sig_chld_handler(struct tevent_context *ev,
309 struct tevent_signal *se,
318 while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
319 bool unclean_shutdown = False;
321 /* If the child terminated normally, assume
322 it was an unclean shutdown unless the
325 if (WIFEXITED(status)) {
326 unclean_shutdown = WEXITSTATUS(status);
328 /* If the child terminated due to a signal
329 we always assume it was unclean.
331 if (WIFSIGNALED(status)) {
332 unclean_shutdown = True;
334 remove_child_pid(pid, unclean_shutdown);
338 static void smbd_setup_sig_chld_handler(void)
340 struct tevent_signal *se;
342 se = tevent_add_signal(smbd_event_context(),
343 smbd_event_context(),
345 smbd_sig_chld_handler,
348 exit_server("failed to setup SIGCHLD handler");
352 struct smbd_open_socket;
354 struct smbd_parent_context {
357 /* the list of listening sockets */
358 struct smbd_open_socket *sockets;
361 struct smbd_open_socket {
362 struct smbd_open_socket *prev, *next;
363 struct smbd_parent_context *parent;
365 struct tevent_fd *fde;
368 static void smbd_open_socket_close_fn(struct tevent_context *ev,
369 struct tevent_fd *fde,
373 /* this might be the socket_wrapper swrap_close() */
377 static void smbd_accept_connection(struct tevent_context *ev,
378 struct tevent_fd *fde,
382 struct smbd_open_socket *s = talloc_get_type_abort(private_data,
383 struct smbd_open_socket);
384 struct sockaddr_storage addr;
385 socklen_t in_addrlen = sizeof(addr);
389 smbd_set_server_fd(accept(s->fd,(struct sockaddr *)&addr,&in_addrlen));
391 if (smbd_server_fd() == -1 && errno == EINTR)
394 if (smbd_server_fd() == -1) {
395 DEBUG(0,("open_sockets_smbd: accept: %s\n",
400 if (s->parent->interactive) {
402 exit_server_cleanly("end of interactive mode");
406 if (!allowable_number_of_smbd_processes()) {
407 close(smbd_server_fd());
408 smbd_set_server_fd(-1);
413 * Generate a unique id in the parent process so that we use
414 * the global random state in the parent.
416 generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
420 NTSTATUS status = NT_STATUS_OK;
425 set_my_unique_id(unique_id);
427 /* Stop zombies, the parent explicitly handles
428 * them, counting worker smbds. */
431 /* close our standard file
433 close_low_fds(False);
436 * Can't use TALLOC_FREE here. Nulling out the argument to it
437 * would overwrite memory we've just freed.
439 talloc_free(s->parent);
442 status = reinit_after_fork(smbd_messaging_context(),
443 smbd_event_context(), true);
444 if (!NT_STATUS_IS_OK(status)) {
445 if (NT_STATUS_EQUAL(status,
446 NT_STATUS_TOO_MANY_OPENED_FILES)) {
447 DEBUG(0,("child process cannot initialize "
448 "because too many files are open\n"));
451 DEBUG(0,("reinit_after_fork() failed\n"));
452 smb_panic("reinit_after_fork() failed");
455 smbd_setup_sig_term_handler();
456 smbd_setup_sig_hup_handler();
458 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
460 |FLAG_MSG_PRINT_GENERAL)) {
461 exit_server_cleanly("Could not register myself in "
467 exit_server_cleanly("end of child");
469 } else if (pid < 0) {
470 DEBUG(0,("smbd_accept_connection: sys_fork() failed: %s\n",
474 /* The parent doesn't need this socket */
475 close(smbd_server_fd());
477 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
478 Clear the closed fd info out of server_fd --
479 and more importantly, out of client_fd in
480 util_sock.c, to avoid a possible
481 getpeername failure if we reopen the logs
482 and use %I in the filename.
485 smbd_set_server_fd(-1);
491 /* Force parent to check log size after
492 * spawning child. Fix from
493 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
494 * parent smbd will log to logserver.smb. It
495 * writes only two messages for each child
496 * started/finished. But each child writes,
497 * say, 50 messages also in logserver.smb,
498 * begining with the debug_count of the
499 * parent, before the child opens its own log
500 * file logserver.client. In a worst case
501 * scenario the size of logserver.smb would be
502 * checked after about 50*50=2500 messages
505 force_check_log_size();
508 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
509 const struct sockaddr_storage *ifss,
512 struct smbd_open_socket *s;
514 s = talloc(parent, struct smbd_open_socket);
520 s->fd = open_socket_in(SOCK_STREAM,
522 parent->sockets == NULL ? 0 : 2,
526 DEBUG(0,("smbd_open_once_socket: open_socket_in: "
527 "%s\n", strerror(errno)));
530 * We ignore an error here, as we've done before
535 /* ready to listen */
536 set_socket_options(s->fd, "SO_KEEPALIVE");
537 set_socket_options(s->fd, lp_socket_options());
539 /* Set server socket to
540 * non-blocking for the accept. */
541 set_blocking(s->fd, False);
543 if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
544 DEBUG(0,("open_sockets_smbd: listen: "
545 "%s\n", strerror(errno)));
551 s->fde = tevent_add_fd(smbd_event_context(),
553 s->fd, TEVENT_FD_READ,
554 smbd_accept_connection,
557 DEBUG(0,("open_sockets_smbd: "
558 "tevent_add_fd: %s\n",
564 tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
566 DLIST_ADD_END(parent->sockets, s, struct smbd_open_socket *);
571 /****************************************************************************
572 Open the socket communication.
573 ****************************************************************************/
575 static bool open_sockets_smbd(struct smbd_parent_context *parent,
576 const char *smb_ports)
578 int num_interfaces = iface_count();
581 unsigned dns_port = 0;
588 smbd_setup_sig_chld_handler();
590 /* use a reasonable default set of ports - listing on 445 and 139 */
592 ports = lp_smb_ports();
593 if (!ports || !*ports) {
594 ports = talloc_strdup(talloc_tos(), SMB_PORTS);
596 ports = talloc_strdup(talloc_tos(), ports);
599 ports = talloc_strdup(talloc_tos(), smb_ports);
602 if (lp_interfaces() && lp_bind_interfaces_only()) {
603 /* We have been given an interfaces line, and been
604 told to only bind to those interfaces. Create a
605 socket per interface and bind to only these.
608 /* Now open a listen socket for each of the
610 for(i = 0; i < num_interfaces; i++) {
611 const struct sockaddr_storage *ifss =
612 iface_n_sockaddr_storage(i);
617 DEBUG(0,("open_sockets_smbd: "
618 "interface %d has NULL IP address !\n",
624 next_token_talloc(talloc_tos(),&ptr, &tok, " \t,");) {
625 unsigned port = atoi(tok);
626 if (port == 0 || port > 0xffff) {
630 if (!smbd_open_one_socket(parent, ifss, port)) {
636 /* Just bind to 0.0.0.0 - accept connections
641 const char *sock_addr = lp_socket_address();
643 const char *sock_ptr;
645 if (strequal(sock_addr, "0.0.0.0") ||
646 strequal(sock_addr, "::")) {
648 sock_addr = "::,0.0.0.0";
650 sock_addr = "0.0.0.0";
654 for (sock_ptr=sock_addr;
655 next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
656 for (ptr=ports; next_token_talloc(talloc_tos(), &ptr, &tok, " \t,"); ) {
657 struct sockaddr_storage ss;
659 unsigned port = atoi(tok);
660 if (port == 0 || port > 0xffff) {
664 /* Keep the first port for mDNS service
671 /* open an incoming socket */
672 if (!interpret_string_addr(&ss, sock_tok,
673 AI_NUMERICHOST|AI_PASSIVE)) {
677 if (!smbd_open_one_socket(parent, &ss, port)) {
684 if (parent->sockets == NULL) {
685 DEBUG(0,("open_sockets_smbd: No "
686 "sockets available to bind to.\n"));
690 /* Setup the main smbd so that we can get messages. Note that
691 do this after starting listening. This is needed as when in
692 clustered mode, ctdb won't allow us to start doing database
693 operations until it has gone thru a full startup, which
694 includes checking to see that smbd is listening. */
696 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
698 DEBUG(0, ("open_sockets_smbd: Failed to register "
699 "myself in serverid.tdb\n"));
703 /* Listen to messages */
705 messaging_register(smbd_messaging_context(), NULL,
706 MSG_SMB_SAM_SYNC, msg_sam_sync);
707 messaging_register(smbd_messaging_context(), NULL,
708 MSG_SHUTDOWN, msg_exit_server);
709 messaging_register(smbd_messaging_context(), NULL,
710 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
711 messaging_register(smbd_messaging_context(), NULL,
712 MSG_SMB_CONF_UPDATED, smb_conf_updated);
713 messaging_register(smbd_messaging_context(), NULL,
714 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
715 messaging_register(smbd_messaging_context(), NULL,
716 MSG_DEBUG, smbd_msg_debug);
717 brl_register_msgs(smbd_messaging_context());
719 #ifdef CLUSTER_SUPPORT
720 if (lp_clustering()) {
721 ctdbd_register_reconfigure(messaging_ctdbd_connection());
726 messaging_register(smbd_messaging_context(), NULL,
727 MSG_SMB_INJECT_FAULT, msg_inject_fault);
731 #ifdef WITH_DNSSD_SUPPORT
732 smbd_setup_mdns_registration(smbd_event_context(),
735 #ifdef WITH_AVAHI_SUPPORT
738 avahi_conn = avahi_start_register(
739 smbd_event_context(), smbd_event_context(), dns_port);
740 if (avahi_conn == NULL) {
741 DEBUG(10, ("avahi_start_register failed\n"));
749 static void smbd_parent_loop(struct smbd_parent_context *parent)
751 /* now accept incoming connections - forking a new process
752 for each incoming connection */
753 DEBUG(2,("waiting for connections\n"));
756 TALLOC_CTX *frame = talloc_stackframe();
758 ret = tevent_loop_once(smbd_event_context());
760 exit_server_cleanly("tevent_loop_once() error");
766 /* NOTREACHED return True; */
769 /****************************************************************************
771 **************************************************************************/
772 void reload_printers(void)
775 int n_services = lp_numservices();
776 int pnum = lp_servicenumber(PRINTERS_NAME);
781 /* remove stale printers */
782 for (snum = 0; snum < n_services; snum++) {
783 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
784 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
785 lp_autoloaded(snum)))
788 pname = lp_printername(snum);
789 if (!pcap_printername_ok(pname)) {
790 DEBUG(3, ("removing stale printer %s\n", pname));
792 if (is_printer_published(NULL, snum, NULL))
793 nt_printer_publish(NULL, snum, DSPRINT_UNPUBLISH);
794 del_a_printer(pname);
795 lp_killservice(snum);
802 /****************************************************************************
803 Reload the services file.
804 **************************************************************************/
806 bool reload_services(bool test)
811 char *fname = lp_configfile();
812 if (file_exist(fname) &&
813 !strcsequal(fname, get_dyn_CONFIGFILE())) {
814 set_dyn_CONFIGFILE(fname);
821 if (test && !lp_file_list_changed())
824 lp_killunused(conn_snum_used);
826 ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
830 /* perhaps the config filename is now set */
832 reload_services(True);
838 if (smbd_server_fd() != -1) {
839 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
840 set_socket_options(smbd_server_fd(), lp_socket_options());
843 mangle_reset_cache();
846 /* this forces service parameters to be flushed */
847 set_current_service(NULL,0,True);
852 static struct files_struct *log_writeable_file_fn(
853 struct files_struct *fsp, void *private_data)
855 bool *found = (bool *)private_data;
858 if (!fsp->can_write) {
862 DEBUG(0, ("Writable files open at exit:\n"));
866 path = talloc_asprintf(talloc_tos(), "%s/%s", fsp->conn->connectpath,
867 smb_fname_str_dbg(fsp->fsp_name));
869 DEBUGADD(0, ("<NOMEM>\n"));
872 DEBUGADD(0, ("%s\n", path));
878 /****************************************************************************
880 ****************************************************************************/
882 /* Reasons for shutting down a server process. */
883 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
885 static void exit_server_common(enum server_exit_reason how,
886 const char *const reason) _NORETURN_;
888 static void exit_server_common(enum server_exit_reason how,
889 const char *const reason)
891 bool had_open_conn = false;
892 struct smbd_server_connection *sconn = smbd_server_conn;
896 exit_firsttime = false;
898 change_to_root_user();
900 if (sconn && sconn->smb1.negprot.auth_context) {
901 struct auth_context *a = sconn->smb1.negprot.auth_context;
902 a->free(&sconn->smb1.negprot.auth_context);
905 if (lp_log_writeable_files_on_exit()) {
907 files_forall(log_writeable_file_fn, &found);
911 had_open_conn = conn_close_all(sconn);
912 invalidate_all_vuids(sconn);
915 /* 3 second timeout. */
916 print_notify_send_messages(smbd_messaging_context(), 3);
918 /* delete our entry in the serverid database. */
919 serverid_deregister_self();
922 if (dcelogin_atmost_once) {
928 /* Destroy Samba DMAPI session only if we are master smbd process */
930 if (!dmapi_destroy_session()) {
931 DEBUG(0,("Unable to close Samba DMAPI session\n"));
940 * we need to force the order of freeing the following,
941 * because smbd_msg_ctx is not a talloc child of smbd_server_conn.
944 TALLOC_FREE(smbd_server_conn);
945 TALLOC_FREE(smbd_msg_ctx);
946 TALLOC_FREE(smbd_event_ctx);
948 if (how != SERVER_EXIT_NORMAL) {
949 int oldlevel = DEBUGLEVEL;
954 DEBUG(0,("Abnormal server exit: %s\n",
955 reason ? reason : "no explanation provided"));
960 DEBUGLEVEL = oldlevel;
964 DEBUG(3,("Server exit (%s)\n",
965 (reason ? reason : "normal exit")));
969 gencache_stabilize();
972 /* if we had any open SMB connections when we exited then we
973 need to tell the parent smbd so that it can trigger a retry
974 of any locks we may have been holding or open files we were
983 void exit_server(const char *const explanation)
985 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
988 void exit_server_cleanly(const char *const explanation)
990 exit_server_common(SERVER_EXIT_NORMAL, explanation);
993 void exit_server_fault(void)
995 exit_server("critical server fault");
998 /****************************************************************************
999 Initialise connect, service and file structs.
1000 ****************************************************************************/
1002 static bool init_structs(void )
1005 * Set the machine NETBIOS name if not already
1006 * set from the config file.
1014 if (!secrets_init())
1020 /****************************************************************************
1022 ****************************************************************************/
1024 /* Declare prototype for build_options() to avoid having to run it through
1025 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1026 prototype generation system is too complicated. */
1028 extern void build_options(bool screen);
1030 int main(int argc,const char *argv[])
1032 /* shall I run as a daemon */
1033 bool is_daemon = false;
1034 bool interactive = false;
1036 bool no_process_group = false;
1037 bool log_stdout = false;
1039 char *profile_level = NULL;
1042 bool print_build_options = False;
1047 OPT_NO_PROCESS_GROUP,
1050 struct poptOption long_options[] = {
1052 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1053 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1054 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1055 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1056 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1057 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1058 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1059 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1061 POPT_COMMON_DYNCONFIG
1064 struct smbd_parent_context *parent = NULL;
1065 TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
1067 smbd_init_globals();
1071 #ifdef HAVE_SET_AUTH_PARAMETERS
1072 set_auth_parameters(argc,argv);
1075 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1076 while((opt = poptGetNextOpt(pc)) != -1) {
1081 case OPT_INTERACTIVE:
1087 case OPT_NO_PROCESS_GROUP:
1088 no_process_group = true;
1090 case OPT_LOG_STDOUT:
1094 print_build_options = True;
1097 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1098 poptBadOption(pc, 0), poptStrerror(opt));
1099 poptPrintUsage(pc, stderr, 0);
1103 poptFreeContext(pc);
1110 setup_logging(argv[0],log_stdout);
1112 if (print_build_options) {
1113 build_options(True); /* Display output to screen as well as debug */
1120 /* needed for SecureWare on SCO */
1126 set_remote_machine_name("smbd", False);
1128 if (interactive && (DEBUGLEVEL >= 9)) {
1129 talloc_enable_leak_report();
1132 if (log_stdout && Fork) {
1133 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1137 /* we want to re-seed early to prevent time delays causing
1138 client problems at a later date. (tridge) */
1139 generate_random_buffer(NULL, 0);
1141 /* make absolutely sure we run as root - to handle cases where people
1142 are crazy enough to have it setuid */
1144 gain_root_privilege();
1145 gain_root_group_privilege();
1147 fault_setup((void (*)(void *))exit_server_fault);
1148 dump_core_setup("smbd");
1150 /* we are never interested in SIGPIPE */
1151 BlockSignals(True,SIGPIPE);
1154 /* we are never interested in SIGFPE */
1155 BlockSignals(True,SIGFPE);
1158 #if defined(SIGUSR2)
1159 /* We are no longer interested in USR2 */
1160 BlockSignals(True,SIGUSR2);
1163 /* POSIX demands that signals are inherited. If the invoking process has
1164 * these signals masked, we will have problems, as we won't recieve them. */
1165 BlockSignals(False, SIGHUP);
1166 BlockSignals(False, SIGUSR1);
1167 BlockSignals(False, SIGTERM);
1169 /* Ensure we leave no zombies until we
1170 * correctly set up child handling below. */
1174 /* we want total control over the permissions on created files,
1175 so set our umask to 0 */
1182 DEBUG(0,("smbd version %s started.\n", samba_version_string()));
1183 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1185 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1186 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1188 /* Output the build options to the debug log */
1189 build_options(False);
1191 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1192 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1196 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1197 DEBUG(0, ("error opening config file\n"));
1201 if (smbd_messaging_context() == NULL)
1204 if (!reload_services(False))
1210 if (!profile_setup(smbd_messaging_context(), False)) {
1211 DEBUG(0,("ERROR: failed to setup profiling\n"));
1214 if (profile_level != NULL) {
1215 int pl = atoi(profile_level);
1216 struct server_id src;
1218 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1220 set_profile_level(pl, src);
1224 DEBUG(3,( "loaded services\n"));
1226 if (!is_daemon && !is_a_socket(0)) {
1228 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1231 * Setting is_daemon here prevents us from eventually calling
1232 * the open_sockets_inetd()
1238 if (is_daemon && !interactive) {
1239 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1240 become_daemon(Fork, no_process_group, log_stdout);
1245 * If we're interactive we want to set our own process group for
1246 * signal management.
1248 if (interactive && !no_process_group)
1249 setpgid( (pid_t)0, (pid_t)0);
1252 if (!directory_exist(lp_lockdir()))
1253 mkdir(lp_lockdir(), 0755);
1256 pidfile_create("smbd");
1258 if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1259 smbd_event_context(), false))) {
1260 DEBUG(0,("reinit_after_fork() failed\n"));
1264 smbd_setup_sig_term_handler();
1265 smbd_setup_sig_hup_handler();
1267 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1269 if (smbd_memcache() == NULL) {
1273 memcache_set_global(smbd_memcache());
1275 /* Initialise the password backed before the global_sam_sid
1276 to ensure that we fetch from ldap before we make a domain sid up */
1278 if(!initialize_password_db(False, smbd_event_context()))
1281 if (!secrets_init()) {
1282 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1286 if(!get_global_sam_sid()) {
1287 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1291 if (!sessionid_init()) {
1295 if (!connections_init(True))
1298 if (!locking_init())
1301 if (!messaging_tdb_parent_init()) {
1305 if (!notify_internal_parent_init()) {
1309 if (!serverid_parent_init()) {
1313 if (!W_ERROR_IS_OK(registry_init_full()))
1317 if (!init_svcctl_db())
1321 if (!print_backend_init(smbd_messaging_context()))
1324 if (!init_guest_info()) {
1325 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1329 /* Open the share_info.tdb here, so we don't have to open
1330 after the fork on every single connection. This is a small
1331 performance improvment and reduces the total number of system
1333 if (!share_info_db_init()) {
1334 DEBUG(0,("ERROR: failed to load share info db.\n"));
1338 /* only start the background queue daemon if we are
1339 running as a daemon -- bad things will happen if
1340 smbd is launched via inetd and we fork a copy of
1343 if (is_daemon && !interactive
1344 && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1345 start_background_queue();
1352 /* Started from inetd. fd 0 is the socket. */
1353 /* We will abort gracefully when the client or remote system
1355 smbd_set_server_fd(dup(0));
1357 /* close our standard file descriptors */
1358 close_low_fds(False); /* Don't close stderr */
1365 smbd_setup_sig_chld_handler();
1369 exit_server_cleanly(NULL);
1373 parent = talloc_zero(smbd_event_context(), struct smbd_parent_context);
1375 exit_server("talloc(struct smbd_parent_context) failed");
1377 parent->interactive = interactive;
1379 if (!open_sockets_smbd(parent, ports))
1380 exit_server("open_sockets_smbd() failed");
1383 /* make sure we always have a valid stackframe */
1384 frame = talloc_stackframe();
1386 smbd_parent_loop(parent);
1388 exit_server_cleanly(NULL);