s3-build: only include memcache.h where needed.
[nivanova/samba-autobuild/.git] / source3 / smbd / server.c
index fcfabcd06f07498b583c3aab793d6f841a21184b..3797ae93da94afb57e372b2fd3a2fe87cf51d9e0 100644 (file)
 */
 
 #include "includes.h"
+#include "popt_common.h"
 #include "smbd/globals.h"
 #include "librpc/gen_ndr/messaging.h"
 #include "registry.h"
+#include "libcli/auth/schannel.h"
+#include "secrets.h"
+#include "memcache.h"
+
+#include "../librpc/gen_ndr/srv_dfs.h"
+#include "../librpc/gen_ndr/srv_dssetup.h"
+#include "../librpc/gen_ndr/srv_echo.h"
+#include "../librpc/gen_ndr/srv_eventlog.h"
+#include "../librpc/gen_ndr/srv_initshutdown.h"
+#include "../librpc/gen_ndr/srv_lsa.h"
+#include "../librpc/gen_ndr/srv_netlogon.h"
+#include "../librpc/gen_ndr/srv_ntsvcs.h"
+#include "../librpc/gen_ndr/srv_samr.h"
+#include "../librpc/gen_ndr/srv_spoolss.h"
+#include "../librpc/gen_ndr/srv_srvsvc.h"
+#include "../librpc/gen_ndr/srv_svcctl.h"
+#include "../librpc/gen_ndr/srv_winreg.h"
+#include "../librpc/gen_ndr/srv_wkssvc.h"
+
+#include "printing/nt_printing_migrate.h"
 
 static_decl_rpc;
 
@@ -39,49 +60,33 @@ int smbd_server_fd(void)
 
 static void smbd_set_server_fd(int fd)
 {
+       struct smbd_server_connection *sconn = smbd_server_conn;
+       const char *name;
+
        server_fd = fd;
-}
 
-int get_client_fd(void)
-{
-       return server_fd;
-}
+       sconn->sock = fd;
 
-struct event_context *smbd_event_context(void)
-{
-       if (!smbd_event_ctx) {
-               smbd_event_ctx = event_context_init(talloc_autofree_context());
-       }
-       if (!smbd_event_ctx) {
-               smb_panic("Could not init smbd event context");
-       }
-       return smbd_event_ctx;
-}
+       /*
+        * Initialize sconn->client_id: If we can't find the client's
+        * name, default to its address.
+        */
 
-struct messaging_context *smbd_messaging_context(void)
-{
-       if (smbd_msg_ctx == NULL) {
-               smbd_msg_ctx = messaging_init(talloc_autofree_context(),
-                                             procid_self(),
-                                             smbd_event_context());
-       }
-       if (smbd_msg_ctx == NULL) {
-               DEBUG(0, ("Could not init smbd messaging context.\n"));
+       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;
        }
-       return smbd_msg_ctx;
+       sconn->client_id.name =
+               (name != NULL) ? name : sconn->client_id.addr;
 }
 
