s3:smbd: pass smbd_server_connection to smbd_setup_sig_term_handler()
[ira/wip.git] / source3 / smbd / server.c
index 81283f0ec956551fb6f59dd6c2652be348a4639d..f7edc9996e40e2ae88ee0912308a6138a571ee4f 100644 (file)
 */
 
 #include "includes.h"
+#include "system/filesys.h"
 #include "popt_common.h"
+#include "smbd/smbd.h"
 #include "smbd/globals.h"
-#include "librpc/gen_ndr/messaging.h"
-#include "registry.h"
 #include "registry/reg_init_full.h"
 #include "libcli/auth/schannel.h"
 #include "secrets.h"
 #include "memcache.h"
 #include "ctdbd_conn.h"
-#include "printing/printer_list.h"
-#include "rpc_server/rpc_ep_setup.h"
-#include "printing/pcap.h"
-#include "printing.h"
+#include "printing/queue_process.h"
+#include "rpc_server/rpc_service_setup.h"
+#include "rpc_server/rpc_config.h"
+#include "serverid.h"
+#include "passdb.h"
+#include "auth.h"
+#include "messages.h"
+#include "smbprofile.h"
+#include "lib/id_cache.h"
+#include "lib/param/param.h"
+
+extern void start_epmd(struct tevent_context *ev_ctx,
+                      struct messaging_context *msg_ctx);
+
+extern void start_lsasd(struct event_context *ev_ctx,
+                       struct messaging_context *msg_ctx);
 
 #ifdef WITH_DFS
 extern int dcelogin_atmost_once;
 #endif /* WITH_DFS */
 
-static void smbd_set_server_fd(int fd)
-{
-       struct smbd_server_connection *sconn = smbd_server_conn;
-       char addr[INET6_ADDRSTRLEN];
-       const char *name;
-
-       sconn->sock = fd;
-
-       /*
-        * Initialize sconn->client_id: If we can't find the client's
-        * name, default to its address.
-        */
-
-       client_addr(fd, sconn->client_id.addr, sizeof(sconn->client_id.addr));
-
-       name = client_name(sconn->sock);
-       if (strcmp(name, "UNKNOWN") != 0) {
-               name = talloc_strdup(sconn, name);
-       } else {
-               name = NULL;
-       }
-       sconn->client_id.name =
-               (name != NULL) ? name : sconn->client_id.addr;
-
-       sub_set_socket_ids(sconn->client_id.addr, sconn->client_id.name,
-                          client_socket_addr(sconn->sock, addr,
-                                             sizeof(addr)));
-}
-
-struct event_context *smbd_event_context(void)
-{
-       return server_event_context();
-}
-
 /*******************************************************************
  What to do when smb.conf is updated.
  ********************************************************************/
@@ -84,13 +62,16 @@ static void smb_conf_updated(struct messaging_context *msg,
                             struct server_id server_id,
                             DATA_BLOB *data)
 {
+       struct tevent_context *ev_ctx =
+               talloc_get_type_abort(private_data, struct tevent_context);
+       struct smbd_server_connection *sconn = msg_ctx_to_sconn(msg);
+
        DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
                  "updated. Reloading.\n"));
        change_to_root_user();
-       reload_services(msg, smbd_server_conn->sock, False);
+       reload_services(msg, sconn->sock, False);
        if (am_parent) {
-               pcap_cache_reload(server_event_context(), msg,
-                                 &reload_pcap_change_notify);
+               printing_subsystem_update(ev_ctx, msg, false);
        }
 }
 
