s3-talloc Change TALLOC_P() to talloc()
[nivanova/samba-autobuild/.git] / source3 / smbd / process.c
index d776ff0377cadc97947e235c9d0c123fdbeef1f5..78beb730b961a9571863543853c1e46056e97616 100644 (file)
@@ -3,28 +3,38 @@
    process incoming packets - main loop
    Copyright (C) Andrew Tridgell 1992-1998
    Copyright (C) Volker Lendecke 2005-2007
-   
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
+#include "../lib/tsocket/tsocket.h"
+#include "system/filesys.h"
+#include "smbd/smbd.h"
 #include "smbd/globals.h"
 #include "librpc/gen_ndr/netlogon.h"
-#include "librpc/gen_ndr/messaging.h"
 #include "../lib/async_req/async_sock.h"
 #include "ctdbd_conn.h"
 #include "../lib/util/select.h"
+#include "printing/pcap.h"
+#include "system/select.h"
+#include "passdb.h"
+#include "auth.h"
+#include "messages.h"
+#include "smbprofile.h"
+#include "rpc_server/spoolss/srv_spoolss_nt.h"
+#include "libsmb/libsmb.h"
 
 extern bool global_machine_password_needs_changing;
 
@@ -48,9 +58,14 @@ static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
 
        DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
 
-       ok = fcntl_lock(sconn->smb1.echo_handler.socket_lock_fd,
+       do {
+               ok = fcntl_lock(
+                       sconn->smb1.echo_handler.socket_lock_fd,
                        SMB_F_SETLKW, 0, 0, F_WRLCK);
+       } while (!ok && (errno == EINTR));
+
        if (!ok) {
+               DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
                return false;
        }
 
@@ -80,9 +95,14 @@ static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
                return true;
        }
 