-struct memcache *smbd_memcache(void)
+struct event_context *smbd_event_context(void)
 {
-       if (!smbd_memcache_ctx) {
-               smbd_memcache_ctx = memcache_init(talloc_autofree_context(),
-                                                 lp_max_stat_cache_size()*1024);
-       }
-       if (!smbd_memcache_ctx) {
-               smb_panic("Could not init smbd memcache");
-       }
-
-       return smbd_memcache_ctx;
+       return server_event_context();
 }
 
 /*******************************************************************
@@ -97,7 +102,7 @@ static void smb_conf_updated(struct messaging_context *msg,
        DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
                  "updated. Reloading.\n"));
        change_to_root_user();
-       reload_services(False);
+       reload_services(msg, smbd_server_fd(), False);
 }
 
 
@@ -273,7 +278,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;
 
-       if (!serverid_deregister(&child_id)) {
+       if (!serverid_deregister(child_id)) {
                DEBUG(1, ("Could not remove pid %d from serverid.tdb\n",
                          (int)pid));
        }
@@ -386,7 +391,7 @@ static void smbd_accept_connection(struct tevent_context *ev,
        pid_t pid = 0;
        uint64_t unique_id;
 
-       smbd_set_server_fd(accept(s->fd,(struct sockaddr *)&addr,&in_addrlen));
+       smbd_set_server_fd(accept(s->fd, (struct sockaddr *)(void *)&addr,&in_addrlen));
 
        if (smbd_server_fd() == -1 && errno == EINTR)
                return;
@@ -398,7 +403,7 @@ static void smbd_accept_connection(struct tevent_context *ev,
        }
 
        if (s->parent->interactive) {
-               smbd_process();
+               smbd_process(smbd_server_conn);
                exit_server_cleanly("end of interactive mode");
                return;
        }
@@ -440,7 +445,8 @@ static void smbd_accept_connection(struct tevent_context *ev,
                s = NULL;
 
                status = reinit_after_fork(smbd_messaging_context(),
-                                          smbd_event_context(), true);
+                                          smbd_event_context(), procid_self(),
+                                          true);
                if (!NT_STATUS_IS_OK(status)) {
                        if (NT_STATUS_EQUAL(status,
                                            NT_STATUS_TOO_MANY_OPENED_FILES)) {
@@ -453,20 +459,24 @@ static void smbd_accept_connection(struct tevent_context *ev,
                }
 
                smbd_setup_sig_term_handler();
-               smbd_setup_sig_hup_handler();
+               smbd_setup_sig_hup_handler(server_event_context(),
+                                          server_messaging_context());
 
-               if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
-                                           |FLAG_MSG_DBWRAP
-                                           |FLAG_MSG_PRINT_GENERAL)) {
+               if (!serverid_register(procid_self(),
+                                      FLAG_MSG_GENERAL|FLAG_MSG_SMBD
+                                      |FLAG_MSG_DBWRAP
+                                      |FLAG_MSG_PRINT_GENERAL)) {
                        exit_server_cleanly("Could not register myself in "
                                            "serverid.tdb");
                }
 
-               smbd_process();
+               smbd_process(smbd_server_conn);
         exit:
                exit_server_cleanly("end of child");
                return;
-       } else if (pid < 0) {
+       }
+
+       if (pid < 0) {
                DEBUG(0,("smbd_accept_connection: sys_fork() failed: %s\n",
                         strerror(errno)));
        }
@@ -693,8 +703,9 @@ 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_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
-                                   |FLAG_MSG_DBWRAP)) {
+       if (!serverid_register(procid_self(),
+                              FLAG_MSG_GENERAL|FLAG_MSG_SMBD
+                              |FLAG_MSG_DBWRAP)) {
                DEBUG(0, ("open_sockets_smbd: Failed to register "
                          "myself in serverid.tdb\n"));
                return false;
@@ -718,7 +729,8 @@ static bool open_sockets_smbd(struct smbd_parent_context *parent,
 
 #ifdef CLUSTER_SUPPORT
        if (lp_clustering()) {
-               ctdbd_register_reconfigure(messaging_ctdbd_connection());
+               ctdbd_register_reconfigure(
+                       messaging_ctdbd_connection(procid_self()));
        }
 #endif
 
@@ -766,234 +778,6 @@ static void smbd_parent_loop(struct smbd_parent_context *parent)
 /* NOTREACHED  return True; */
 }
 