@@ -104,9 +85,12 @@ static void smb_pcap_updated(struct messaging_context *msg,
                             struct server_id server_id,
                             DATA_BLOB *data)
 {
+       struct tevent_context *ev_ctx =
+               talloc_get_type_abort(private_data, struct tevent_context);
+
        DEBUG(10,("Got message saying pcap was updated. Reloading.\n"));
        change_to_root_user();
-       reload_printers(server_event_context(), msg);
+       delete_and_reload_printers(ev_ctx, msg);
 }
 
 /*******************************************************************
@@ -133,20 +117,6 @@ static void  killkids(void)
        if(am_parent) kill(0,SIGTERM);
 }
 
-/****************************************************************************
- Process a sam sync message - not sure whether to do this here or
- somewhere else.
-****************************************************************************/
-
-static void msg_sam_sync(struct messaging_context *msg,
-                        void *private_data,
-                        uint32_t msg_type,
-                        struct server_id server_id,
-                        DATA_BLOB *data)
-{
-        DEBUG(10, ("** sam sync message received, ignoring\n"));
-}
-
 static void msg_exit_server(struct messaging_context *msg,
                            void *private_data,
                            uint32_t msg_type,
@@ -190,6 +160,22 @@ static void msg_inject_fault(struct messaging_context *msg,
 }
 #endif /* DEVELOPER */
 
+NTSTATUS messaging_send_to_children(struct messaging_context *msg_ctx,
+                                   uint32_t msg_type, DATA_BLOB* data)
+{
+       NTSTATUS status;
+       struct child_pid *child;
+
+       for (child = children; child != NULL; child = child->next) {
+               status = messaging_send(msg_ctx, pid_to_procid(child->pid),
+                                       msg_type, data);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+       }
+       return NT_STATUS_OK;
+}
+
 /*
  * Parent smbd process sets its own debug level first and then
  * sends a message to all the smbd children to adjust their debug
@@ -202,16 +188,9 @@ static void smbd_msg_debug(struct messaging_context *msg_ctx,
                           struct server_id server_id,
                           DATA_BLOB *data)
 {
-       struct child_pid *child;
-
        debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
 
-       for (child = children; child != NULL; child = child->next) {
-               messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
-                                  MSG_DEBUG,
-                                  data->data,
-                                  strlen((char *) data->data) + 1);
-       }
+       messaging_send_to_children(msg_ctx, MSG_DEBUG, data);
 }
 
 static void add_child_pid(pid_t pid)
@@ -245,16 +224,19 @@ static void cleanup_timeout_fn(struct event_context *event_ctx,
                                void *private_data)
 {
        struct timed_event **cleanup_te = (struct timed_event **)private_data;
+       struct messaging_context *msg = smbd_messaging_context();
 
        DEBUG(1,("Cleaning up brl and lock database after unclean shutdown\n"));
-       message_send_all(smbd_messaging_context(), MSG_SMB_UNLOCK, NULL, 0, NULL);
-       messaging_send_buf(smbd_messaging_context(), procid_self(),
+       message_send_all(msg, MSG_SMB_UNLOCK, NULL, 0, NULL);
+       messaging_send_buf(msg, messaging_server_id(msg),
                                MSG_SMB_BRL_VALIDATE, NULL, 0);
        /* mark the cleanup as having been done */
        (*cleanup_te) = NULL;
 }
 