-       ok = fcntl_lock(sconn->smb1.echo_handler.socket_lock_fd,
+       do {
+               ok = fcntl_lock(
+                       sconn->smb1.echo_handler.socket_lock_fd,
                        SMB_F_SETLKW, 0, 0, F_UNLCK);
+       } while (!ok && (errno == EINTR));
+
        if (!ok) {
+               DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
                return false;
        }
 
@@ -245,6 +265,7 @@ static NTSTATUS read_packet_remainder(int fd, char *buffer,
 static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
                                                    const char lenbuf[4],
                                                    struct smbd_server_connection *sconn,
+                                                   int sock,
                                                    char **buffer,
                                                    unsigned int timeout,
                                                    size_t *p_unread,
@@ -259,7 +280,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
        memcpy(writeX_header, lenbuf, 4);
 
        status = read_fd_with_timeout(
-               sconn->sock, writeX_header + 4,
+               sock, writeX_header + 4,
                STANDARD_WRITE_AND_X_HEADER_SIZE,
                STANDARD_WRITE_AND_X_HEADER_SIZE,
                timeout, NULL);
@@ -286,7 +307,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
                if (doff > STANDARD_WRITE_AND_X_HEADER_SIZE) {
                        size_t drain = doff - STANDARD_WRITE_AND_X_HEADER_SIZE;
-                       if (drain_socket(sconn->sock, drain) != drain) {
+                       if (drain_socket(sock, drain) != drain) {
                                smb_panic("receive_smb_raw_talloc_partial_read:"
                                        " failed to drain pending bytes");
                        }
@@ -325,7 +346,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
         * talloc and return.
         */
 
-       *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
+       *buffer = talloc_array(mem_ctx, char, len+4);
 
        if (*buffer == NULL) {
                DEBUG(0, ("Could not allocate inbuf of length %d\n",
@@ -341,7 +362,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
        if(toread > 0) {
                status = read_packet_remainder(
-                       sconn->sock,
+                       sock,
                        (*buffer) + 4 + STANDARD_WRITE_AND_X_HEADER_SIZE,
                        timeout, toread);
 
@@ -358,6 +379,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
 static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
                                       struct smbd_server_connection *sconn,
+                                      int sock,
                                       char **buffer, unsigned int timeout,
                                       size_t *p_unread, size_t *plen)
 {
@@ -368,7 +390,7 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
 
        *p_unread = 0;
 
-       status = read_smb_length_return_keepalive(sconn->sock, lenbuf, timeout,
+       status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
                                                  &len);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
@@ -381,7 +403,7 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
            sconn->smb1.echo_handler.trusted_fde == NULL) {
 
                return receive_smb_raw_talloc_partial_read(
-                       mem_ctx, lenbuf, sconn, buffer, timeout,
+                       mem_ctx, lenbuf, sconn, sock, buffer, timeout,
                        p_unread, plen);
        }
 
@@ -393,7 +415,7 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
         * The +4 here can't wrap, we've checked the length above already.
         */
 
-       *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
+       *buffer = talloc_array(mem_ctx, char, len+4);
 
        if (*buffer == NULL) {
                DEBUG(0, ("Could not allocate inbuf of length %d\n",
@@ -403,7 +425,7 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
 
        memcpy(*buffer, lenbuf, sizeof(lenbuf));
 
-       status = read_packet_remainder(sconn->sock, (*buffer)+4, timeout, len);
+       status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
        }
@@ -412,7 +434,9 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
        return NT_STATUS_OK;
 }
 
-static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,        int fd,
+static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
+                                  struct smbd_server_connection *sconn,
+                                  int sock,
                                   char **buffer, unsigned int timeout,
                                   size_t *p_unread, bool *p_encrypted,
                                   size_t *p_len,
@@ -424,14 +448,12 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,   int fd,
 
        *p_encrypted = false;
 
-       status = receive_smb_raw_talloc(mem_ctx, smbd_server_conn, buffer,
-                                       timeout, p_unread, &len);
+       status = receive_smb_raw_talloc(mem_ctx, sconn, sock, buffer, timeout,
+                                       p_unread, &len);
        if (!NT_STATUS_IS_OK(status)) {
-               char addr[INET6_ADDRSTRLEN];
                DEBUG(1, ("read_smb_length_return_keepalive failed for "
                          "client %s read error = %s.\n",
-                         get_peer_addr(fd, addr, sizeof(addr)),
-                         nt_errstr(status)));
+                         sconn->client_id.addr, nt_errstr(status)));
                return status;
        }
 
@@ -447,7 +469,7 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,     int fd,
        }
 
        /* Check the incoming SMB signature. */
-       if (!srv_check_sign_mac(smbd_server_conn, *buffer, seqnum, trusted_channel)) {
+       if (!srv_check_sign_mac(sconn, *buffer, seqnum, trusted_channel)) {
                DEBUG(0, ("receive_smb: SMB Signature verification failed on "
                          "incoming packet!\n"));
                return NT_STATUS_INVALID_NETWORK_RESPONSE;
@@ -482,9 +504,9 @@ static bool init_smb_request(struct smb_request *req,
        req->vuid   = SVAL(inbuf, smb_uid);
        req->tid    = SVAL(inbuf, smb_tid);
        req->wct    = CVAL(inbuf, smb_wct);
-       req->vwv    = (uint16_t *)(inbuf+smb_vwv);
+       req->vwv    = discard_const_p(uint16_t, (inbuf+smb_vwv));
        req->buflen = smb_buflen(inbuf);
-       req->buf    = (const uint8_t *)smb_buf(inbuf);
+       req->buf    = (const uint8_t *)smb_buf_const(inbuf);
        req->unread_bytes = unread_bytes;
        req->encrypted = encrypted;
        req->sconn = sconn;
@@ -503,7 +525,7 @@ static bool init_smb_request(struct smb_request *req,
                return false;
        }
        /* Ensure bcc is correct. */
-       if (((uint8 *)smb_buf(inbuf)) + req->buflen > inbuf + req_size) {
+       if (((const uint8_t *)smb_buf_const(inbuf)) + req->buflen > inbuf + req_size) {
                DEBUG(0,("init_smb_request: invalid bcc number %u "
                        "(wct = %u, size %u)\n",
                        (unsigned int)req->buflen,
@@ -602,7 +624,7 @@ static bool push_queued_message(struct smb_request *req,
                }
        }
 
-       msg->te = event_add_timed(smbd_event_context(),
+       msg->te = event_add_timed(server_event_context(),
                                  msg,
                                  end_time,
                                  smbd_deferred_open_timer,
@@ -686,7 +708,7 @@ void schedule_deferred_open_message_smb(uint64_t mid)
                                "scheduling mid %llu\n",
                                (unsigned long long)mid ));
 
-                       te = event_add_timed(smbd_event_context(),
+                       te = event_add_timed(server_event_context(),
                                             pml,
                                             timeval_zero(),
                                             smbd_deferred_open_timer,
@@ -869,7 +891,7 @@ struct idle_event *event_add_idle(struct event_context *event_ctx,
        struct idle_event *result;
        struct timeval now = timeval_current();
 
-       result = TALLOC_P(mem_ctx, struct idle_event);
+       result = talloc(mem_ctx, struct idle_event);
        if (result == NULL) {
                DEBUG(0, ("talloc failed\n"));
                return NULL;
@@ -912,8 +934,8 @@ void smbd_setup_sig_term_handler(void)
 {
        struct tevent_signal *se;
 
-       se = tevent_add_signal(smbd_event_context(),
-                              smbd_event_context(),
+       se = tevent_add_signal(server_event_context(),
+                              server_event_context(),
                               SIGTERM, 0,
                               smbd_sig_term_handler,
                               NULL);
@@ -934,6 +956,9 @@ static void smbd_sig_hup_handler(struct tevent_context *ev,
        change_to_root_user();
        DEBUG(1,("Reloading services after SIGHUP\n"));
        reload_services(msg_ctx, smbd_server_conn->sock, False);
+       if (am_parent) {
+               pcap_cache_reload(ev, msg_ctx, &reload_pcap_change_notify);
+       }
 }
 
 void smbd_setup_sig_hup_handler(struct tevent_context *ev,
@@ -950,36 +975,23 @@ void smbd_setup_sig_hup_handler(struct tevent_context *ev,
 
 static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *conn)
 {
-       fd_set r_fds, w_fds;
-       int selrtn = 0;
-       struct timeval to;
-       int maxfd = 0;
-
-       to.tv_sec = SMBD_SELECT_TIMEOUT;
-       to.tv_usec = 0;
-
-       /*
-        * Setup the select fd sets.
-        */
+       int timeout;
+       int num_pfds = 0;
+       int ret;
+       bool retry;
 
-       FD_ZERO(&r_fds);
-       FD_ZERO(&w_fds);
+       timeout = SMBD_SELECT_TIMEOUT * 1000;
 
        /*
         * Are there any timed events waiting ? If so, ensure we don't
         * select for longer than it would take to wait for them.
         */
 
-       {
-               struct timeval now;
-               GetTimeOfDay(&now);
-
-               event_add_to_select_args(smbd_event_context(), &now,
-                                        &r_fds, &w_fds, &to, &maxfd);
-       }
+       event_add_to_poll_args(server_event_context(), conn,
+                              &conn->pfds, &num_pfds, &timeout);
 
        /* Process a signal and timed events now... */
-       if (run_events(smbd_event_context(), &selrtn, NULL, NULL)) {
+       if (run_events_poll(server_event_context(), 0, NULL, 0)) {
                return NT_STATUS_RETRY;
        }
 
@@ -987,33 +999,28 @@ static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *
                int sav;
                START_PROFILE(smbd_idle);
 
-               selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&to);
+               ret = sys_poll(conn->pfds, num_pfds, timeout);
                sav = errno;
 
                END_PROFILE(smbd_idle);
                errno = sav;
        }
 
-       /* Check if error */
-       if (selrtn == -1) {
-               if (errno == EINTR)
+       if (ret == -1) {
+               if (errno == EINTR) {
                        return NT_STATUS_RETRY;
-               else
-                       /* Maybe the socket is dead? */
-                       return map_nt_error_from_unix(errno);
+               }
+               return map_nt_error_from_unix(errno);
        }
 
-       /* Process events until all available fds have been handled.
-        * This allows for fair round-robin handling of all available fds
-        * on each select() wakeup, while still maintaining responsiveness
-        * by re-checking for signal and timed events between the handling
-        * of each ready fd. */
-       do {
-               run_events(smbd_event_context(), &selrtn, &r_fds, &w_fds);
-       } while (selrtn > 0);
+       retry = run_events_poll(server_event_context(), ret, conn->pfds,
+                               num_pfds);
+       if (retry) {
+               return NT_STATUS_RETRY;
+       }
 
-       /* Processed all fds or timed out */
-       if (selrtn == 0) {
+       /* Did we timeout ? */
+       if (ret == 0) {
                return NT_STATUS_RETRY;
        }
 
@@ -1344,12 +1351,12 @@ static bool create_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
                char *msg;
                if (asprintf(&msg, "num_bytes too large: %u",
                             (unsigned)num_bytes) == -1) {
-                       msg = CONST_DISCARD(char *, "num_bytes too large");
+                       msg = discard_const_p(char, "num_bytes too large");
                }
                smb_panic(msg);
        }
 
-       *outbuf = TALLOC_ARRAY(mem_ctx, char,
+       *outbuf = talloc_array(mem_ctx, char,
                               smb_size + num_words*2 + num_bytes);
        if (*outbuf == NULL) {
                return false;
@@ -1371,7 +1378,7 @@ static bool create_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
 void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
 {
        char *outbuf;
-       if (!create_outbuf(req, req, (char *)req->inbuf, &outbuf, num_words,
+       if (!create_outbuf(req, req, (const char *)req->inbuf, &outbuf, num_words,
                           num_bytes)) {
                smb_panic("could not allocate output buffer\n");
        }
@@ -1443,7 +1450,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
 
        if (smb_messages[type].fn == NULL) {
                DEBUG(0,("Unknown message type %d!\n",type));
-               smb_dump("Unknown", 1, (char *)req->inbuf, size);
+               smb_dump("Unknown", 1, (const char *)req->inbuf, size);
                reply_unknown_new(req, type);
                return NULL;
        }
@@ -1458,10 +1465,10 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
        DEBUG(3,("switch message %s (pid %d) conn 0x%lx\n", smb_fn_name(type),
                 (int)sys_getpid(), (unsigned long)conn));
 
-       smb_dump(smb_fn_name(type), 1, (char *)req->inbuf, size);
+       smb_dump(smb_fn_name(type), 1, (const char *)req->inbuf, size);
 
        /* Ensure this value is replaced in the incoming packet. */
-       SSVAL(req->inbuf,smb_uid,session_tag);
+       SSVAL(discard_const_p(uint8_t, req->inbuf),smb_uid,session_tag);
 
        /*
         * Ensure the correct username is in current_user_info.  This is a
@@ -1480,9 +1487,9 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                        vuser = get_valid_user_struct(sconn, session_tag);
                        if (vuser) {
                                set_current_user_info(
-                                       vuser->server_info->sanitized_username,
-                                       vuser->server_info->unix_name,
-                                       vuser->server_info->info3->base.domain.string);
+                                       vuser->session_info->sanitized_username,
+                                       vuser->session_info->unix_name,
+                                       vuser->session_info->info3->base.domain.string);
                        }
                }
        }
@@ -1571,7 +1578,8 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
  Construct a reply to the incoming packet.
 ****************************************************************************/
 
-static void construct_reply(char *inbuf, int size, size_t unread_bytes,
+static void construct_reply(struct smbd_server_connection *sconn,
+                           char *inbuf, int size, size_t unread_bytes,
                            uint32_t seqnum, bool encrypted,
                            struct smb_perfcount_data *deferred_pcd)
 {
@@ -1582,8 +1590,8 @@ static void construct_reply(char *inbuf, int size, size_t unread_bytes,
                smb_panic("could not allocate smb_request");
        }
 
-       if (!init_smb_request(req, smbd_server_conn, (uint8 *)inbuf,
-                             unread_bytes, encrypted, seqnum)) {
+       if (!init_smb_request(req, sconn, (uint8 *)inbuf, unread_bytes,
+                             encrypted, seqnum)) {
                exit_server_cleanly("Invalid SMB request");
        }
 
@@ -1676,7 +1684,8 @@ static void process_smb(struct smbd_server_connection *sconn,
 
        show_msg((char *)inbuf);
 
-       construct_reply((char *)inbuf,nread,unread_bytes,seqnum,encrypted,deferred_pcd);
+       construct_reply(sconn, (char *)inbuf, nread, unread_bytes, seqnum,
+                       encrypted, deferred_pcd);
        sconn->trans_num++;
 
 done:
@@ -1745,7 +1754,7 @@ static void construct_reply_common(struct smb_request *req, const char *inbuf,
 
 void construct_reply_common_req(struct smb_request *req, char *outbuf)
 {
-       construct_reply_common(req, (char *)req->inbuf, outbuf);
+       construct_reply_common(req, (const char *)req->inbuf, outbuf);
 }
 
 /*
@@ -1885,7 +1894,7 @@ static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
                return false;
        }
 
-       outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, uint8_t, new_size);
+       outbuf = talloc_realloc(NULL, *poutbuf, uint8_t, new_size);
        if (outbuf == NULL) {
                DEBUG(0, ("talloc failed\n"));
                return false;
@@ -1899,7 +1908,7 @@ static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
 
                if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
                        DEBUG(1, ("invalid command chain\n"));
-                       *poutbuf = TALLOC_REALLOC_ARRAY(
+                       *poutbuf = talloc_realloc(
                                NULL, *poutbuf, uint8_t, old_size);
                        return false;
                }
@@ -1968,9 +1977,9 @@ void chain_reply(struct smb_request *req)
        uint32_t chain_offset;  /* uint32_t to avoid overflow */
 
        uint8_t wct;
-       uint16_t *vwv;
+       const uint16_t *vwv;
        uint16_t buflen;
-       uint8_t *buf;
+       const uint8_t *buf;
 
        if (IVAL(req->outbuf, smb_rcls) != 0) {
                fixup_chain_error_packet(req);
@@ -1987,7 +1996,7 @@ void chain_reply(struct smb_request *req)
 
        if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
                if (req->chain_outbuf == NULL) {
-                       req->chain_outbuf = TALLOC_REALLOC_ARRAY(
+                       req->chain_outbuf = talloc_realloc(
                                req, req->outbuf, uint8_t,
                                smb_len(req->outbuf) + 4);
                        if (req->chain_outbuf == NULL) {
@@ -2019,7 +2028,7 @@ void chain_reply(struct smb_request *req)
                 * over-allocated (reply_pipe_read_and_X used to be such an
                 * example).
                 */
-               req->chain_outbuf = TALLOC_REALLOC_ARRAY(
+               req->chain_outbuf = talloc_realloc(
                        req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
                if (req->chain_outbuf == NULL) {
                        smb_panic("talloc failed");
@@ -2030,8 +2039,8 @@ void chain_reply(struct smb_request *req)
                 * Update smb headers where subsequent chained commands
                 * may have updated them.
                 */
-               SCVAL(req->chain_outbuf, smb_tid, CVAL(req->outbuf, smb_tid));
-               SCVAL(req->chain_outbuf, smb_uid, CVAL(req->outbuf, smb_uid));
+               SSVAL(req->chain_outbuf, smb_tid, SVAL(req->outbuf, smb_tid));
+               SSVAL(req->chain_outbuf, smb_uid, SVAL(req->outbuf, smb_uid));
 
                if (!smb_splice_chain(&req->chain_outbuf,
                                      CVAL(req->outbuf, smb_com),
@@ -2119,7 +2128,7 @@ void chain_reply(struct smb_request *req)
        if (length_needed > smblen) {
                goto error;
        }
-       vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
+       vwv = (const uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
 
        /*
         * Now grab the new byte buffer....
@@ -2135,11 +2144,11 @@ void chain_reply(struct smb_request *req)
        if (length_needed > smblen) {
                goto error;
        }
-       buf = (uint8_t *)(vwv+wct+1);
+       buf = (const uint8_t *)(vwv+wct+1);
 
        req->cmd = chain_cmd;
        req->wct = wct;
-       req->vwv = vwv;
+       req->vwv = discard_const_p(uint16_t, vwv);
        req->buflen = buflen;
        req->buf = buf;
 
@@ -2216,72 +2225,35 @@ void chain_reply(struct smb_request *req)
 
 static void check_reload(struct smbd_server_connection *sconn, time_t t)
 {
-       time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
 
-       if(last_smb_conf_reload_time == 0) {
+       if (last_smb_conf_reload_time == 0) {
                last_smb_conf_reload_time = t;
-               /* Our printing subsystem might not be ready at smbd start up.
-                  Then no printer is available till the first printers check
-                  is performed.  A lower initial interval circumvents this. */
-               if ( printcap_cache_time > 60 )
-                       last_printer_reload_time = t - printcap_cache_time + 60;
-               else
-                       last_printer_reload_time = t;
-       }
-
-       if (mypid != getpid()) { /* First time or fork happened meanwhile */
-               /* randomize over 60 second the printcap reload to avoid all
-                * process hitting cupsd at the same time */
-               int time_range = 60;
-
-               last_printer_reload_time += random() % time_range;
-               mypid = getpid();
        }
 
        if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
                reload_services(sconn->msg_ctx, sconn->sock, True);
                last_smb_conf_reload_time = t;
        }
-
-       /* 'printcap cache time = 0' disable the feature */
-
-       if ( printcap_cache_time != 0 )
-       { 
-               /* see if it's time to reload or if the clock has been set back */
-
-               if ( (t >= last_printer_reload_time+printcap_cache_time) 
-                       || (t-last_printer_reload_time  < 0) ) 
-               {
-                       DEBUG( 3,( "Printcap cache time expired.\n"));
-                       reload_printers(sconn->msg_ctx);
-                       last_printer_reload_time = t;
-               }
-       }
 }
 
 static bool fd_is_readable(int fd)
 {
-       fd_set fds;
-       struct timeval timeout = {0, };
-       int ret;
+       int ret, revents;
 
-       FD_ZERO(&fds);
-       FD_SET(fd, &fds);
+       ret = poll_one_fd(fd, POLLIN|POLLHUP, 0, &revents);
+
+       return ((ret > 0) && ((revents & (POLLIN|POLLHUP|POLLERR)) != 0));
 
-       ret = sys_select(fd+1, &fds, NULL, NULL, &timeout);
-       if (ret == -1) {
-               return false;
-       }
-       return FD_ISSET(fd, &fds);
 }
 
-static void smbd_server_connection_write_handler(struct smbd_server_connection *conn)
+static void smbd_server_connection_write_handler(
+       struct smbd_server_connection *sconn)
 {
        /* TODO: make write nonblocking */
 }
 
 static void smbd_server_connection_read_handler(
-       struct smbd_server_connection *conn, int fd)
+       struct smbd_server_connection *sconn, int fd)
 {
        uint8_t *inbuf = NULL;
        size_t inbuf_len = 0;
@@ -2291,29 +2263,29 @@ static void smbd_server_connection_read_handler(
        NTSTATUS status;
        uint32_t seqnum;
 
-       bool from_client = (conn->sock == fd);
+       bool from_client = (sconn->sock == fd);
 
        if (from_client) {
-               smbd_lock_socket(conn);
+               smbd_lock_socket(sconn);
 
-               if (!fd_is_readable(fd)) {
+               if (lp_async_smb_echo_handler() && !fd_is_readable(fd)) {
                        DEBUG(10,("the echo listener was faster\n"));
-                       smbd_unlock_socket(conn);
+                       smbd_unlock_socket(sconn);
                        return;
                }
 
                /* TODO: make this completely nonblocking */
-               status = receive_smb_talloc(mem_ctx, fd,
+               status = receive_smb_talloc(mem_ctx, sconn, fd,
                                            (char **)(void *)&inbuf,
                                            0, /* timeout */
                                            &unread_bytes,
                                            &encrypted,
                                            &inbuf_len, &seqnum,
                                            false /* trusted channel */);
-               smbd_unlock_socket(conn);
+               smbd_unlock_socket(sconn);
        } else {
                /* TODO: make this completely nonblocking */
-               status = receive_smb_talloc(mem_ctx, fd,
+               status = receive_smb_talloc(mem_ctx, sconn, fd,
                                            (char **)(void *)&inbuf,
                                            0, /* timeout */
                                            &unread_bytes,
@@ -2333,7 +2305,7 @@ static void smbd_server_connection_read_handler(
        }
 
 process:
-       process_smb(conn, inbuf, inbuf_len, unread_bytes,
+       process_smb(sconn, inbuf, inbuf_len, unread_bytes,
                    seqnum, encrypted, NULL);
 }
 
@@ -2374,6 +2346,7 @@ static void smbd_server_echo_handler(struct event_context *ev,
        }
 }
 
+#ifdef CLUSTER_SUPPORT
 /****************************************************************************
 received when we should release a specific IP
 ****************************************************************************/
@@ -2386,6 +2359,9 @@ static void release_ip(const char *ip, void *priv)
                p = addr + 7;
        }
 
+       DEBUG(10, ("Got release IP message for %s, "
+                  "our address is %s\n", ip, p));
+
        if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
                /* we can't afford to do a clean exit - that involves
                   database writes, which would potentially mean we
@@ -2400,16 +2376,6 @@ static void release_ip(const char *ip, void *priv)
        }
 }
 
-static void msg_release_ip(struct messaging_context *msg_ctx, void *private_data,
-                          uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
-{
-       struct smbd_server_connection *sconn = talloc_get_type_abort(
-               private_data, struct smbd_server_connection);
-
-       release_ip((char *)data->data, sconn->client_id.addr);
-}
-
-#ifdef CLUSTER_SUPPORT
 static int client_get_tcp_info(int sock, struct sockaddr_storage *server,
                               struct sockaddr_storage *client)
 {
@@ -2466,21 +2432,9 @@ static bool deadtime_fn(const struct timeval *now, void *private_data)
        struct smbd_server_connection *sconn =
                (struct smbd_server_connection *)private_data;
 
-       if (sconn->using_smb2) {
-               /* TODO: implement real idle check */
-               if (sconn->smb2.sessions.list) {
-                       return true;
-               }
-               DEBUG( 2, ( "Closing idle SMB2 connection\n" ) );
-               messaging_send(sconn->msg_ctx,
-                              messaging_server_id(sconn->msg_ctx),
-                              MSG_SHUTDOWN, &data_blob_null);
-               return false;
-       }
-
        if ((conn_num_open(sconn) == 0)
            || (conn_idle_all(sconn, now->tv_sec))) {
-               DEBUG( 2, ( "Closing idle SMB1 connection\n" ) );
+               DEBUG( 2, ( "Closing idle connection\n" ) );
                messaging_send(sconn->msg_ctx,
                               messaging_server_id(sconn->msg_ctx),
                               MSG_SHUTDOWN, &data_blob_null);
@@ -2498,13 +2452,16 @@ static bool housekeeping_fn(const struct timeval *now, void *private_data)
 {
        struct smbd_server_connection *sconn = talloc_get_type_abort(
                private_data, struct smbd_server_connection);
+
+       DEBUG(5, ("housekeeping\n"));
+
        change_to_root_user();
 
        /* update printer queue caches if necessary */
        update_monitored_printq_cache(sconn->msg_ctx);
 
        /* check if we need to reload services */
-       check_reload(sconn, time(NULL));
+       check_reload(sconn, time_mono(NULL));
 
        /* Change machine password if neccessary. */
        attempt_machine_password_change();
@@ -2652,7 +2609,7 @@ static bool smbd_echo_reply(uint8_t *inbuf, size_t inbuf_len,
                return false;
        }
 
-       if (!create_outbuf(talloc_tos(), &req, (char *)req.inbuf, &outbuf,
+       if (!create_outbuf(talloc_tos(), &req, (const char *)req.inbuf, &outbuf,
                           1, req.buflen)) {
                DEBUG(10, ("create_outbuf failed\n"));
                return false;
@@ -2735,7 +2692,7 @@ static void smbd_echo_reader(struct tevent_context *ev,
 
        DEBUG(10,("echo_handler[%d]: reading pdu\n", (int)sys_getpid()));
 
-       status = receive_smb_talloc(state->pending, sconn->sock,
+       status = receive_smb_talloc(state->pending, sconn, sconn->sock,
                                    (char **)(void *)&state->pending[num_pending].iov_base,
                                    0 /* timeout */,
                                    &unread,
@@ -2832,7 +2789,7 @@ static void smbd_echo_loop(struct smbd_server_connection *sconn,
 /*
  * Handle SMBecho requests in a forked child process
  */
-static bool fork_echo_handler(struct smbd_server_connection *sconn)
+bool fork_echo_handler(struct smbd_server_connection *sconn)
 {
        int listener_pipe[2];
        int res;
@@ -2857,7 +2814,7 @@ static bool fork_echo_handler(struct smbd_server_connection *sconn)
                set_blocking(listener_pipe[1], false);
 
                status = reinit_after_fork(sconn->msg_ctx,
-                                          smbd_event_context(),
+                                          server_event_context(),
                                           procid_self(), false);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(1, ("reinit_after_fork failed: %s\n",
@@ -2877,7 +2834,7 @@ static bool fork_echo_handler(struct smbd_server_connection *sconn)
         * Without smb signing this is the same as the normal smbd
         * listener. This needs to change once signing comes in.
         */
-       sconn->smb1.echo_handler.trusted_fde = event_add_fd(smbd_event_context(),
+       sconn->smb1.echo_handler.trusted_fde = event_add_fd(server_event_context(),
                                        sconn,
                                        sconn->smb1.echo_handler.trusted_fd,
                                        EVENT_FD_READ,
@@ -2946,11 +2903,9 @@ void smbd_process(struct smbd_server_connection *sconn)
        const char *remaddr = NULL;
        int ret;
 
-       if (lp_maxprotocol() == PROTOCOL_SMB2 &&
-           lp_security() != SEC_SHARE &&
-           !lp_async_smb_echo_handler()) {
+       if (lp_maxprotocol() == PROTOCOL_SMB2) {
                /*
-                * We're not making the desion here,
+                * We're not making the decision here,
                 * we're just allowing the client
                 * to decide between SMB1 and SMB2
                 * with the first negprot
@@ -3069,10 +3024,6 @@ void smbd_process(struct smbd_server_connection *sconn)
                exit_server("Failed to init smb_signing");
        }
 
-       if (lp_async_smb_echo_handler() && !fork_echo_handler(sconn)) {
-               exit_server("Failed to fork echo handler");
-       }
-
        /* Setup oplocks */
        if (!init_oplocks(sconn->msg_ctx))
                exit_server("Failed to init oplocks");
@@ -3080,8 +3031,6 @@ void smbd_process(struct smbd_server_connection *sconn)
        /* register our message handlers */
        messaging_register(sconn->msg_ctx, NULL,
                           MSG_SMB_FORCE_TDIS, msg_force_tdis);
-       messaging_register(sconn->msg_ctx, sconn,
-                          MSG_SMB_RELEASE_IP, msg_release_ip);
        messaging_register(sconn->msg_ctx, NULL,
                           MSG_SMB_CLOSE_FILE, msg_close_file);
 
@@ -3095,7 +3044,7 @@ void smbd_process(struct smbd_server_connection *sconn)
                           MSG_DEBUG, debug_message);
 
        if ((lp_keepalive() != 0)
-           && !(event_add_idle(smbd_event_context(), NULL,
+           && !(event_add_idle(server_event_context(), NULL,
                                timeval_set(lp_keepalive(), 0),
                                "keepalive", keepalive_fn,
                                NULL))) {
@@ -3103,15 +3052,15 @@ void smbd_process(struct smbd_server_connection *sconn)
                exit(1);
        }
 
-       if (!(event_add_idle(smbd_event_context(), NULL,
+       if (!(event_add_idle(server_event_context(), NULL,
                             timeval_set(IDLE_CLOSED_TIMEOUT, 0),
                             "deadtime", deadtime_fn, sconn))) {
                DEBUG(0, ("Could not add deadtime event\n"));
                exit(1);
        }
 
-       if (!(event_add_idle(smbd_event_context(), NULL,
-                            timeval_set(SMBD_SELECT_TIMEOUT, 0),
+       if (!(event_add_idle(server_event_context(), NULL,
+                            timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
                             "housekeeping", housekeeping_fn, sconn))) {
                DEBUG(0, ("Could not add housekeeping event\n"));
                exit(1);
@@ -3167,7 +3116,7 @@ void smbd_process(struct smbd_server_connection *sconn)
                exit_server("init_dptrs() failed");
        }
 
-       sconn->smb1.fde = event_add_fd(smbd_event_context(),
+       sconn->smb1.fde = event_add_fd(server_event_context(),
                                                  sconn,
                                                  sconn->sock,
                                                  EVENT_FD_READ,
@@ -3202,7 +3151,7 @@ void smbd_process(struct smbd_server_connection *sconn)
 
 bool req_is_in_chain(struct smb_request *req)
 {
-       if (req->vwv != (uint16_t *)(req->inbuf+smb_vwv)) {
+       if (req->vwv != (const uint16_t *)(req->inbuf+smb_vwv)) {
                /*
                 * We're right now handling a subsequent request, so we must
                 * be in a chain