-/****************************************************************************
- Reload printers
-**************************************************************************/
-void reload_printers(void)
-{
-       int snum;
-       int n_services = lp_numservices();
-       int pnum = lp_servicenumber(PRINTERS_NAME);
-       const char *pname;
-
-       pcap_cache_reload();
-
-       /* remove stale printers */
-       for (snum = 0; snum < n_services; snum++) {
-               /* avoid removing PRINTERS_NAME or non-autoloaded printers */
-               if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
-                                     lp_autoloaded(snum)))
-                       continue;
-
-               pname = lp_printername(snum);
-               if (!pcap_printername_ok(pname)) {
-                       DEBUG(3, ("removing stale printer %s\n", pname));
-
-                       if (is_printer_published(NULL, snum, NULL))
-                               nt_printer_publish(NULL, snum, DSPRINT_UNPUBLISH);
-                       del_a_printer(pname);
-                       lp_killservice(snum);
-               }
-       }
-
-       load_printers();
-}
-
-/****************************************************************************
- Reload the services file.
-**************************************************************************/
-
-bool reload_services(bool test)
-{
-       bool ret;
-
-       if (lp_loaded()) {
-               char *fname = lp_configfile();
-               if (file_exist(fname) &&
-                   !strcsequal(fname, get_dyn_CONFIGFILE())) {
-                       set_dyn_CONFIGFILE(fname);
-                       test = False;
-               }
-       }
-
-       reopen_logs();
-
-       if (test && !lp_file_list_changed())
-               return(True);
-
-       lp_killunused(conn_snum_used);
-
-       ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
-
-       reload_printers();
-
-       /* perhaps the config filename is now set */
-       if (!test)
-               reload_services(True);
-
-       reopen_logs();
-
-       load_interfaces();
-
-       if (smbd_server_fd() != -1) {
-               set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
-               set_socket_options(smbd_server_fd(), lp_socket_options());
-       }
-
-       mangle_reset_cache();
-       reset_stat_cache();
-
-       /* this forces service parameters to be flushed */
-       set_current_service(NULL,0,True);
-
-       return(ret);
-}
-
-static struct files_struct *log_writeable_file_fn(
-       struct files_struct *fsp, void *private_data)
-{
-       bool *found = (bool *)private_data;
-       char *path;
-
-       if (!fsp->can_write) {
-               return NULL;
-       }
-       if (!(*found)) {
-               DEBUG(0, ("Writable files open at exit:\n"));
-               *found = true;
-       }
-
-       path = talloc_asprintf(talloc_tos(), "%s/%s", fsp->conn->connectpath,
-                              smb_fname_str_dbg(fsp->fsp_name));
-       if (path == NULL) {
-               DEBUGADD(0, ("<NOMEM>\n"));
-       }
-
-       DEBUGADD(0, ("%s\n", path));
-
-       TALLOC_FREE(path);
-       return NULL;
-}
-
-/****************************************************************************
- Exit the server.
-****************************************************************************/
-
-/* Reasons for shutting down a server process. */
-enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
-
-static void exit_server_common(enum server_exit_reason how,
-       const char *const reason) _NORETURN_;
-
-static void exit_server_common(enum server_exit_reason how,
-       const char *const reason)
-{
-       bool had_open_conn = false;
-       struct smbd_server_connection *sconn = smbd_server_conn;
-
-       if (!exit_firsttime)
-               exit(0);
-       exit_firsttime = false;
-
-       change_to_root_user();
-
-       if (sconn && sconn->smb1.negprot.auth_context) {
-               struct auth_context *a = sconn->smb1.negprot.auth_context;
-               a->free(&sconn->smb1.negprot.auth_context);
-       }
-
-       if (lp_log_writeable_files_on_exit()) {
-               bool found = false;
-               files_forall(log_writeable_file_fn, &found);
-       }
-
-       if (sconn) {
-               had_open_conn = conn_close_all(sconn);
-               invalidate_all_vuids(sconn);
-       }
-
-       /* 3 second timeout. */
-       print_notify_send_messages(smbd_messaging_context(), 3);
-
-       /* delete our entry in the serverid database. */
-       serverid_deregister_self();
-
-#ifdef WITH_DFS
-       if (dcelogin_atmost_once) {
-               dfs_unlogin();
-       }
-#endif
-
-#ifdef USE_DMAPI
-       /* Destroy Samba DMAPI session only if we are master smbd process */
-       if (am_parent) {
-               if (!dmapi_destroy_session()) {
-                       DEBUG(0,("Unable to close Samba DMAPI session\n"));
-               }
-       }
-#endif
-
-       locking_end();
-       printing_end();
-
-       /*
-        * we need to force the order of freeing the following,
-        * because smbd_msg_ctx is not a talloc child of smbd_server_conn.
-        */
-       sconn = NULL;
-       TALLOC_FREE(smbd_server_conn);
-       TALLOC_FREE(smbd_msg_ctx);
-       TALLOC_FREE(smbd_event_ctx);
-
-       if (how != SERVER_EXIT_NORMAL) {
-               int oldlevel = DEBUGLEVEL;
-
-               DEBUGLEVEL = 10;
-
-               DEBUGSEP(0);
-               DEBUG(0,("Abnormal server exit: %s\n",
-                       reason ? reason : "no explanation provided"));
-               DEBUGSEP(0);
-
-               log_stack_trace();
-
-               DEBUGLEVEL = oldlevel;
-               dump_core();
-
-       } else {    
-               DEBUG(3,("Server exit (%s)\n",
-                       (reason ? reason : "normal exit")));
-               if (am_parent) {
-                       pidfile_unlink();
-               }
-               gencache_stabilize();
-       }
-
-       /* if we had any open SMB connections when we exited then we
-          need to tell the parent smbd so that it can trigger a retry
-          of any locks we may have been holding or open files we were
-          blocking */
-       if (had_open_conn) {
-               exit(1);
-       } else {
-               exit(0);
-       }
-}
-
-void exit_server(const char *const explanation)
-{
-       exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
-}
-
-void exit_server_cleanly(const char *const explanation)
-{
-       exit_server_common(SERVER_EXIT_NORMAL, explanation);
-}
-
-void exit_server_fault(void)
-{
-       exit_server("critical server fault");
-}
 
 /****************************************************************************
  Initialise connect, service and file structs.
@@ -1017,6 +801,13 @@ static bool init_structs(void )
        return True;
 }
 
+static bool spoolss_init_cb(void *ptr)
+{
+       struct messaging_context *msg_ctx = talloc_get_type_abort(
+               ptr, struct messaging_context);
+       return nt_printing_tdb_migrate(msg_ctx);
+}
+
 /****************************************************************************
  main program.
 ****************************************************************************/