-static void remove_child_pid(pid_t pid, bool unclean_shutdown)
+static void remove_child_pid(struct tevent_context *ev_ctx,
+                            pid_t pid,
+                            bool unclean_shutdown)
 {
        struct child_pid *child;
        static struct timed_event *cleanup_te;
@@ -270,7 +252,7 @@ static void remove_child_pid(pid_t pid, bool unclean_shutdown)
                if (!cleanup_te) {
                        /* call the cleanup timer, but not too often */
                        int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
-                       cleanup_te = event_add_timed(smbd_event_context(), NULL,
+                       cleanup_te = event_add_timed(ev_ctx, NULL,
                                                timeval_current_ofs(cleanup_time, 0),
                                                cleanup_timeout_fn,
                                                &cleanup_te);
@@ -278,8 +260,7 @@ static void remove_child_pid(pid_t pid, bool unclean_shutdown)
                }
        }
 
-       child_id = procid_self(); /* Just initialize pid and potentially vnn */
-       child_id.pid = pid;
+       child_id = pid_to_procid(pid);
 
        if (!serverid_deregister(child_id)) {
                DEBUG(1, ("Could not remove pid %d from serverid.tdb\n",
@@ -340,16 +321,16 @@ static void smbd_sig_chld_handler(struct tevent_context *ev,
                if (WIFSIGNALED(status)) {
                        unclean_shutdown = True;
                }
-               remove_child_pid(pid, unclean_shutdown);
+               remove_child_pid(ev, pid, unclean_shutdown);
        }
 }
 
-static void smbd_setup_sig_chld_handler(void)
+static void smbd_setup_sig_chld_handler(struct tevent_context *ev_ctx)
 {
        struct tevent_signal *se;
 
-       se = tevent_add_signal(smbd_event_context(),
-                              smbd_event_context(),
+       se = tevent_add_signal(ev_ctx,
+                              ev_ctx, /* mem_ctx */
                               SIGCHLD, 0,
                               smbd_sig_chld_handler,
                               NULL);
@@ -363,6 +344,9 @@ struct smbd_open_socket;
 struct smbd_parent_context {
        bool interactive;
 
+       struct tevent_context *ev_ctx;
+       struct messaging_context *msg_ctx;
+
        /* the list of listening sockets */
        struct smbd_open_socket *sockets;
 };
@@ -390,6 +374,8 @@ static void smbd_accept_connection(struct tevent_context *ev,
 {
        struct smbd_open_socket *s = talloc_get_type_abort(private_data,
                                     struct smbd_open_socket);
+       struct messaging_context *msg_ctx = s->parent->msg_ctx;
+       struct smbd_server_connection *sconn = msg_ctx_to_sconn(msg_ctx);
        struct sockaddr_storage addr;
        socklen_t in_addrlen = sizeof(addr);
        int fd;
@@ -397,8 +383,7 @@ static void smbd_accept_connection(struct tevent_context *ev,
        uint64_t unique_id;
 
        fd = accept(s->fd, (struct sockaddr *)(void *)&addr,&in_addrlen);
-       smbd_set_server_fd(fd);
-
+       sconn->sock = fd;
        if (fd == -1 && errno == EINTR)
                return;
 
@@ -409,14 +394,14 @@ static void smbd_accept_connection(struct tevent_context *ev,
        }
 
        if (s->parent->interactive) {
-               smbd_process(smbd_server_conn);
+               smbd_process(ev, sconn);
                exit_server_cleanly("end of interactive mode");
                return;
        }
 
        if (!allowable_number_of_smbd_processes()) {
                close(fd);
-               smbd_set_server_fd(-1);
+               sconn->sock = -1;
                return;
        }
 
@@ -441,7 +426,9 @@ static void smbd_accept_connection(struct tevent_context *ev,
 
                /* close our standard file
                   descriptors */
-               close_low_fds(False);
+               if (!debug_get_output_is_stdout()) {
+                       close_low_fds(False); /* Don't close stderr */
+               }
 
                /*
                 * Can't use TALLOC_FREE here. Nulling out the argument to it
@@ -450,8 +437,8 @@ static void smbd_accept_connection(struct tevent_context *ev,
                talloc_free(s->parent);
                s = NULL;
 
-               status = reinit_after_fork(smbd_messaging_context(),
-                                          smbd_event_context(), procid_self(),
+               status = reinit_after_fork(msg_ctx,
+                                          ev,
                                           true);
                if (!NT_STATUS_IS_OK(status)) {
                        if (NT_STATUS_EQUAL(status,
@@ -460,15 +447,24 @@ static void smbd_accept_connection(struct tevent_context *ev,
                                         "because too many files are open\n"));
                                goto exit;
                        }
+                       if (lp_clustering() &&
+                           NT_STATUS_EQUAL(status,
+                           NT_STATUS_INTERNAL_DB_ERROR)) {
+                               DEBUG(1,("child process cannot initialize "
+                                        "because connection to CTDB "
+                                        "has failed\n"));
+                               goto exit;
+                       }
+
                        DEBUG(0,("reinit_after_fork() failed\n"));
                        smb_panic("reinit_after_fork() failed");
                }
 
-               smbd_setup_sig_term_handler();
-               smbd_setup_sig_hup_handler(server_event_context(),
-                                          server_messaging_context());
+               smbd_setup_sig_term_handler(sconn);
+               smbd_setup_sig_hup_handler(ev,
+                                          msg_ctx);
 
-               if (!serverid_register(procid_self(),
+               if (!serverid_register(messaging_server_id(msg_ctx),
                                       FLAG_MSG_GENERAL|FLAG_MSG_SMBD
                                       |FLAG_MSG_DBWRAP
                                       |FLAG_MSG_PRINT_GENERAL)) {
@@ -476,7 +472,7 @@ static void smbd_accept_connection(struct tevent_context *ev,
                                            "serverid.tdb");
                }
 
-               smbd_process(smbd_server_conn);
+               smbd_process(ev, sconn);
         exit:
                exit_server_cleanly("end of child");
                return;
@@ -497,8 +493,7 @@ static void smbd_accept_connection(struct tevent_context *ev,
                getpeername failure if we reopen the logs
                and use %I in the filename.
        */
-
-       smbd_set_server_fd(-1);
+       sconn->sock = -1;
 
        if (pid != 0) {
                add_child_pid(pid);
@@ -522,6 +517,8 @@ static void smbd_accept_connection(struct tevent_context *ev,
 }
 
 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
+                                struct tevent_context *ev_ctx,
+                                struct messaging_context *msg_ctx,
                                 const struct sockaddr_storage *ifss,
                                 uint16_t port)
 {
@@ -564,7 +561,7 @@ static bool smbd_open_one_socket(struct smbd_parent_context *parent,
                return false;
        }
 
-       s->fde = tevent_add_fd(smbd_event_context(),
+       s->fde = tevent_add_fd(ev_ctx,
                               s,
                               s->fd, TEVENT_FD_READ,
                               smbd_accept_connection,
@@ -584,37 +581,18 @@ static bool smbd_open_one_socket(struct smbd_parent_context *parent,
        return true;
 }
 
-static bool smbd_parent_housekeeping(const struct timeval *now, void *private_data)
-{
-       time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
-       time_t t = time_mono(NULL);
-
-       DEBUG(5, ("parent housekeeping\n"));
-
-       /* if periodic printcap rescan is enabled, see if it's time to reload */
-       if ((printcap_cache_time != 0)
-        && (t >= (last_printer_reload_time + printcap_cache_time))) {
-               DEBUG( 3,( "Printcap cache time expired.\n"));
-               pcap_cache_reload(server_event_context(),
-                                 smbd_messaging_context(),
-                                 &reload_pcap_change_notify);
-               last_printer_reload_time = t;
-       }
-
-       return true;
-}
-
 /****************************************************************************
  Open the socket communication.
 ****************************************************************************/
 
 static bool open_sockets_smbd(struct smbd_parent_context *parent,
+                             struct tevent_context *ev_ctx,
                              struct messaging_context *msg_ctx,
                              const char *smb_ports)
 {
        int num_interfaces = iface_count();
        int i;
-       char *ports;
+       const char *ports;
        unsigned dns_port = 0;
 
 #ifdef HAVE_ATEXIT
@@ -622,7 +600,7 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
 #endif
 
        /* Stop zombies */
-       smbd_setup_sig_chld_handler();
+       smbd_setup_sig_chld_handler(ev_ctx);
 
        /* use a reasonable default set of ports - listing on 445 and 139 */
        if (!smb_ports) {
@@ -664,7 +642,18 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
                                        continue;
                                }
 
-                               if (!smbd_open_one_socket(parent, ifss, port)) {
+                               /* Keep the first port for mDNS service
+                                * registration.
+                                */
+                               if (dns_port == 0) {
+                                       dns_port = port;
+                               }
+
+                               if (!smbd_open_one_socket(parent,
+                                                         ev_ctx,
+                                                         msg_ctx,
+                                                         ifss,
+                                                         port)) {
                                        return false;
                                }
                        }
@@ -711,7 +700,11 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
                                        continue;
                                }
 
-                               if (!smbd_open_one_socket(parent, &ss, port)) {
+                               if (!smbd_open_one_socket(parent,
+                                                         ev_ctx,
+                                                         msg_ctx,
+                                                         &ss,
+                                                         port)) {
                                        return false;
                                }
                        }
@@ -730,36 +723,29 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
           operations until it has gone thru a full startup, which
           includes checking to see that smbd is listening. */
 
-       if (!serverid_register(procid_self(),
+       if (!serverid_register(messaging_server_id(msg_ctx),
                               FLAG_MSG_GENERAL|FLAG_MSG_SMBD
+                              |FLAG_MSG_PRINT_GENERAL
                               |FLAG_MSG_DBWRAP)) {
                DEBUG(0, ("open_sockets_smbd: Failed to register "
                          "myself in serverid.tdb\n"));
                return false;
        }
 
-       if (!(event_add_idle(smbd_event_context(), NULL,
-                            timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
-                            "parent_housekeeping", smbd_parent_housekeeping,
-                            NULL))) {
-               DEBUG(0, ("Could not add parent_housekeeping event\n"));
-               return false;
-       }
-
         /* Listen to messages */
 
-       messaging_register(msg_ctx, NULL, MSG_SMB_SAM_SYNC, msg_sam_sync);
        messaging_register(msg_ctx, NULL, MSG_SHUTDOWN, msg_exit_server);
-       messaging_register(msg_ctx, NULL, MSG_SMB_FILE_RENAME,
-                          msg_file_was_renamed);
-       messaging_register(msg_ctx, NULL, MSG_SMB_CONF_UPDATED,
+       messaging_register(msg_ctx, ev_ctx, MSG_SMB_CONF_UPDATED,
                           smb_conf_updated);
        messaging_register(msg_ctx, NULL, MSG_SMB_STAT_CACHE_DELETE,
                           smb_stat_cache_delete);
        messaging_register(msg_ctx, NULL, MSG_DEBUG, smbd_msg_debug);
-       messaging_register(msg_ctx, NULL, MSG_PRINTER_PCAP, smb_pcap_updated);
+       messaging_register(msg_ctx, ev_ctx, MSG_PRINTER_PCAP,
+                          smb_pcap_updated);
        brl_register_msgs(msg_ctx);
 
+       msg_idmap_register_msg(msg_ctx);
+
 #ifdef CLUSTER_SUPPORT
        if (lp_clustering()) {
                ctdbd_register_reconfigure(messaging_ctdbd_connection());
@@ -773,14 +759,15 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
 
        if (lp_multicast_dns_register() && (dns_port != 0)) {
 #ifdef WITH_DNSSD_SUPPORT
-               smbd_setup_mdns_registration(smbd_event_context(),
+               smbd_setup_mdns_registration(ev_ctx,
                                             parent, dns_port);
 #endif
 #ifdef WITH_AVAHI_SUPPORT
                void *avahi_conn;
 
-               avahi_conn = avahi_start_register(
-                       smbd_event_context(), smbd_event_context(), dns_port);
+               avahi_conn = avahi_start_register(ev_ctx,
+                                                 ev_ctx,
+                                                 dns_port);
                if (avahi_conn == NULL) {
                        DEBUG(10, ("avahi_start_register failed\n"));
                }
@@ -790,7 +777,8 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
        return true;
 }
 
-static void smbd_parent_loop(struct smbd_parent_context *parent)
+static void smbd_parent_loop(struct tevent_context *ev_ctx,
+                            struct smbd_parent_context *parent)
 {
        /* now accept incoming connections - forking a new process
           for each incoming connection */
@@ -799,7 +787,7 @@ static void smbd_parent_loop(struct smbd_parent_context *parent)
                int ret;
                TALLOC_CTX *frame = talloc_stackframe();
 
-               ret = tevent_loop_once(smbd_event_context());
+               ret = tevent_loop_once(ev_ctx);
                if (ret != 0) {
                        exit_server_cleanly("tevent_loop_once() error");
                }
@@ -831,6 +819,34 @@ static bool init_structs(void )
        return True;
 }
 
+static void smbd_parent_sig_term_handler(struct tevent_context *ev,
+                                        struct tevent_signal *se,
+                                        int signum,
+                                        int count,
+                                        void *siginfo,
+                                        void *private_data)
+{
+       exit_server_cleanly("termination signal");
+}
+
+static void smbd_parent_sig_hup_handler(struct tevent_context *ev,
+                                       struct tevent_signal *se,
+                                       int signum,
+                                       int count,
+                                       void *siginfo,
+                                       void *private_data)
+{
+       struct smbd_parent_context *parent =
+               talloc_get_type_abort(private_data,
+               struct smbd_parent_context);
+
+       change_to_root_user();
+       DEBUG(1,("parent: Reloading services after SIGHUP\n"));
+       reload_services(parent->msg_ctx, -1, false);
+
+       printing_subsystem_update(parent->ev_ctx, parent->msg_ctx, true);
+}
+
 /****************************************************************************
  main program.
 ****************************************************************************/
@@ -879,6 +895,9 @@ extern void build_options(bool screen);
        TALLOC_CTX *frame;
        NTSTATUS status;
        uint64_t unique_id;
+       struct tevent_context *ev_ctx;
+       struct messaging_context *msg_ctx;
+       struct tevent_signal *se;
 
        /*
         * Do this before any other talloc operation
@@ -886,10 +905,9 @@ extern void build_options(bool screen);
        talloc_enable_null_tracking();
        frame = talloc_stackframe();
 
-       load_case_tables();
+       setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
 
-       /* Initialize the event context, it will panic on error */
-       smbd_event_context();
+       load_case_tables();
 
        smbd_init_globals();
 
@@ -973,8 +991,8 @@ extern void build_options(bool screen);
        gain_root_privilege();
        gain_root_group_privilege();
 
-       fault_setup((void (*)(void *))exit_server_fault);
-       dump_core_setup("smbd");
+       fault_setup();
+       dump_core_setup("smbd", lp_logfile());
 
        /* we are never interested in SIGPIPE */
        BlockSignals(True,SIGPIPE);
@@ -1021,21 +1039,38 @@ extern void build_options(bool screen);
        }
 
        if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
-               DEBUG(0, ("error opening config file\n"));
+               DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
                exit(1);
        }
 
        /* Init the security context and global current_user */
        init_sec_ctx();
 
-       if (smbd_messaging_context() == NULL)
+       /*
+        * Initialize the event context. The event context needs to be
+        * initialized before the messaging context, cause the messaging
+        * context holds an event context.
+        * FIXME: This should be s3_tevent_context_init()
+        */
+       ev_ctx = server_event_context();
+       if (ev_ctx == NULL) {
+               exit(1);
+       }
+
+       /*
+        * Init the messaging context
+        * FIXME: This should only call messaging_init()
+        */
+       msg_ctx = server_messaging_context();
+       if (msg_ctx == NULL) {
                exit(1);
+       }
 
        /*
         * Reloading of the printers will not work here as we don't have a
         * server info and rpc services set up. It will be called later.
         */
-       if (!reload_services(smbd_messaging_context(), -1, False)) {
+       if (!reload_services(NULL, -1, False)) {
                exit(1);
        }
 
@@ -1046,7 +1081,7 @@ extern void build_options(bool screen);
        init_structs();
 
 #ifdef WITH_PROFILE
-       if (!profile_setup(smbd_messaging_context(), False)) {
+       if (!profile_setup(msg_ctx, False)) {
                DEBUG(0,("ERROR: failed to setup profiling\n"));
                return -1;
        }
@@ -1095,19 +1130,40 @@ extern void build_options(bool screen);
        if (is_daemon)
                pidfile_create("smbd");
 
-       status = reinit_after_fork(smbd_messaging_context(),
-                                  smbd_event_context(),
-                                  procid_self(), false);
+       status = reinit_after_fork(msg_ctx,
+                                  ev_ctx,
+                                  false);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(0,("reinit_after_fork() failed\n"));
                exit(1);
        }
 
-       smbd_server_conn->msg_ctx = smbd_messaging_context();
+       smbd_server_conn->msg_ctx = msg_ctx;
 
-       smbd_setup_sig_term_handler();
-       smbd_setup_sig_hup_handler(smbd_event_context(),
-                                  smbd_server_conn->msg_ctx);
+       parent = talloc_zero(ev_ctx, struct smbd_parent_context);
+       if (!parent) {
+               exit_server("talloc(struct smbd_parent_context) failed");
+       }
+       parent->interactive = interactive;
+       parent->ev_ctx = ev_ctx;
+       parent->msg_ctx = msg_ctx;
+
+       se = tevent_add_signal(parent->ev_ctx,
+                              parent,
+                              SIGTERM, 0,
+                              smbd_parent_sig_term_handler,
+                              parent);
+       if (!se) {
+               exit_server("failed to setup SIGTERM handler");
+       }
+       se = tevent_add_signal(parent->ev_ctx,
+                              parent,
+                              SIGHUP, 0,
+                              smbd_parent_sig_hup_handler,
+                              parent);
+       if (!se) {
+               exit_server("failed to setup SIGHUP handler");
+       }
 
        /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
 
@@ -1120,7 +1176,7 @@ extern void build_options(bool screen);
        /* Initialise the password backed before the global_sam_sid
           to ensure that we fetch from ldap before we make a domain sid up */
 
-       if(!initialize_password_db(False, smbd_event_context()))
+       if(!initialize_password_db(false, ev_ctx))
                exit(1);
 
        if (!secrets_init()) {
@@ -1129,10 +1185,12 @@ extern void build_options(bool screen);
        }
 
        if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
-               if (!open_schannel_session_store(NULL, lp_private_dir())) {
+               struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_context());
+               if (!open_schannel_session_store(NULL, lp_ctx)) {
                        DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
                        exit(1);
                }
+               TALLOC_FREE(lp_ctx);
        }
 
        if(!get_global_sam_sid()) {
@@ -1150,28 +1208,21 @@ extern void build_options(bool screen);
        if (!locking_init())
                exit(1);
 
-       if (!messaging_tdb_parent_init(smbd_event_context())) {
-               exit(1);
-       }
-
-       if (!notify_internal_parent_init(smbd_event_context())) {
+       if (!messaging_tdb_parent_init(ev_ctx)) {
                exit(1);
        }
 
-       if (!serverid_parent_init(smbd_event_context())) {
+       if (!notify_internal_parent_init(ev_ctx)) {
                exit(1);
        }
 
-       if (!printer_list_parent_init()) {
+       if (!serverid_parent_init(ev_ctx)) {
                exit(1);
        }
 
        if (!W_ERROR_IS_OK(registry_init_full()))
                exit(1);
 
-       if (!print_backend_init(smbd_messaging_context()))
-               exit(1);
-
        /* Open the share_info.tdb here, so we don't have to open
           after the fork on every single connection.  This is a small
           performance improvment and reduces the total number of system
@@ -1198,23 +1249,47 @@ extern void build_options(bool screen);
                return -1;
        }
 
-       if (!dcesrv_ep_setup(smbd_event_context(), smbd_server_conn->msg_ctx)) {
+       /* This MUST be done before start_epmd() because otherwise
+        * start_epmd() forks and races against dcesrv_ep_setup() to
+        * call directory_create_or_exist() */
+       if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
+               DEBUG(0, ("Failed to create pipe directory %s - %s\n",
+                         lp_ncalrpc_dir(), strerror(errno)));
+               return -1;
+       }
+
+       if (is_daemon && !interactive) {
+               if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
+                       start_epmd(ev_ctx, msg_ctx);
+               }
+       }
+
+       if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
                exit(1);
        }
 
-       /* Publish nt printers, this requires a working winreg pipe */
-       pcap_cache_reload(server_event_context(), smbd_messaging_context(),
-                         &reload_printers);
+       /* only start other daemons if we are running as a daemon
+        * -- bad things will happen if smbd is launched via inetd
+        *  and we fork a copy of ourselves here */
+       if (is_daemon && !interactive) {
+
+               if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
+                       start_lsasd(ev_ctx, msg_ctx);
+               }
 
-       /* only start the background queue daemon if we are 
-          running as a daemon -- bad things will happen if
-          smbd is launched via inetd and we fork a copy of 
-          ourselves here */
+               if (!_lp_disable_spoolss() &&
+                   (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
+                       bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);
 
-       if (is_daemon && !interactive
-           && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
-               start_background_queue(smbd_event_context(),
-                                      smbd_messaging_context());
+                       if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
+                               exit(1);
+                       }
+               }
+       } else if (!_lp_disable_spoolss() &&
+                  (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
+               if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
+                       exit(1);
+               }
        }
 
        if (!is_daemon) {
@@ -1224,38 +1299,38 @@ extern void build_options(bool screen);
                /* Started from inetd. fd 0 is the socket. */
                /* We will abort gracefully when the client or remote system
                   goes away */
-               smbd_set_server_fd(dup(0));
+               smbd_server_conn->sock = dup(0);
 
                /* close our standard file descriptors */
-               close_low_fds(False); /* Don't close stderr */
+               if (!debug_get_output_is_stdout()) {
+                       close_low_fds(False); /* Don't close stderr */
+               }
 
 #ifdef HAVE_ATEXIT
                atexit(killkids);
 #endif
 
                /* Stop zombies */
-               smbd_setup_sig_chld_handler();
+               smbd_setup_sig_chld_handler(ev_ctx);
 
-               smbd_process(smbd_server_conn);
+               smbd_process(ev_ctx, smbd_server_conn);
 
                exit_server_cleanly(NULL);
                return(0);
        }
 
-       parent = talloc_zero(smbd_event_context(), struct smbd_parent_context);
-       if (!parent) {
-               exit_server("talloc(struct smbd_parent_context) failed");
-       }
-       parent->interactive = interactive;
-
-       if (!open_sockets_smbd(parent, smbd_messaging_context(), ports))
+       if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
                exit_server("open_sockets_smbd() failed");
 
+       /* do a printer update now that all messaging has been set up,
+        * before we allow clients to start connecting */
+       printing_subsystem_update(ev_ctx, msg_ctx, false);
+
        TALLOC_FREE(frame);
        /* make sure we always have a valid stackframe */
        frame = talloc_stackframe();
 
-       smbd_parent_loop(parent);
+       smbd_parent_loop(ev_ctx, parent);
 
        exit_server_cleanly(NULL);
        TALLOC_FREE(frame);