@@ -1063,6 +854,12 @@ extern void build_options(bool screen);
        };
        struct smbd_parent_context *parent = NULL;
        TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
+       NTSTATUS status;
+       uint64_t unique_id;
+       struct rpc_srv_callbacks spoolss_cb;
+
+       /* Initialize the event context, it will panic on error */
+       smbd_event_context();
 
        smbd_init_globals();
 
@@ -1121,8 +918,6 @@ extern void build_options(bool screen);
        setluid(0);
 #endif
 
-       sec_init();
-
        set_remote_machine_name("smbd", False);
 
        if (interactive && (DEBUGLEVEL >= 9)) {
@@ -1138,9 +933,11 @@ extern void build_options(bool screen);
            client problems at a later date. (tridge) */
        generate_random_buffer(NULL, 0);
 
+       /* get initial effective uid and gid */
+       sec_init();
+
        /* make absolutely sure we run as root - to handle cases where people
           are crazy enough to have it setuid */
-
        gain_root_privilege();
        gain_root_group_privilege();
 
@@ -1175,8 +972,6 @@ extern void build_options(bool screen);
           so set our umask to 0 */
        umask(0);
 
-       init_sec_ctx();
-
        reopen_logs();
 
        DEBUG(0,("smbd version %s started.\n", samba_version_string()));
@@ -1198,11 +993,24 @@ extern void build_options(bool screen);
                exit(1);
        }
 
+       /* Init the security context and global current_user */
+       init_sec_ctx();
+
        if (smbd_messaging_context() == NULL)
                exit(1);
 
-       if (!reload_services(False))
-               return(-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(), smbd_server_fd(),
+                            False)) {
+               exit(1);
+       }
+
+       /* ...NOTE... Log files are working from this point! */
+
+       DEBUG(3,("loaded services\n"));
 
        init_structs();
 
@@ -1221,8 +1029,6 @@ extern void build_options(bool screen);
        }
 #endif
 
-       DEBUG(3,( "loaded services\n"));
-
        if (!is_daemon && !is_a_socket(0)) {
                if (!interactive)
                        DEBUG(0,("standard input is not a socket, assuming -D option\n"));
@@ -1240,6 +1046,9 @@ extern void build_options(bool screen);
                become_daemon(Fork, no_process_group, log_stdout);
        }
 
+        generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
+        set_my_unique_id(unique_id);
+
 #if HAVE_SETPGID
        /*
         * If we're interactive we want to set our own process group for
@@ -1255,14 +1064,19 @@ extern void build_options(bool screen);
        if (is_daemon)
                pidfile_create("smbd");
 
-       if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
-                            smbd_event_context(), false))) {
+       status = reinit_after_fork(smbd_messaging_context(),
+                                  smbd_event_context(),
+                                  procid_self(), 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_setup_sig_term_handler();
-       smbd_setup_sig_hup_handler();
+       smbd_setup_sig_hup_handler(smbd_event_context(),
+                                  smbd_server_conn->msg_ctx);
 
        /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
 
@@ -1283,6 +1097,13 @@ extern void build_options(bool screen);
                exit(1);
        }
 
+       if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
+               if (!open_schannel_session_store(NULL, lp_private_dir())) {
+                       DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
+                       exit(1);
+               }
+       }
+
        if(!get_global_sam_sid()) {
                DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
                exit(1);
@@ -1313,28 +1134,56 @@ extern void build_options(bool screen);
        if (!W_ERROR_IS_OK(registry_init_full()))
                exit(1);
 
+       if (!print_backend_init(smbd_messaging_context()))
+               exit(1);
+
 #if 0
        if (!init_svcctl_db())
                 exit(1);
 #endif
 
-       if (!print_backend_init(smbd_messaging_context()))
+       /* 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
+          fds used. */
+       if (!share_info_db_init()) {
+               DEBUG(0,("ERROR: failed to load share info db.\n"));
                exit(1);
+       }
+
+       if (!init_system_info()) {
+               DEBUG(0,("ERROR: failed to setup system user info.\n"));
+               return -1;
+       }
 
        if (!init_guest_info()) {
                DEBUG(0,("ERROR: failed to setup guest info.\n"));
                return -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
-          fds used. */
-       if (!share_info_db_init()) {
-               DEBUG(0,("ERROR: failed to load share info db.\n"));
+       /*
+        * Initialize spoolss with an init function to convert printers first.
+        * static_init_rpc will try to initialize the spoolss server too but you
+        * can't register it twice.
+        */
+       spoolss_cb.init = spoolss_init_cb;
+       spoolss_cb.shutdown = NULL;
+       spoolss_cb.private_data = smbd_server_conn->msg_ctx;
+
+       /* Spoolss depends on a winreg pipe, so start it first. */
+       if (!NT_STATUS_IS_OK(rpc_winreg_init(NULL))) {
                exit(1);
        }
 
+       if (!NT_STATUS_IS_OK(rpc_spoolss_init(&spoolss_cb))) {
+               exit(1);
+       }
+
+       static_init_rpc;
+
+       /* Publish nt printers, this requires a working winreg pipe */
+       reload_printers(smbd_messaging_context());
+
        /* 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 
@@ -1342,7 +1191,8 @@ extern void build_options(bool screen);
 
        if (is_daemon && !interactive
            && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
-               start_background_queue();
+               start_background_queue(smbd_event_context(),
+                                      smbd_messaging_context());
        }
 
        if (!is_daemon) {
@@ -1364,7 +1214,7 @@ extern void build_options(bool screen);
                /* Stop zombies */
                smbd_setup_sig_chld_handler();
 
-               smbd_process();
+               smbd_process(smbd_server_conn);
 
                exit_server_cleanly(NULL);
                return(0);