Imported Upstream version 4.0.0+dfsg1
[abartlet/samba-debian.git] / source3 / smbd / process.c
index f43005dda3ad8526b5a58b188bb05df69de95095..eeda6f99f22e1b9404bac2d913d5329fbf15d35c 100644 (file)
@@ -27,7 +27,7 @@
 #include "../lib/async_req/async_sock.h"
 #include "ctdbd_conn.h"
 #include "../lib/util/select.h"
-#include "printing/pcap.h"
+#include "printing/queue_process.h"
 #include "system/select.h"
 #include "passdb.h"
 #include "auth.h"
 #include "smbprofile.h"
 #include "rpc_server/spoolss/srv_spoolss_nt.h"
 #include "libsmb/libsmb.h"
-
-extern bool global_machine_password_needs_changing;
+#include "../lib/util/tevent_ntstatus.h"
+#include "../libcli/security/dom_sid.h"
+#include "../libcli/security/security_token.h"
+#include "lib/id_cache.h"
+#include "serverid.h"
+
+/* Internal message queue for deferred opens. */
+struct pending_message_list {
+       struct pending_message_list *next, *prev;
+       struct timeval request_time; /* When was this first issued? */
+       struct smbd_server_connection *sconn;
+       struct timed_event *te;
+       struct smb_perfcount_data pcd;
+       uint32_t seqnum;
+       bool encrypted;
+       bool processed;
+       DATA_BLOB buf;
+       DATA_BLOB private_data;
+};
 
 static void construct_reply_common(struct smb_request *req, const char *inbuf,
                                   char *outbuf);
-static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid);
+static struct pending_message_list *get_deferred_open_message_smb(
+       struct smbd_server_connection *sconn, uint64_t mid);
+static bool smb_splice_chain(uint8_t **poutbuf, const uint8_t *andx_buf);
 
 static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
 {
@@ -56,12 +75,12 @@ static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
                return true;
        }
 
-       DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
+       DEBUG(10,("pid[%d] wait for socket lock\n", (int)getpid()));
 
        do {
                ok = fcntl_lock(
                        sconn->smb1.echo_handler.socket_lock_fd,
-                       SMB_F_SETLKW, 0, 0, F_WRLCK);
+                       F_SETLKW, 0, 0, F_WRLCK);
        } while (!ok && (errno == EINTR));
 
        if (!ok) {
@@ -69,7 +88,7 @@ static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
                return false;
        }
 
-       DEBUG(10,("pid[%d] got for socket lock\n", (int)sys_getpid()));
+       DEBUG(10,("pid[%d] got for socket lock\n", (int)getpid()));
 
        return true;
 }
@@ -98,7 +117,7 @@ static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
        do {
                ok = fcntl_lock(
                        sconn->smb1.echo_handler.socket_lock_fd,
-                       SMB_F_SETLKW, 0, 0, F_UNLCK);
+                       F_SETLKW, 0, 0, F_UNLCK);
        } while (!ok && (errno == EINTR));
 
        if (!ok) {
@@ -106,7 +125,7 @@ static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
                return false;
        }
 
-       DEBUG(10,("pid[%d] unlocked socket\n", (int)sys_getpid()));
+       DEBUG(10,("pid[%d] unlocked socket\n", (int)getpid()));
 
        return true;
 }
@@ -142,7 +161,7 @@ bool srv_send_smb(struct smbd_server_connection *sconn, char *buffer,
        }
 
        if (do_encrypt) {
-               NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
+               NTSTATUS status = srv_encrypt_buffer(sconn, buffer, &buf_out);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(0, ("send_smb: SMB encryption failed "
                                "on outgoing packet! Error %s\n",
@@ -162,16 +181,16 @@ bool srv_send_smb(struct smbd_server_connection *sconn, char *buffer,
                 * client failed.
                 */
                DEBUG(1,("pid[%d] Error writing %d bytes to client %s. %d. (%s)\n",
-                        (int)sys_getpid(), (int)len,
+                        (int)getpid(), (int)len,
                         get_peer_addr(sconn->sock, addr, sizeof(addr)),
                         (int)ret, strerror(errno) ));
 
-               srv_free_enc_buffer(buf_out);
+               srv_free_enc_buffer(sconn, buf_out);
                goto out;
        }
 
        SMB_PERFCOUNT_SET_MSGLEN_OUT(pcd, len);
-       srv_free_enc_buffer(buf_out);
+       srv_free_enc_buffer(sconn, buf_out);
 out:
        SMB_PERFCOUNT_END(pcd);
 
@@ -197,9 +216,10 @@ int srv_set_message(char *buf,
        return (smb_size + num_words*2 + num_bytes);
 }
 
-static bool valid_smb_header(const uint8_t *inbuf)
+static bool valid_smb_header(struct smbd_server_connection *sconn,
+                            const uint8_t *inbuf)
 {
-       if (is_encrypted_packet(inbuf)) {
+       if (is_encrypted_packet(sconn, inbuf)) {
                return true;
        }
        /*
@@ -287,7 +307,9 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(0, ("read_fd_with_timeout failed for client %s read "
-                         "error = %s.\n", sconn->client_id.addr,
+                         "error = %s.\n",
+                         tsocket_address_string(sconn->remote_address,
+                                                talloc_tos()),
                          nt_errstr(status)));
                return status;
        }
@@ -321,7 +343,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
                /* Copy the header we've written. */
 
-               *buffer = (char *)TALLOC_MEMDUP(mem_ctx,
+               *buffer = (char *)talloc_memdup(mem_ctx,
                                writeX_header,
                                sizeof(writeX_header));
 
@@ -346,7 +368,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",
@@ -415,7 +437,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",
@@ -454,12 +476,14 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
                DEBUG(NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)?5:1,
                      ("receive_smb_raw_talloc failed for client %s "
                       "read error = %s.\n",
-                      sconn->client_id.addr, nt_errstr(status)));
+                      tsocket_address_string(sconn->remote_address,
+                                             talloc_tos()),
+                      nt_errstr(status)) );
                return status;
        }
 
-       if (is_encrypted_packet((uint8_t *)*buffer)) {
-               status = srv_decrypt_buffer(*buffer);
+       if (is_encrypted_packet(sconn, (uint8_t *)*buffer)) {
+               status = srv_decrypt_buffer(sconn, *buffer);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(0, ("receive_smb_talloc: SMB decryption failed on "
                                "incoming packet! Error %s\n",
@@ -490,13 +514,21 @@ static bool init_smb_request(struct smb_request *req,
                             size_t unread_bytes, bool encrypted,
                             uint32_t seqnum)
 {
+       struct smbXsrv_tcon *tcon;
+       NTSTATUS status;
+       NTTIME now;
        size_t req_size = smb_len(inbuf) + 4;
+
        /* Ensure we have at least smb_size bytes. */
        if (req_size < smb_size) {
                DEBUG(0,("init_smb_request: invalid request size %u\n",
                        (unsigned int)req_size ));
                return false;
        }
+
+       req->request_time = timeval_current();
+       now = timeval_to_nttime(&req->request_time);
+
        req->cmd    = CVAL(inbuf, smb_com);
        req->flags2 = SVAL(inbuf, smb_flg2);
        req->smbpid = SVAL(inbuf, smb_pid);
@@ -505,17 +537,22 @@ 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    = (const 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;
-       req->conn = conn_find(sconn,req->tid);
+       status = smb1srv_tcon_lookup(sconn->conn, req->tid, now, &tcon);
+       if (NT_STATUS_IS_OK(status)) {
+               req->conn = tcon->compat;
+       } else {
+               req->conn = NULL;
+       }
        req->chain_fsp = NULL;
-       req->chain_outbuf = NULL;
-       req->done = false;
        req->smb2req = NULL;
+       req->priv_paths = NULL;
+       req->chain = NULL;
        smb_init_perfcount_data(&req->pcd);
 
        /* Ensure we have at least wct words and 2 bytes of bcc. */
@@ -526,7 +563,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,
@@ -551,6 +588,7 @@ static void smbd_deferred_open_timer(struct event_context *ev,
 {
        struct pending_message_list *msg = talloc_get_type(private_data,
                                           struct pending_message_list);
+       struct smbd_server_connection *sconn = msg->sconn;
        TALLOC_CTX *mem_ctx = talloc_tos();
        uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
        uint8_t *inbuf;
@@ -571,14 +609,14 @@ static void smbd_deferred_open_timer(struct event_context *ev,
         * re-processed in error. */
        msg->processed = true;
 
-       process_smb(smbd_server_conn, inbuf,
+       process_smb(sconn, inbuf,
                    msg->buf.length, 0,
                    msg->seqnum, msg->encrypted, &msg->pcd);
 
        /* If it's still there and was processed, remove it. */
-       msg = get_deferred_open_message_smb(mid);
+       msg = get_deferred_open_message_smb(sconn, mid);
        if (msg && msg->processed) {
-               remove_deferred_open_message_smb(mid);
+               remove_deferred_open_message_smb(sconn, mid);
        }
 }
 
@@ -595,12 +633,13 @@ static bool push_queued_message(struct smb_request *req,
        int msg_len = smb_len(req->inbuf) + 4;
        struct pending_message_list *msg;
 
-       msg = TALLOC_ZERO_P(NULL, struct pending_message_list);
+       msg = talloc_zero(NULL, struct pending_message_list);
 
        if(msg == NULL) {
                DEBUG(0,("push_message: malloc fail (1)\n"));
                return False;
        }
+       msg->sconn = req->sconn;
 
        msg->buf = data_blob_talloc(msg, req->inbuf, msg_len);
        if(msg->buf.data == NULL) {
@@ -625,18 +664,19 @@ static bool push_queued_message(struct smb_request *req,
                }
        }
 
-       msg->te = event_add_timed(smbd_event_context(),
-                                 msg,
-                                 end_time,
-                                 smbd_deferred_open_timer,
-                                 msg);
+       msg->te = tevent_add_timer(msg->sconn->ev_ctx,
+                                  msg,
+                                  end_time,
+                                  smbd_deferred_open_timer,
+                                  msg);
        if (!msg->te) {
                DEBUG(0,("push_message: event_add_timed failed\n"));
                TALLOC_FREE(msg);
                return false;
        }
 
-       DLIST_ADD_END(deferred_open_queue, msg, struct pending_message_list *);
+       DLIST_ADD_END(req->sconn->deferred_open_queue, msg,
+                     struct pending_message_list *);
 
        DEBUG(10,("push_message: pushed message length %u on "
                  "deferred_open_queue\n", (unsigned int)msg_len));
@@ -648,22 +688,23 @@ static bool push_queued_message(struct smb_request *req,
  Function to delete a sharing violation open message by mid.
 ****************************************************************************/
 
-void remove_deferred_open_message_smb(uint64_t mid)
+void remove_deferred_open_message_smb(struct smbd_server_connection *sconn,
+                                     uint64_t mid)
 {
        struct pending_message_list *pml;
 
-       if (smbd_server_conn->using_smb2) {
-               remove_deferred_open_message_smb2(smbd_server_conn, mid);
+       if (sconn->using_smb2) {
+               remove_deferred_open_message_smb2(sconn, mid);
                return;
        }
 
-       for (pml = deferred_open_queue; pml; pml = pml->next) {
+       for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
                if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
                        DEBUG(10,("remove_deferred_open_message_smb: "
                                  "deleting mid %llu len %u\n",
                                  (unsigned long long)mid,
                                  (unsigned int)pml->buf.length ));
-                       DLIST_REMOVE(deferred_open_queue, pml);
+                       DLIST_REMOVE(sconn->deferred_open_queue, pml);
                        TALLOC_FREE(pml);
                        return;
                }
@@ -675,17 +716,17 @@ void remove_deferred_open_message_smb(uint64_t mid)
  schedule it for immediate processing.
 ****************************************************************************/
 
-void schedule_deferred_open_message_smb(uint64_t mid)
+bool schedule_deferred_open_message_smb(struct smbd_server_connection *sconn,
+                                       uint64_t mid)
 {
        struct pending_message_list *pml;
        int i = 0;
 
-       if (smbd_server_conn->using_smb2) {
-               schedule_deferred_open_message_smb2(smbd_server_conn, mid);
-               return;
+       if (sconn->using_smb2) {
+               return schedule_deferred_open_message_smb2(sconn, mid);
        }
 
-       for (pml = deferred_open_queue; pml; pml = pml->next) {
+       for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
                uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
 
                DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
@@ -709,11 +750,11 @@ void schedule_deferred_open_message_smb(uint64_t mid)
                                "scheduling mid %llu\n",
                                (unsigned long long)mid ));
 
-                       te = event_add_timed(smbd_event_context(),
-                                            pml,
-                                            timeval_zero(),
-                                            smbd_deferred_open_timer,
-                                            pml);
+                       te = tevent_add_timer(pml->sconn->ev_ctx,
+                                             pml,
+                                             timeval_zero(),
+                                             smbd_deferred_open_timer,
+                                             pml);
                        if (!te) {
                                DEBUG(10,("schedule_deferred_open_message_smb: "
                                        "event_add_timed() failed, "
@@ -723,29 +764,31 @@ void schedule_deferred_open_message_smb(uint64_t mid)
 
                        TALLOC_FREE(pml->te);
                        pml->te = te;
-                       DLIST_PROMOTE(deferred_open_queue, pml);
-                       return;
+                       DLIST_PROMOTE(sconn->deferred_open_queue, pml);
+                       return true;
                }
        }
 
        DEBUG(10,("schedule_deferred_open_message_smb: failed to "
                "find message mid %llu\n",
                (unsigned long long)mid ));
+
+       return false;
 }
 
 /****************************************************************************
  Return true if this mid is on the deferred queue and was not yet processed.
 ****************************************************************************/
 
-bool open_was_deferred(uint64_t mid)
+bool open_was_deferred(struct smbd_server_connection *sconn, uint64_t mid)
 {
        struct pending_message_list *pml;
 
-       if (smbd_server_conn->using_smb2) {
-               return open_was_deferred_smb2(smbd_server_conn, mid);
+       if (sconn->using_smb2) {
+               return open_was_deferred_smb2(sconn, mid);
        }
 
-       for (pml = deferred_open_queue; pml; pml = pml->next) {
+       for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
                if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
                        return True;
                }
@@ -757,11 +800,12 @@ bool open_was_deferred(uint64_t mid)
  Return the message queued by this mid.
 ****************************************************************************/
 
-static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid)
+static struct pending_message_list *get_deferred_open_message_smb(
+       struct smbd_server_connection *sconn, uint64_t mid)
 {
        struct pending_message_list *pml;
 
-       for (pml = deferred_open_queue; pml; pml = pml->next) {
+       for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
                if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
                        return pml;
                }
@@ -779,13 +823,13 @@ bool get_deferred_open_message_state(struct smb_request *smbreq,
 {
        struct pending_message_list *pml;
 
-       if (smbd_server_conn->using_smb2) {
+       if (smbreq->sconn->using_smb2) {
                return get_deferred_open_message_state_smb2(smbreq->smb2req,
                                        p_request_time,
                                        pp_state);
        }
 
-       pml = get_deferred_open_message_smb(smbreq->mid);
+       pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
        if (!pml) {
                return false;
        }
@@ -841,139 +885,74 @@ bool push_deferred_open_message_smb(struct smb_request *req,
                                   private_data, priv_len);
 }
 
-struct idle_event {
-       struct timed_event *te;
-       struct timeval interval;
-       char *name;
-       bool (*handler)(const struct timeval *now, void *private_data);
-       void *private_data;
-};
-
-static void smbd_idle_event_handler(struct event_context *ctx,
-                                   struct timed_event *te,
-                                   struct timeval now,
-                                   void *private_data)
+static void smbd_sig_term_handler(struct tevent_context *ev,
+                                 struct tevent_signal *se,
+                                 int signum,
+                                 int count,
+                                 void *siginfo,
+                                 void *private_data)
 {
-       struct idle_event *event =
-               talloc_get_type_abort(private_data, struct idle_event);
-
-       TALLOC_FREE(event->te);
+       exit_server_cleanly("termination signal");
+}
 
-       DEBUG(10,("smbd_idle_event_handler: %s %p called\n",
-                 event->name, event->te));
+void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
+{
+       struct tevent_signal *se;
 
-       if (!event->handler(&now, event->private_data)) {
-               DEBUG(10,("smbd_idle_event_handler: %s %p stopped\n",
-                         event->name, event->te));
-               /* Don't repeat, delete ourselves */
-               TALLOC_FREE(event);
-               return;
+       se = tevent_add_signal(sconn->ev_ctx,
+                              sconn,
+                              SIGTERM, 0,
+                              smbd_sig_term_handler,
+                              sconn);
+       if (!se) {
+               exit_server("failed to setup SIGTERM handler");
        }
-
-       DEBUG(10,("smbd_idle_event_handler: %s %p rescheduled\n",
-                 event->name, event->te));
-
-       event->te = event_add_timed(ctx, event,
-                                   timeval_sum(&now, &event->interval),
-                                   smbd_idle_event_handler, event);
-
-       /* We can't do much but fail here. */
-       SMB_ASSERT(event->te != NULL);
 }
 
-struct idle_event *event_add_idle(struct event_context *event_ctx,
-                                 TALLOC_CTX *mem_ctx,
-                                 struct timeval interval,
-                                 const char *name,
-                                 bool (*handler)(const struct timeval *now,
-                                                 void *private_data),
+static void smbd_sig_hup_handler(struct tevent_context *ev,
+                                 struct tevent_signal *se,
+                                 int signum,
+                                 int count,
+                                 void *siginfo,
                                  void *private_data)
 {
-       struct idle_event *result;
-       struct timeval now = timeval_current();
-
-       result = TALLOC_P(mem_ctx, struct idle_event);
-       if (result == NULL) {
-               DEBUG(0, ("talloc failed\n"));
-               return NULL;
-       }
-
-       result->interval = interval;
-       result->handler = handler;
-       result->private_data = private_data;
-
-       if (!(result->name = talloc_asprintf(result, "idle_evt(%s)", name))) {
-               DEBUG(0, ("talloc failed\n"));
-               TALLOC_FREE(result);
-               return NULL;
-       }
-
-       result->te = event_add_timed(event_ctx, result,
-                                    timeval_sum(&now, &interval),
-                                    smbd_idle_event_handler, result);
-       if (result->te == NULL) {
-               DEBUG(0, ("event_add_timed failed\n"));
-               TALLOC_FREE(result);
-               return NULL;
-       }
+       struct smbd_server_connection *sconn =
+               talloc_get_type_abort(private_data,
+               struct smbd_server_connection);
 
-       DEBUG(10,("event_add_idle: %s %p\n", result->name, result->te));
-       return result;
+       change_to_root_user();
+       DEBUG(1,("Reloading services after SIGHUP\n"));
+       reload_services(sconn, conn_snum_used, false);
 }
 
-static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *conn)
+void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
 {
-       int timeout;
-       int num_pfds = 0;
-       int ret;
-       bool retry;
-
-       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.
-        */
-
-       event_add_to_poll_args(smbd_event_context(), conn,
-                              &conn->pfds, &num_pfds, &timeout);
-
-       /* Process a signal and timed events now... */
-       if (run_events_poll(smbd_event_context(), 0, NULL, 0)) {
-               return NT_STATUS_RETRY;
-       }
-
-       {
-               int sav;
-               START_PROFILE(smbd_idle);
-
-               ret = sys_poll(conn->pfds, num_pfds, timeout);
-               sav = errno;
-
-               END_PROFILE(smbd_idle);
-               errno = sav;
-       }
-
-       if (ret == -1) {
-               if (errno == EINTR) {
-                       return NT_STATUS_RETRY;
-               }
-               return map_nt_error_from_unix(errno);
-       }
+       struct tevent_signal *se;
 
-       retry = run_events_poll(smbd_event_context(), ret, conn->pfds,
-                               num_pfds);
-       if (retry) {
-               return NT_STATUS_RETRY;
+       se = tevent_add_signal(sconn->ev_ctx,
+                              sconn,
+                              SIGHUP, 0,
+                              smbd_sig_hup_handler,
+                              sconn);
+       if (!se) {
+               exit_server("failed to setup SIGHUP handler");
        }
+}
 
-       /* Did we timeout ? */
-       if (ret == 0) {
-               return NT_STATUS_RETRY;
-       }
+static void smbd_conf_updated(struct messaging_context *msg,
+                             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);
 
-       /* should not be reached */
-       return NT_STATUS_INTERNAL_ERROR;
+       DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
+                 "updated. Reloading.\n"));
+       change_to_root_user();
+       reload_services(sconn, conn_snum_used, false);
 }
 
 /*
@@ -1299,12 +1278,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;
@@ -1326,7 +1305,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");
        }
@@ -1338,22 +1317,28 @@ void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
  Dump a packet to a file.
 ********************************************************************/
 
-static void smb_dump(const char *name, int type, const char *data, ssize_t len)
+static void smb_dump(const char *name, int type, const char *data)
 {
+       size_t len;
        int fd, i;
        char *fname = NULL;
        if (DEBUGLEVEL < 50) {
                return;
        }
 
-       if (len < 4) len = smb_len(data)+4;
+       len = smb_len_tcp(data)+4;
        for (i=1;i<100;i++) {
-               if (asprintf(&fname, "/tmp/%s.%d.%s", name, i,
-                            type ? "req" : "resp") == -1) {
+               fname = talloc_asprintf(talloc_tos(),
+                               "/tmp/%s.%d.%s",
+                               name,
+                               i,
+                               type ? "req" : "resp");
+               if (fname == NULL) {
                        return;
                }
                fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
                if (fd != -1 || errno != EEXIST) break;
+               TALLOC_FREE(fname);
        }
        if (fd != -1) {
                ssize_t ret = write(fd, data, len);
@@ -1362,7 +1347,7 @@ static void smb_dump(const char *name, int type, const char *data, ssize_t len)
                close(fd);
                DEBUG(0,("created %s len %lu\n", fname, (unsigned long)len));
        }
-       SAFE_FREE(fname);
+       TALLOC_FREE(fname);
 }
 
 /****************************************************************************
@@ -1378,27 +1363,21 @@ static void smb_dump(const char *name, int type, const char *data, ssize_t len)
  find.
 ****************************************************************************/
 
-static connection_struct *switch_message(uint8 type, struct smb_request *req, int size)
+static connection_struct *switch_message(uint8 type, struct smb_request *req)
 {
        int flags;
-       uint16 session_tag;
+       uint64_t session_tag;
        connection_struct *conn = NULL;
        struct smbd_server_connection *sconn = req->sconn;
+       NTTIME now = timeval_to_nttime(&req->request_time);
+       struct smbXsrv_session *session = NULL;
+       NTSTATUS status;
 
        errno = 0;
 
-       /* Make sure this is an SMB packet. smb_size contains NetBIOS header
-        * so subtract 4 from it. */
-       if ((size < (smb_size - 4)) ||
-           !valid_smb_header(req->inbuf)) {
-               DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
-                        smb_len(req->inbuf)));
-               exit_server_cleanly("Non-SMB packet");
-       }
-
        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);
                reply_unknown_new(req, type);
                return NULL;
        }
@@ -1406,17 +1385,16 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
        flags = smb_messages[type].flags;
 
        /* In share mode security we must ignore the vuid. */
-       session_tag = (lp_security() == SEC_SHARE)
-               ? UID_FIELD_INVALID : req->vuid;
+       session_tag = req->vuid;
        conn = req->conn;
 
        DEBUG(3,("switch message %s (pid %d) conn 0x%lx\n", smb_fn_name(type),
-                (int)sys_getpid(), (unsigned long)conn));
+                (int)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);
 
        /* 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
@@ -1427,18 +1405,42 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
         * JRA.
         */
 
+       /*
+        * lookup an existing session
+        *
+        * Note: for now we only check for NT_STATUS_NETWORK_SESSION_EXPIRED
+        * here, the main check is still in change_to_user()
+        */
+       status = smb1srv_session_lookup(sconn->conn,
+                                       session_tag,
+                                       now,
+                                       &session);
+       if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
+               switch (type) {
+               case SMBsesssetupX:
+                       status = NT_STATUS_OK;
+                       break;
+               default:
+                       DEBUG(1,("Error: session %llu is expired, mid=%llu.\n",
+                                (unsigned long long)session_tag,
+                                (unsigned long long)req->mid));
+                       reply_nterror(req, NT_STATUS_NETWORK_SESSION_EXPIRED);
+                       return conn;
+               }
+       }
+
        if (session_tag != sconn->smb1.sessions.last_session_tag) {
-               user_struct *vuser = NULL;
+               struct user_struct *vuser = NULL;
 
                sconn->smb1.sessions.last_session_tag = session_tag;
-               if(session_tag != UID_FIELD_INVALID) {
-                       vuser = get_valid_user_struct(sconn, session_tag);
-                       if (vuser) {
-                               set_current_user_info(
-                                       vuser->session_info->sanitized_username,
-                                       vuser->session_info->unix_name,
-                                       vuser->session_info->info3->base.domain.string);
-                       }
+               if (session) {
+                       vuser = session->compat;
+               }
+               if (vuser) {
+                       set_current_user_info(
+                               vuser->session_info->unix_info->sanitized_username,
+                               vuser->session_info->unix_info->unix_name,
+                               vuser->session_info->info->domain_name);
                }
        }
 
@@ -1490,11 +1492,15 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                if (req->encrypted) {
                        conn->encrypted_tid = true;
                        /* encrypted required from now on. */
-                       conn->encrypt_level = Required;
+                       conn->encrypt_level = SMB_SIGNING_REQUIRED;
                } else if (ENCRYPTION_REQUIRED(conn)) {
                        if (req->cmd != SMBtrans2 && req->cmd != SMBtranss2) {
-                               exit_server_cleanly("encryption required "
-                                       "on connection");
+                               DEBUG(1,("service[%s] requires encryption"
+                                       "%s ACCESS_DENIED. mid=%llu\n",
+                                       lp_servicename(talloc_tos(), SNUM(conn)),
+                                       smb_fn_name(type),
+                                       (unsigned long long)req->mid));
+                               reply_nterror(req, NT_STATUS_ACCESS_DENIED);
                                return conn;
                        }
                }
@@ -1508,14 +1514,38 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                conn->num_smb_operations++;
        }
 
-       /* does this protocol need to be run as guest? */
-       if ((flags & AS_GUEST)
-           && (!change_to_guest() ||
-               !allow_access(lp_hostsdeny(-1), lp_hostsallow(-1),
-                             sconn->client_id.name,
-                             sconn->client_id.addr))) {
-               reply_nterror(req, NT_STATUS_ACCESS_DENIED);
-               return conn;
+       /*
+        * Does this protocol need to be run as guest? (Only archane
+        * messenger service requests have this...)
+        */
+       if (flags & AS_GUEST) {
+               char *raddr;
+               bool ok;
+
+               if (!change_to_guest()) {
+                       reply_nterror(req, NT_STATUS_ACCESS_DENIED);
+                       return conn;
+               }
+
+               raddr = tsocket_address_inet_addr_string(sconn->remote_address,
+                                                        talloc_tos());
+               if (raddr == NULL) {
+                       reply_nterror(req, NT_STATUS_NO_MEMORY);
+                       return conn;
+               }
+
+               /*
+                * Haven't we checked this in smbd_process already???
+                */
+
+               ok = allow_access(lp_hostsdeny(-1), lp_hostsallow(-1),
+                                 sconn->remote_hostname, raddr);
+               TALLOC_FREE(raddr);
+
+               if (!ok) {
+                       reply_nterror(req, NT_STATUS_ACCESS_DENIED);
+                       return conn;
+               }
        }
 
        smb_messages[type].fn(req);
@@ -1554,21 +1584,7 @@ static void construct_reply(struct smbd_server_connection *sconn,
                SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, size);
        }
 
-       conn = switch_message(req->cmd, req, size);
-
-       if (req->unread_bytes) {
-               /* writeX failed. drain socket. */
-               if (drain_socket(req->sconn->sock, req->unread_bytes) !=
-                               req->unread_bytes) {
-                       smb_panic("failed to drain pending bytes");
-               }
-               req->unread_bytes = 0;
-       }
-
-       if (req->done) {
-               TALLOC_FREE(req);
-               return;
-       }
+       conn = switch_message(req->cmd, req);
 
        if (req->outbuf == NULL) {
                return;
@@ -1591,6 +1607,170 @@ static void construct_reply(struct smbd_server_connection *sconn,
        return;
 }
 
+static void construct_reply_chain(struct smbd_server_connection *sconn,
+                                 char *inbuf, int size, uint32_t seqnum,
+                                 bool encrypted,
+                                 struct smb_perfcount_data *deferred_pcd)
+{
+       struct smb_request **reqs = NULL;
+       struct smb_request *req;
+       unsigned num_reqs;
+       bool ok;
+
+       ok = smb1_parse_chain(talloc_tos(), (uint8_t *)inbuf, sconn, encrypted,
+                             seqnum, &reqs, &num_reqs);
+       if (!ok) {
+               char errbuf[smb_size];
+               error_packet(errbuf, 0, 0, NT_STATUS_INVALID_PARAMETER,
+                            __LINE__, __FILE__);
+               if (!srv_send_smb(sconn, errbuf, true, seqnum, encrypted,
+                                 NULL)) {
+                       exit_server_cleanly("construct_reply_chain: "
+                                           "srv_send_smb failed.");
+               }
+               return;
+       }
+
+       req = reqs[0];
+       req->inbuf = (uint8_t *)talloc_move(reqs, &inbuf);
+
+       req->conn = switch_message(req->cmd, req);
+
+       if (req->outbuf == NULL) {
+               /*
+                * Request has suspended itself, will come
+                * back here.
+                */
+               return;
+       }
+       smb_request_done(req);
+}
+
+/*
+ * To be called from an async SMB handler that is potentially chained
+ * when it is finished for shipping.
+ */
+
+void smb_request_done(struct smb_request *req)
+{
+       struct smb_request **reqs = NULL;
+       struct smb_request *first_req;
+       size_t i, num_reqs, next_index;
+       NTSTATUS status;
+
+       if (req->chain == NULL) {
+               first_req = req;
+               goto shipit;
+       }
+
+       reqs = req->chain;
+       num_reqs = talloc_array_length(reqs);
+
+       for (i=0; i<num_reqs; i++) {
+               if (reqs[i] == req) {
+                       break;
+               }
+       }
+       if (i == num_reqs) {
+               /*
+                * Invalid chain, should not happen
+                */
+               status = NT_STATUS_INTERNAL_ERROR;
+               goto error;
+       }
+       next_index = i+1;
+
+       while ((next_index < num_reqs) && (IVAL(req->outbuf, smb_rcls) == 0)) {
+               struct smb_request *next = reqs[next_index];
+               struct smbXsrv_tcon *tcon;
+               NTTIME now = timeval_to_nttime(&req->request_time);
+
+               next->vuid = SVAL(req->outbuf, smb_uid);
+               next->tid  = SVAL(req->outbuf, smb_tid);
+               status = smb1srv_tcon_lookup(req->sconn->conn, req->tid,
+                                            now, &tcon);
+               if (NT_STATUS_IS_OK(status)) {
+                       req->conn = tcon->compat;
+               } else {
+                       req->conn = NULL;
+               }
+               next->chain_fsp = req->chain_fsp;
+               next->inbuf = (uint8_t *)req->inbuf;
+
+               req = next;
+               req->conn = switch_message(req->cmd, req);
+
+               if (req->outbuf == NULL) {
+                       /*
+                        * Request has suspended itself, will come
+                        * back here.
+                        */
+                       return;
+               }
+               next_index += 1;
+       }
+
+       first_req = reqs[0];
+
+       for (i=1; i<next_index; i++) {
+               bool ok;
+
+               ok = smb_splice_chain(&first_req->outbuf, reqs[i]->outbuf);
+               if (!ok) {
+                       status = NT_STATUS_INTERNAL_ERROR;
+                       goto error;
+               }
+       }
+
+       SSVAL(first_req->outbuf, smb_uid, SVAL(req->outbuf, smb_uid));
+       SSVAL(first_req->outbuf, smb_tid, SVAL(req->outbuf, smb_tid));
+
+       /*
+        * This scary statement intends to set the
+        * FLAGS2_32_BIT_ERROR_CODES flg2 field in first_req->outbuf
+        * to the value last_req->outbuf carries
+        */
+       SSVAL(first_req->outbuf, smb_flg2,
+             (SVAL(first_req->outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
+             |(SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
+
+       /*
+        * Transfer the error codes from the subrequest to the main one
+        */
+       SSVAL(first_req->outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
+       SSVAL(first_req->outbuf, smb_err,  SVAL(req->outbuf, smb_err));
+
+       _smb_setlen_large(
+               first_req->outbuf, talloc_get_size(first_req->outbuf) - 4);
+
+shipit:
+       if (!srv_send_smb(first_req->sconn,
+                         (char *)first_req->outbuf,
+                         true, first_req->seqnum+1,
+                         IS_CONN_ENCRYPTED(req->conn)||first_req->encrypted,
+                         &first_req->pcd)) {
+               exit_server_cleanly("construct_reply_chain: srv_send_smb "
+                                   "failed.");
+       }
+       TALLOC_FREE(req);       /* non-chained case */
+       TALLOC_FREE(reqs);      /* chained case */
+       return;
+
+error:
+       {
+               char errbuf[smb_size];
+               error_packet(errbuf, 0, 0, status, __LINE__, __FILE__);
+               if (!srv_send_smb(req->sconn, errbuf, true,
+                                 req->seqnum+1, req->encrypted,
+                                 NULL)) {
+                       exit_server_cleanly("construct_reply_chain: "
+                                           "srv_send_smb failed.");
+               }
+       }
+       TALLOC_FREE(req);       /* non-chained case */
+       TALLOC_FREE(reqs);      /* chained case */
+}
+
 /****************************************************************************
  Process an smb from the client
 ****************************************************************************/
@@ -1608,7 +1788,7 @@ static void process_smb(struct smbd_server_connection *sconn,
        DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
                  sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
 
-       if (msg_type != 0) {
+       if (msg_type != NBSSmessage) {
                /*
                 * NetBIOS session request, keepalive, etc.
                 */
@@ -1622,7 +1802,7 @@ static void process_smb(struct smbd_server_connection *sconn,
                if (smbd_is_smb2_header(inbuf, nread)) {
                        smbd_smb2_first_negprot(sconn, inbuf, nread);
                        return;
-               } else if (nread >= smb_size && valid_smb_header(inbuf)
+               } else if (nread >= smb_size && valid_smb_header(sconn, inbuf)
                                && CVAL(inbuf, smb_com) != 0x72) {
                        /* This is a non-negprot SMB1 packet.
                           Disable SMB2 from now on. */
@@ -1630,10 +1810,35 @@ static void process_smb(struct smbd_server_connection *sconn,
                }
        }
 
+       /* Make sure this is an SMB packet. smb_size contains NetBIOS header
+        * so subtract 4 from it. */
+       if ((nread < (smb_size - 4)) || !valid_smb_header(sconn, inbuf)) {
+               DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
+                        smb_len(inbuf)));
+
+               /* special magic for immediate exit */
+               if ((nread == 9) &&
+                   (IVAL(inbuf, 4) == 0x74697865) &&
+                   lp_parm_bool(-1, "smbd", "suicide mode", false)) {
+                       uint8_t exitcode = CVAL(inbuf, 8);
+                       DEBUG(1, ("Exiting immediately with code %d\n",
+                                 (int)exitcode));
+                       exit(exitcode);
+               }
+
+               exit_server_cleanly("Non-SMB packet");
+       }
+
        show_msg((char *)inbuf);
 
-       construct_reply(sconn, (char *)inbuf, nread, unread_bytes, seqnum,
-                       encrypted, deferred_pcd);
+       if ((unread_bytes == 0) && smb1_is_chain(inbuf)) {
+               construct_reply_chain(sconn, (char *)inbuf, nread,
+                                     seqnum, encrypted, deferred_pcd);
+       } else {
+               construct_reply(sconn, (char *)inbuf, nread, unread_bytes,
+                               seqnum, encrypted, deferred_pcd);
+       }
+
        sconn->trans_num++;
 
 done:
@@ -1684,15 +1889,21 @@ void remove_from_common_flags2(uint32 v)
 static void construct_reply_common(struct smb_request *req, const char *inbuf,
                                   char *outbuf)
 {
+       uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
+       uint16_t out_flags2 = common_flags2;
+
+       out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
+       out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
+       out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
+
        srv_set_message(outbuf,0,0,false);
 
        SCVAL(outbuf, smb_com, req->cmd);
        SIVAL(outbuf,smb_rcls,0);
        SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); 
-       SSVAL(outbuf,smb_flg2,
-               (SVAL(inbuf,smb_flg2) & FLAGS2_UNICODE_STRINGS) |
-               common_flags2);
+       SSVAL(outbuf,smb_flg2, out_flags2);
        memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
+       memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
 
        SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
        SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
@@ -1702,41 +1913,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);
-}
-
-/*
- * How many bytes have we already accumulated up to the current wct field
- * offset?
- */
-
-size_t req_wct_ofs(struct smb_request *req)
-{
-       size_t buf_size;
-
-       if (req->chain_outbuf == NULL) {
-               return smb_wct - 4;
-       }
-       buf_size = talloc_get_size(req->chain_outbuf);
-       if ((buf_size % 4) != 0) {
-               buf_size += (4 - (buf_size % 4));
-       }
-       return buf_size - 4;
-}
-
-/*
- * Hack around reply_nterror & friends not being aware of chained requests,
- * generating illegal (i.e. wct==0) chain replies.
- */
-
-static void fixup_chain_error_packet(struct smb_request *req)
-{
-       uint8_t *outbuf = req->outbuf;
-       req->outbuf = NULL;
-       reply_outbuf(req, 2, 0);
-       memcpy(req->outbuf, outbuf, smb_wct);
-       TALLOC_FREE(outbuf);
-       SCVAL(req->outbuf, smb_vwv0, 0xff);
+       construct_reply_common(req, (const char *)req->inbuf, outbuf);
 }
 
 /**
@@ -1756,7 +1933,9 @@ static bool find_andx_cmd_ofs(uint8_t *buf, size_t *pofs)
 
        cmd = CVAL(buf, smb_com);
 
-       SMB_ASSERT(is_andx_req(cmd));
+       if (!is_andx_req(cmd)) {
+               return false;
+       }
 
        ofs = smb_vwv0;
 
@@ -1772,7 +1951,9 @@ static bool find_andx_cmd_ofs(uint8_t *buf, size_t *pofs)
                 */
                ofs = SVAL(buf, ofs+2) + 4 + 1;
 
-               SMB_ASSERT(ofs+4 < talloc_get_size(buf));
+               if (ofs+4 >= talloc_get_size(buf)) {
+                       return false;
+               }
        }
 
        *pofs = ofs;
@@ -1782,39 +1963,27 @@ static bool find_andx_cmd_ofs(uint8_t *buf, size_t *pofs)
 /**
  * @brief Do the smb chaining at a buffer level
  * @param[in] poutbuf          Pointer to the talloc'ed buffer to be modified
- * @param[in] smb_command      The command that we want to issue
- * @param[in] wct              How many words?
- * @param[in] vwv              The words, already in network order
- * @param[in] bytes_alignment  How shall we align "bytes"?
- * @param[in] num_bytes                How many bytes?
- * @param[in] bytes            The data the request ships
- *
- * smb_splice_chain() adds the vwv and bytes to the request already present in
- * *poutbuf.
+ * @param[in] andx_buf         Buffer to be appended
  */
 
-static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
-                            uint8_t wct, const uint16_t *vwv,
-                            size_t bytes_alignment,
-                            uint32_t num_bytes, const uint8_t *bytes)
+static bool smb_splice_chain(uint8_t **poutbuf, const uint8_t *andx_buf)
 {
+       uint8_t smb_command     = CVAL(andx_buf, smb_com);
+       uint8_t wct             = CVAL(andx_buf, smb_wct);
+       const uint16_t *vwv     = (const uint16_t *)(andx_buf + smb_vwv);
+       uint32_t num_bytes      = smb_buflen(andx_buf);
+       const uint8_t *bytes    = (const uint8_t *)smb_buf_const(andx_buf);
+
        uint8_t *outbuf;
        size_t old_size, new_size;
        size_t ofs;
        size_t chain_padding = 0;
-       size_t bytes_padding = 0;
-       bool first_request;
-
-       old_size = talloc_get_size(*poutbuf);
+       size_t andx_cmd_ofs;
 
-       /*
-        * old_size == smb_wct means we're pushing the first request in for
-        * libsmb/
-        */
 
-       first_request = (old_size == smb_wct);
+       old_size = talloc_get_size(*poutbuf);
 
-       if (!first_request && ((old_size % 4) != 0)) {
+       if ((old_size % 4) != 0) {
                /*
                 * Align the wct field of subsequent requests to a 4-byte
                 * boundary
@@ -1824,52 +1993,39 @@ static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
 
        /*
         * After the old request comes the new wct field (1 byte), the vwv's
-        * and the num_bytes field. After at we might need to align the bytes
-        * given to us to "bytes_alignment", increasing the num_bytes value.
+        * and the num_bytes field.
         */
 
        new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
-
-       if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
-               bytes_padding = bytes_alignment - (new_size % bytes_alignment);
-       }
-
-       new_size += bytes_padding + num_bytes;
+       new_size += num_bytes;
 
        if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
-               DEBUG(1, ("splice_chain: %u bytes won't fit\n",
+               DEBUG(1, ("smb_splice_chain: %u bytes won't fit\n",
                          (unsigned)new_size));
                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;
        }
        *poutbuf = outbuf;
 
-       if (first_request) {
-               SCVAL(outbuf, smb_com, smb_command);
-       } else {
-               size_t andx_cmd_ofs;
-
-               if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
-                       DEBUG(1, ("invalid command chain\n"));
-                       *poutbuf = TALLOC_REALLOC_ARRAY(
-                               NULL, *poutbuf, uint8_t, old_size);
-                       return false;
-               }
-
-               if (chain_padding != 0) {
-                       memset(outbuf + old_size, 0, chain_padding);
-                       old_size += chain_padding;
-               }
+       if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
+               DEBUG(1, ("invalid command chain\n"));
+               *poutbuf = talloc_realloc(NULL, *poutbuf, uint8_t, old_size);
+               return false;
+       }
 
-               SCVAL(outbuf, andx_cmd_ofs, smb_command);
-               SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
+       if (chain_padding != 0) {
+               memset(outbuf + old_size, 0, chain_padding);
+               old_size += chain_padding;
        }
 
+       SCVAL(outbuf, andx_cmd_ofs, smb_command);
+       SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
+
        ofs = old_size;
 
        /*
@@ -1886,23 +2042,46 @@ static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
         */
 
        memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
-       ofs += sizeof(uint16_t) * wct;
 
        /*
-        * bcc (byte count)
+        * HACK ALERT
+        *
+        * Read&X has an offset into its data buffer at
+        * vwv[6]. reply_read_andx has no idea anymore that it's
+        * running from within a chain, so we have to fix up the
+        * offset here.
+        *
+        * Although it looks disgusting at this place, I want to keep
+        * it here. The alternative would be to push knowledge about
+        * the andx chain down into read&x again.
         */
 
-       SSVAL(outbuf, ofs, num_bytes + bytes_padding);
-       ofs += sizeof(uint16_t);
+       if (smb_command == SMBreadX) {
+               uint8_t *bytes_addr;
+
+               if (wct < 7) {
+                       /*
+                        * Invalid read&x response
+                        */
+                       return false;
+               }
+
+               bytes_addr = outbuf + ofs        /* vwv start */
+                       + sizeof(uint16_t) * wct /* vwv array */
+                       + sizeof(uint16_t);      /* bcc */
+
+               SSVAL(outbuf + ofs, 6 * sizeof(uint16_t),
+                     bytes_addr - outbuf - 4);
+       }
+
+       ofs += sizeof(uint16_t) * wct;
 
        /*
-        * padding
+        * bcc (byte count)
         */
 
-       if (bytes_padding != 0) {
-               memset(outbuf + ofs, 0, bytes_padding);
-               ofs += bytes_padding;
-       }
+       SSVAL(outbuf, ofs, num_bytes);
+       ofs += sizeof(uint16_t);
 
        /*
         * The bytes field
@@ -1913,268 +2092,244 @@ static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
        return true;
 }
 
-/****************************************************************************
- Construct a chained reply and add it to the already made reply
-****************************************************************************/
-
-void chain_reply(struct smb_request *req)
+bool smb1_is_chain(const uint8_t *buf)
 {
-       size_t smblen = smb_len(req->inbuf);
-       size_t already_used, length_needed;
-       uint8_t chain_cmd;
-       uint32_t chain_offset;  /* uint32_t to avoid overflow */
+       uint8_t cmd, wct, andx_cmd;
 
-       uint8_t wct;
-       uint16_t *vwv;
-       uint16_t buflen;
-       uint8_t *buf;
-
-       if (IVAL(req->outbuf, smb_rcls) != 0) {
-               fixup_chain_error_packet(req);
+       cmd = CVAL(buf, smb_com);
+       if (!is_andx_req(cmd)) {
+               return false;
        }
+       wct = CVAL(buf, smb_wct);
+       if (wct < 2) {
+               return false;
+       }
+       andx_cmd = CVAL(buf, smb_vwv);
+       return (andx_cmd != 0xFF);
+}
 
-       /*
-        * Any of the AndX requests and replies have at least a wct of
-        * 2. vwv[0] is the next command, vwv[1] is the offset from the
-        * beginning of the SMB header to the next wct field.
-        *
-        * None of the AndX requests put anything valuable in vwv[0] and [1],
-        * so we can overwrite it here to form the chain.
-        */
+bool smb1_walk_chain(const uint8_t *buf,
+                    bool (*fn)(uint8_t cmd,
+                               uint8_t wct, const uint16_t *vwv,
+                               uint16_t num_bytes, const uint8_t *bytes,
+                               void *private_data),
+                    void *private_data)
+{
+       size_t smblen = smb_len(buf);
+       const char *smb_buf = smb_base(buf);
+       uint8_t cmd, chain_cmd;
+       uint8_t wct;
+       const uint16_t *vwv;
+       uint16_t num_bytes;
+       const uint8_t *bytes;
 
-       if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
-               if (req->chain_outbuf == NULL) {
-                       req->chain_outbuf = TALLOC_REALLOC_ARRAY(
-                               req, req->outbuf, uint8_t,
-                               smb_len(req->outbuf) + 4);
-                       if (req->chain_outbuf == NULL) {
-                               smb_panic("talloc failed");
-                       }
-               }
-               req->outbuf = NULL;
-               goto error;
+       cmd = CVAL(buf, smb_com);
+       wct = CVAL(buf, smb_wct);
+       vwv = (const uint16_t *)(buf + smb_vwv);
+       num_bytes = smb_buflen(buf);
+       bytes = (uint8_t *)smb_buf_const(buf);
+
+       if (!fn(cmd, wct, vwv, num_bytes, bytes, private_data)) {
+               return false;
        }
 
-       /*
-        * Here we assume that this is the end of the chain. For that we need
-        * to set "next command" to 0xff and the offset to 0. If we later find
-        * more commands in the chain, this will be overwritten again.
-        */
+       if (!is_andx_req(cmd)) {
+               return true;
+       }
+       if (wct < 2) {
+               return false;
+       }
+
+       chain_cmd = CVAL(vwv, 0);
+
+       while (chain_cmd != 0xff) {
+               uint32_t chain_offset;  /* uint32_t to avoid overflow */
+               size_t length_needed;
+               ptrdiff_t vwv_offset;
 
-       SCVAL(req->outbuf, smb_vwv0, 0xff);
-       SCVAL(req->outbuf, smb_vwv0+1, 0);
-       SSVAL(req->outbuf, smb_vwv1, 0);
+               chain_offset = SVAL(vwv+1, 0);
 
-       if (req->chain_outbuf == NULL) {
                /*
-                * In req->chain_outbuf we collect all the replies. Start the
-                * chain by copying in the first reply.
-                *
-                * We do the realloc because later on we depend on
-                * talloc_get_size to determine the length of
-                * chain_outbuf. The reply_xxx routines might have
-                * over-allocated (reply_pipe_read_and_X used to be such an
-                * example).
+                * Check if the client tries to fool us. The chain
+                * offset needs to point beyond the current request in
+                * the chain, it needs to strictly grow. Otherwise we
+                * might be tricked into an endless loop always
+                * processing the same request over and over again. We
+                * used to assume that vwv and the byte buffer array
+                * in a chain are always attached, but OS/2 the
+                * Write&X/Read&X chain puts the Read&X vwv array
+                * right behind the Write&X vwv chain. The Write&X bcc
+                * array is put behind the Read&X vwv array. So now we
+                * check whether the chain offset points strictly
+                * behind the previous vwv array. req->buf points
+                * right after the vwv array of the previous
+                * request. See
+                * https://bugzilla.samba.org/show_bug.cgi?id=8360 for
+                * more information.
                 */
-               req->chain_outbuf = TALLOC_REALLOC_ARRAY(
-                       req, req->outbuf, uint8_t,
-                       smb_len_large(req->outbuf) + 4);
-               if (req->chain_outbuf == NULL) {
-                       smb_panic("talloc failed");
+
+               vwv_offset = ((const char *)vwv - smb_buf);
+               if (chain_offset <= vwv_offset) {
+                       return false;
                }
-               req->outbuf = NULL;
-       } else {
+
                /*
-                * Update smb headers where subsequent chained commands
-                * may have updated them.
+                * Next check: Make sure the chain offset does not
+                * point beyond the overall smb request length.
                 */
-               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),
-                                     CVAL(req->outbuf, smb_wct),
-                                     (uint16_t *)(req->outbuf + smb_vwv),
-                                     0, smb_buflen(req->outbuf),
-                                     (uint8_t *)smb_buf(req->outbuf))) {
-                       goto error;
+
+               length_needed = chain_offset+1; /* wct */
+               if (length_needed > smblen) {
+                       return false;
                }
-               TALLOC_FREE(req->outbuf);
-       }
 
-       /*
-        * We use the old request's vwv field to grab the next chained command
-        * and offset into the chained fields.
-        */
+               /*
+                * Now comes the pointer magic. Goal here is to set up
+                * vwv and buf correctly again. The chain offset (the
+                * former vwv[1]) points at the new wct field.
+                */
+
+               wct = CVAL(smb_buf, chain_offset);
 
-       chain_cmd = CVAL(req->vwv+0, 0);
-       chain_offset = SVAL(req->vwv+1, 0);
+               if (is_andx_req(chain_cmd) && (wct < 2)) {
+                       return false;
+               }
 
-       if (chain_cmd == 0xff) {
                /*
-                * End of chain, no more requests from the client. So ship the
-                * replies.
+                * Next consistency check: Make the new vwv array fits
+                * in the overall smb request.
                 */
-               smb_setlen((char *)(req->chain_outbuf),
-                          talloc_get_size(req->chain_outbuf) - 4);
-
-               if (!srv_send_smb(req->sconn, (char *)req->chain_outbuf,
-                                 true, req->seqnum+1,
-                                 IS_CONN_ENCRYPTED(req->conn)
-                                 ||req->encrypted,
-                                 &req->pcd)) {
-                       exit_server_cleanly("chain_reply: srv_send_smb "
-                                           "failed.");
-               }
-               TALLOC_FREE(req->chain_outbuf);
-               req->done = true;
-               return;
-       }
 
-       /* add a new perfcounter for this element of chain */
-       SMB_PERFCOUNT_ADD(&req->pcd);
-       SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd);
-       SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen);
+               length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
+               if (length_needed > smblen) {
+                       return false;
+               }
+               vwv = (const uint16_t *)(smb_buf + chain_offset + 1);
 
-       /*
-        * Check if the client tries to fool us. The chain offset
-        * needs to point beyond the current request in the chain, it
-        * needs to strictly grow. Otherwise we might be tricked into
-        * an endless loop always processing the same request over and
-        * over again. We used to assume that vwv and the byte buffer
-        * array in a chain are always attached, but OS/2 the
-        * Write&X/Read&X chain puts the Read&X vwv array right behind
-        * the Write&X vwv chain. The Write&X bcc array is put behind
-        * the Read&X vwv array. So now we check whether the chain
-        * offset points strictly behind the previous vwv
-        * array. req->buf points right after the vwv array of the
-        * previous request. See
-        * https://bugzilla.samba.org/show_bug.cgi?id=8360 for more
-        * information.
-        */
+               /*
+                * Now grab the new byte buffer....
+                */
 
-       already_used = PTR_DIFF(req->buf, smb_base(req->inbuf));
-       if (chain_offset <= already_used) {
-               goto error;
-       }
+               num_bytes = SVAL(vwv+wct, 0);
 
-       /*
-        * Next check: Make sure the chain offset does not point beyond the
-        * overall smb request length.
-        */
+               /*
+                * .. and check that it fits.
+                */
 
-       length_needed = chain_offset+1; /* wct */
-       if (length_needed > smblen) {
-               goto error;
-       }
+               length_needed += num_bytes;
+               if (length_needed > smblen) {
+                       return false;
+               }
+               bytes = (const uint8_t *)(vwv+wct+1);
 
-       /*
-        * Now comes the pointer magic. Goal here is to set up req->vwv and
-        * req->buf correctly again to be able to call the subsequent
-        * switch_message(). The chain offset (the former vwv[1]) points at
-        * the new wct field.
-        */
+               if (!fn(chain_cmd, wct, vwv, num_bytes, bytes, private_data)) {
+                       return false;
+               }
 
-       wct = CVAL(smb_base(req->inbuf), chain_offset);
+               if (!is_andx_req(chain_cmd)) {
+                       return true;
+               }
+               chain_cmd = CVAL(vwv, 0);
+       }
+       return true;
+}
 
-       /*
-        * Next consistency check: Make the new vwv array fits in the overall
-        * smb request.
-        */
+static bool smb1_chain_length_cb(uint8_t cmd,
+                                uint8_t wct, const uint16_t *vwv,
+                                uint16_t num_bytes, const uint8_t *bytes,
+                                void *private_data)
+{
+       unsigned *count = (unsigned *)private_data;
+       *count += 1;
+       return true;
+}
 
-       length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
-       if (length_needed > smblen) {
-               goto error;
+unsigned smb1_chain_length(const uint8_t *buf)
+{
+       unsigned count = 0;
+
+       if (!smb1_walk_chain(buf, smb1_chain_length_cb, &count)) {
+               return 0;
        }
-       vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
+       return count;
+}
 
-       /*
-        * Now grab the new byte buffer....
-        */
+struct smb1_parse_chain_state {
+       TALLOC_CTX *mem_ctx;
+       const uint8_t *buf;
+       struct smbd_server_connection *sconn;
+       bool encrypted;
+       uint32_t seqnum;
 
-       buflen = SVAL(vwv+wct, 0);
+       struct smb_request **reqs;
+       unsigned num_reqs;
+};
 
-       /*
-        * .. and check that it fits.
-        */
+static bool smb1_parse_chain_cb(uint8_t cmd,
+                               uint8_t wct, const uint16_t *vwv,
+                               uint16_t num_bytes, const uint8_t *bytes,
+                               void *private_data)
+{
+       struct smb1_parse_chain_state *state =
+               (struct smb1_parse_chain_state *)private_data;
+       struct smb_request **reqs;
+       struct smb_request *req;
+       bool ok;
 
-       length_needed += buflen;
-       if (length_needed > smblen) {
-               goto error;
+       reqs = talloc_realloc(state->mem_ctx, state->reqs,
+                             struct smb_request *, state->num_reqs+1);
+       if (reqs == NULL) {
+               return false;
        }
-       buf = (uint8_t *)(vwv+wct+1);
+       state->reqs = reqs;
 
-       req->cmd = chain_cmd;
-       req->wct = wct;
-       req->vwv = vwv;
-       req->buflen = buflen;
-       req->buf = buf;
-
-       switch_message(chain_cmd, req, smblen);
-
-       if (req->outbuf == NULL) {
-               /*
-                * This happens if the chained command has suspended itself or
-                * if it has called srv_send_smb() itself.
-                */
-               return;
+       req = talloc(reqs, struct smb_request);
+       if (req == NULL) {
+               return false;
        }
 
-       /*
-        * We end up here if the chained command was not itself chained or
-        * suspended, but for example a close() command. We now need to splice
-        * the chained commands' outbuf into the already built up chain_outbuf
-        * and ship the result.
-        */
-       goto done;
+       ok = init_smb_request(req, state->sconn, state->buf, 0,
+                             state->encrypted, state->seqnum);
+       if (!ok) {
+               return false;
+       }
+       req->cmd = cmd;
+       req->wct = wct;
+       req->vwv = vwv;
+       req->buflen = num_bytes;
+       req->buf = bytes;
 
- error:
-       /*
-        * We end up here if there's any error in the chain syntax. Report a
-        * DOS error, just like Windows does.
-        */
-       reply_force_doserror(req, ERRSRV, ERRerror);
-       fixup_chain_error_packet(req);
+       reqs[state->num_reqs] = req;
+       state->num_reqs += 1;
+       return true;
+}
 
- done:
-       /*
-        * This scary statement intends to set the
-        * FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf
-        * to the value req->outbuf carries
-        */
-       SSVAL(req->chain_outbuf, smb_flg2,
-             (SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
-             | (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
+bool smb1_parse_chain(TALLOC_CTX *mem_ctx, const uint8_t *buf,
+                     struct smbd_server_connection *sconn,
+                     bool encrypted, uint32_t seqnum,
+                     struct smb_request ***reqs, unsigned *num_reqs)
+{
+       struct smb1_parse_chain_state state;
+       unsigned i;
 
-       /*
-        * Transfer the error codes from the subrequest to the main one
-        */
-       SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
-       SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err));
+       state.mem_ctx = mem_ctx;
+       state.buf = buf;
+       state.sconn = sconn;
+       state.encrypted = encrypted;
+       state.seqnum = seqnum;
+       state.reqs = NULL;
+       state.num_reqs = 0;
 
-       if (!smb_splice_chain(&req->chain_outbuf,
-                             CVAL(req->outbuf, smb_com),
-                             CVAL(req->outbuf, smb_wct),
-                             (uint16_t *)(req->outbuf + smb_vwv),
-                             0, smb_buflen(req->outbuf),
-                             (uint8_t *)smb_buf(req->outbuf))) {
-               exit_server_cleanly("chain_reply: smb_splice_chain failed\n");
+       if (!smb1_walk_chain(buf, smb1_parse_chain_cb, &state)) {
+               TALLOC_FREE(state.reqs);
+               return false;
        }
-       TALLOC_FREE(req->outbuf);
-
-       smb_setlen((char *)(req->chain_outbuf),
-                  talloc_get_size(req->chain_outbuf) - 4);
-
-       show_msg((char *)(req->chain_outbuf));
-
-       if (!srv_send_smb(req->sconn, (char *)req->chain_outbuf,
-                         true, req->seqnum+1,
-                         IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
-                         &req->pcd)) {
-               exit_server_cleanly("chain_reply: srv_send_smb failed.");
+       for (i=0; i<state.num_reqs; i++) {
+               state.reqs[i]->chain = state.reqs;
        }
-       TALLOC_FREE(req->chain_outbuf);
-       req->done = true;
+       *reqs = state.reqs;
+       *num_reqs = state.num_reqs;
+       return true;
 }
 
 /****************************************************************************
@@ -2189,7 +2344,7 @@ static void check_reload(struct smbd_server_connection *sconn, time_t t)
        }
 
        if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
-               reload_services(sconn->msg_ctx, sconn->sock, True);
+               reload_services(sconn, conn_snum_used, true);
                last_smb_conf_reload_time = t;
        }
 }
@@ -2204,13 +2359,14 @@ static bool fd_is_readable(int fd)
 
 }
 
-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;
@@ -2220,35 +2376,41 @@ static void smbd_server_connection_read_handler(
        NTSTATUS status;
        uint32_t seqnum;
 
-       bool from_client = (conn->sock == fd);
+       bool from_client;
+
+       if (lp_async_smb_echo_handler()
+           && fd_is_readable(sconn->smb1.echo_handler.trusted_fd)) {
+               /*
+                * This is the super-ugly hack to prefer the packets
+                * forwarded by the echo handler over the ones by the
+                * client directly
+                */
+               fd = sconn->smb1.echo_handler.trusted_fd;
+       }
+
+       from_client = (sconn->sock == fd);
 
        if (from_client) {
-               smbd_lock_socket(conn);
+               smbd_lock_socket(sconn);
 
-               if (lp_async_smb_echo_handler() && !fd_is_readable(fd)) {
+               if (!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, conn, fd,
-                                           (char **)(void *)&inbuf,
-                                           0, /* timeout */
-                                           &unread_bytes,
-                                           &encrypted,
-                                           &inbuf_len, &seqnum,
-                                           false /* trusted channel */);
-               smbd_unlock_socket(conn);
-       } else {
-               /* TODO: make this completely nonblocking */
-               status = receive_smb_talloc(mem_ctx, conn, fd,
-                                           (char **)(void *)&inbuf,
-                                           0, /* timeout */
-                                           &unread_bytes,
-                                           &encrypted,
-                                           &inbuf_len, &seqnum,
-                                           true /* trusted channel */);
+       /* TODO: make this completely nonblocking */
+       status = receive_smb_talloc(mem_ctx, sconn, fd,
+                                   (char **)(void *)&inbuf,
+                                   0, /* timeout */
+                                   &unread_bytes,
+                                   &encrypted,
+                                   &inbuf_len, &seqnum,
+                                   false /* trusted channel */);
+
+       if (from_client) {
+               smbd_unlock_socket(sconn);
        }
 
        if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
@@ -2262,7 +2424,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);
 }
 
@@ -2303,12 +2465,22 @@ static void smbd_server_echo_handler(struct event_context *ev,
        }
 }
 
+#ifdef CLUSTER_SUPPORT
+
+struct smbd_release_ip_state {
+       struct smbd_server_connection *sconn;
+       char addr[INET6_ADDRSTRLEN];
+};
+
 /****************************************************************************
 received when we should release a specific IP
 ****************************************************************************/
 static void release_ip(const char *ip, void *priv)
 {
-       const char *addr = (const char *)priv;
+       struct smbd_release_ip_state *state =
+               talloc_get_type_abort(priv,
+               struct smbd_release_ip_state);
+       const char *addr = state->addr;
        const char *p = addr;
 
        if (strncmp("::ffff:", addr, 7) == 0) {
@@ -2319,29 +2491,55 @@ static void release_ip(const char *ip, void *priv)
                   "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
-                  are still running after the failover has finished -
-                  we have to get rid of this process ID straight
-                  away */
                DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
                        ip));
-               /* note we must exit with non-zero status so the unclean handler gets
-                  called in the parent, so that the brl database is tickled */
-               _exit(1);
+               /*
+                * With SMB2 we should do a clean disconnect,
+                * the previous_session_id in the session setup
+                * will cleanup the old session, tcons and opens.
+                *
+                * A clean disconnect is needed in order to support
+                * durable handles.
+                *
+                * Note: typically this is never triggered
+                *       as we got a TCP RST (triggered by ctdb event scripts)
+                *       before we get CTDB_SRVID_RELEASE_IP.
+                *
+                * We used to call _exit(1) here, but as this was mostly never
+                * triggered and has implication on our process model,
+                * we can just use smbd_server_connection_terminate()
+                * (also for SMB1).
+                */
+               smbd_server_connection_terminate(state->sconn,
+                                                "CTDB_SRVID_RELEASE_IP");
+               return;
        }
 }
 
-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)
+static NTSTATUS smbd_register_ips(struct smbd_server_connection *sconn,
+                                 struct sockaddr_storage *srv,
+                                 struct sockaddr_storage *clnt)
 {
-       struct smbd_server_connection *sconn = talloc_get_type_abort(
-               private_data, struct smbd_server_connection);
+       struct smbd_release_ip_state *state;
+       struct ctdbd_connection *cconn;
+
+       cconn = messaging_ctdbd_connection();
+       if (cconn == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       state = talloc_zero(sconn, struct smbd_release_ip_state);
+       if (state == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+       state->sconn = sconn;
+       if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
-       release_ip((char *)data->data, sconn->client_id.addr);
+       return ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
 }
 
-#ifdef CLUSTER_SUPPORT
 static int client_get_tcp_info(int sock, struct sockaddr_storage *server,
                               struct sockaddr_storage *client)
 {
@@ -2363,7 +2561,8 @@ static int client_get_tcp_info(int sock, struct sockaddr_storage *server,
  */
 static bool keepalive_fn(const struct timeval *now, void *private_data)
 {
-       struct smbd_server_connection *sconn = smbd_server_conn;
+       struct smbd_server_connection *sconn = talloc_get_type_abort(
+               private_data, struct smbd_server_connection);
        bool ret;
 
        if (sconn->using_smb2) {
@@ -2371,9 +2570,9 @@ static bool keepalive_fn(const struct timeval *now, void *private_data)
                return false;
        }
 
-       smbd_lock_socket(smbd_server_conn);
+       smbd_lock_socket(sconn);
        ret = send_keepalive(sconn->sock);
-       smbd_unlock_socket(smbd_server_conn);
+       smbd_unlock_socket(sconn);
 
        if (!ret) {
                char addr[INET6_ADDRSTRLEN];
@@ -2429,9 +2628,6 @@ static bool housekeeping_fn(const struct timeval *now, void *private_data)
        /* check if we need to reload services */
        check_reload(sconn, time_mono(NULL));
 
-       /* Change machine password if neccessary. */
-       attempt_machine_password_change();
-
         /*
         * Force a log file check.
         */
@@ -2440,30 +2636,158 @@ static bool housekeeping_fn(const struct timeval *now, void *private_data)
        return true;
 }
 
-static int create_unlink_tmp(const char *dir)
+/*
+ * Read an smb packet in the echo handler child, giving the parent
+ * smbd one second to react once the socket becomes readable.
+ */
+
+struct smbd_echo_read_state {
+       struct tevent_context *ev;
+       struct smbd_server_connection *sconn;
+
+       char *buf;
+       size_t buflen;
+       uint32_t seqnum;
+};
+
+static void smbd_echo_read_readable(struct tevent_req *subreq);
+static void smbd_echo_read_waited(struct tevent_req *subreq);
+
+static struct tevent_req *smbd_echo_read_send(
+       TALLOC_CTX *mem_ctx, struct tevent_context *ev,
+       struct smbd_server_connection *sconn)
 {
-       char *fname;
-       int fd;
+       struct tevent_req *req, *subreq;
+       struct smbd_echo_read_state *state;
 
-       fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
-       if (fname == NULL) {
-               errno = ENOMEM;
-               return -1;
+       req = tevent_req_create(mem_ctx, &state,
+                               struct smbd_echo_read_state);
+       if (req == NULL) {
+               return NULL;
        }
-       fd = mkstemp(fname);
-       if (fd == -1) {
-               TALLOC_FREE(fname);
-               return -1;
+       state->ev = ev;
+       state->sconn = sconn;
+
+       subreq = wait_for_read_send(state, ev, sconn->sock);
+       if (tevent_req_nomem(subreq, req)) {
+               return tevent_req_post(req, ev);
        }
-       if (unlink(fname) == -1) {
-               int sys_errno = errno;
-               close(fd);
-               TALLOC_FREE(fname);
-               errno = sys_errno;
-               return -1;
+       tevent_req_set_callback(subreq, smbd_echo_read_readable, req);
+       return req;
+}
+
+static void smbd_echo_read_readable(struct tevent_req *subreq)
+{
+       struct tevent_req *req = tevent_req_callback_data(
+               subreq, struct tevent_req);
+       struct smbd_echo_read_state *state = tevent_req_data(
+               req, struct smbd_echo_read_state);
+       bool ok;
+       int err;
+
+       ok = wait_for_read_recv(subreq, &err);
+       TALLOC_FREE(subreq);
+       if (!ok) {
+               tevent_req_nterror(req, map_nt_error_from_unix(err));
+               return;
        }
-       TALLOC_FREE(fname);
-       return fd;
+
+       /*
+        * Give the parent smbd one second to step in
+        */
+
+       subreq = tevent_wakeup_send(
+               state, state->ev, timeval_current_ofs(1, 0));
+       if (tevent_req_nomem(subreq, req)) {
+               return;
+       }
+       tevent_req_set_callback(subreq, smbd_echo_read_waited, req);
+}
+
+static void smbd_echo_read_waited(struct tevent_req *subreq)
+{
+       struct tevent_req *req = tevent_req_callback_data(
+               subreq, struct tevent_req);
+       struct smbd_echo_read_state *state = tevent_req_data(
+               req, struct smbd_echo_read_state);
+       struct smbd_server_connection *sconn = state->sconn;
+       bool ok;
+       NTSTATUS status;
+       size_t unread = 0;
+       bool encrypted;
+
+       ok = tevent_wakeup_recv(subreq);
+       TALLOC_FREE(subreq);
+       if (!ok) {
+               tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
+               return;
+       }
+
+       ok = smbd_lock_socket_internal(sconn);
+       if (!ok) {
+               tevent_req_nterror(req, map_nt_error_from_unix(errno));
+               DEBUG(0, ("%s: failed to lock socket\n", __location__));
+               return;
+       }
+
+       if (!fd_is_readable(sconn->sock)) {
+               DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
+                         (int)getpid()));
+
+               ok = smbd_unlock_socket_internal(sconn);
+               if (!ok) {
+                       tevent_req_nterror(req, map_nt_error_from_unix(errno));
+                       DEBUG(1, ("%s: failed to unlock socket\n",
+                               __location__));
+                       return;
+               }
+
+               subreq = wait_for_read_send(state, state->ev, sconn->sock);
+               if (tevent_req_nomem(subreq, req)) {
+                       return;
+               }
+               tevent_req_set_callback(subreq, smbd_echo_read_readable, req);
+               return;
+       }
+
+       status = receive_smb_talloc(state, sconn, sconn->sock, &state->buf,
+                                   0 /* timeout */,
+                                   &unread,
+                                   &encrypted,
+                                   &state->buflen,
+                                   &state->seqnum,
+                                   false /* trusted_channel*/);
+
+       if (tevent_req_nterror(req, status)) {
+               tevent_req_nterror(req, status);
+               DEBUG(1, ("echo_handler[%d]: receive_smb_raw_talloc failed: %s\n",
+                         (int)getpid(), nt_errstr(status)));
+               return;
+       }
+
+       ok = smbd_unlock_socket_internal(sconn);
+       if (!ok) {
+               tevent_req_nterror(req, map_nt_error_from_unix(errno));
+               DEBUG(1, ("%s: failed to unlock socket\n", __location__));
+               return;
+       }
+       tevent_req_done(req);
+}
+
+static NTSTATUS smbd_echo_read_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
+                                   char **pbuf, size_t *pbuflen, uint32_t *pseqnum)
+{
+       struct smbd_echo_read_state *state = tevent_req_data(
+               req, struct smbd_echo_read_state);
+       NTSTATUS status;
+
+       if (tevent_req_is_nterror(req, &status)) {
+               return status;
+       }
+       *pbuf = talloc_move(mem_ctx, &state->buf);
+       *pbuflen = state->buflen;
+       *pseqnum = state->seqnum;
+       return NT_STATUS_OK;
 }
 
 struct smbd_echo_state {
@@ -2474,7 +2798,6 @@ struct smbd_echo_state {
 
        struct tevent_fd *parent_fde;
 
-       struct tevent_fd *read_fde;
        struct tevent_req *write_req;
 };
 
@@ -2522,20 +2845,20 @@ static void smbd_echo_writer_done(struct tevent_req *req)
                DEBUG(1, ("writev to parent failed: %s\n", strerror(err)));
                exit(1);
        }
-       DEBUG(10,("echo_handler[%d]: forwarded pdu to main\n", (int)sys_getpid()));
+       DEBUG(10,("echo_handler[%d]: forwarded pdu to main\n", (int)getpid()));
        smbd_echo_activate_writer(state);
 }
 
-static bool smbd_echo_reply(uint8_t *inbuf, size_t inbuf_len,
+static bool smbd_echo_reply(struct smbd_echo_state *state,
+                           uint8_t *inbuf, size_t inbuf_len,
                            uint32_t seqnum)
 {
        struct smb_request req;
        uint16_t num_replies;
-       size_t out_len;
        char *outbuf;
        bool ok;
 
-       if ((inbuf_len == 4) && (CVAL(inbuf, 0) == SMBkeepalive)) {
+       if ((inbuf_len == 4) && (CVAL(inbuf, 0) == NBSSkeepalive)) {
                DEBUG(10, ("Got netbios keepalive\n"));
                /*
                 * Just swallow it
@@ -2547,12 +2870,12 @@ static bool smbd_echo_reply(uint8_t *inbuf, size_t inbuf_len,
                DEBUG(10, ("Got short packet: %d bytes\n", (int)inbuf_len));
                return false;
        }
-       if (!valid_smb_header(inbuf)) {
+       if (!valid_smb_header(state->sconn, inbuf)) {
                DEBUG(10, ("Got invalid SMB header\n"));
                return false;
        }
 
-       if (!init_smb_request(&req, smbd_server_conn, inbuf, 0, false,
+       if (!init_smb_request(&req, state->sconn, inbuf, 0, false,
                              seqnum)) {
                return false;
        }
@@ -2575,7 +2898,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;
@@ -2588,8 +2911,6 @@ static bool smbd_echo_reply(uint8_t *inbuf, size_t inbuf_len,
                memcpy(smb_buf(req.outbuf), req.buf, req.buflen);
        }
 
-       out_len = smb_len(req.outbuf) + 4;
-
        ok = srv_send_smb(req.sconn,
                          (char *)outbuf,
                          true, seqnum+1,
@@ -2610,107 +2931,13 @@ static void smbd_echo_exit(struct tevent_context *ev,
        exit(0);
 }
 
-static void smbd_echo_reader(struct tevent_context *ev,
-                            struct tevent_fd *fde, uint16_t flags,
-                            void *private_data)
-{
-       struct smbd_echo_state *state = talloc_get_type_abort(
-               private_data, struct smbd_echo_state);
-       struct smbd_server_connection *sconn = state->sconn;
-       size_t unread, num_pending;
-       NTSTATUS status;
-       struct iovec *tmp;
-       size_t iov_len;
-       uint32_t seqnum = 0;
-       bool reply;
-       bool ok;
-       bool encrypted = false;
-
-       smb_msleep(1000);
-
-       ok = smbd_lock_socket_internal(sconn);
-       if (!ok) {
-               DEBUG(0, ("%s: failed to lock socket\n",
-                       __location__));
-               exit(1);
-       }
-
-       if (!fd_is_readable(sconn->sock)) {
-               DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
-                         (int)sys_getpid()));
-               ok = smbd_unlock_socket_internal(sconn);
-               if (!ok) {
-                       DEBUG(1, ("%s: failed to unlock socket in\n",
-                               __location__));
-                       exit(1);
-               }
-               return;
-       }
-
-       num_pending = talloc_array_length(state->pending);
-       tmp = talloc_realloc(state, state->pending, struct iovec,
-                            num_pending+1);
-       if (tmp == NULL) {
-               DEBUG(1, ("talloc_realloc failed\n"));
-               exit(1);
-       }
-       state->pending = tmp;
-
-       DEBUG(10,("echo_handler[%d]: reading pdu\n", (int)sys_getpid()));
-
-       status = receive_smb_talloc(state->pending, sconn, sconn->sock,
-                                   (char **)(void *)&state->pending[num_pending].iov_base,
-                                   0 /* timeout */,
-                                   &unread,
-                                   &encrypted,
-                                   &iov_len,
-                                   &seqnum,
-                                   false /* trusted_channel*/);
-       if (!NT_STATUS_IS_OK(status)) {
-               DEBUG(1, ("echo_handler[%d]: receive_smb_raw_talloc failed: %s\n",
-                         (int)sys_getpid(), nt_errstr(status)));
-               exit(1);
-       }
-       state->pending[num_pending].iov_len = iov_len;
-
-       ok = smbd_unlock_socket_internal(sconn);
-       if (!ok) {
-               DEBUG(1, ("%s: failed to unlock socket in\n",
-                       __location__));
-               exit(1);
-       }
-
-       reply = smbd_echo_reply((uint8_t *)state->pending[num_pending].iov_base,
-                               state->pending[num_pending].iov_len,
-                               seqnum);
-       if (reply) {
-               DEBUG(10,("echo_handler[%d]: replied to client\n", (int)sys_getpid()));
-               /* no check, shrinking by some bytes does not fail */
-               state->pending = talloc_realloc(state, state->pending,
-                                               struct iovec,
-                                               num_pending);
-               return;
-       }
-
-       if (state->pending[num_pending].iov_len >= smb_size) {
-               /*
-                * place the seqnum in the packet so that the main process
-                * can reply with signing
-                */
-               SIVAL((uint8_t *)state->pending[num_pending].iov_base,
-                     smb_ss_field, seqnum);
-               SIVAL((uint8_t *)state->pending[num_pending].iov_base,
-                     smb_ss_field+4, NT_STATUS_V(NT_STATUS_OK));
-       }
-
-       DEBUG(10,("echo_handler[%d]: forward to main\n", (int)sys_getpid()));
-       smbd_echo_activate_writer(state);
-}
+static void smbd_echo_got_packet(struct tevent_req *req);
 
 static void smbd_echo_loop(struct smbd_server_connection *sconn,
                           int parent_pipe)
 {
        struct smbd_echo_state *state;
+       struct tevent_req *read_req;
 
        state = talloc_zero(sconn, struct smbd_echo_state);
        if (state == NULL) {
@@ -2733,14 +2960,14 @@ static void smbd_echo_loop(struct smbd_server_connection *sconn,
                TALLOC_FREE(state);
                return;
        }
-       state->read_fde = tevent_add_fd(state->ev, state, sconn->sock,
-                                       TEVENT_FD_READ, smbd_echo_reader,
-                                       state);
-       if (state->read_fde == NULL) {
-               DEBUG(1, ("tevent_add_fd failed\n"));
+
+       read_req = smbd_echo_read_send(state, state->ev, sconn);
+       if (read_req == NULL) {
+               DEBUG(1, ("smbd_echo_read_send failed\n"));
                TALLOC_FREE(state);
                return;
        }
+       tevent_req_set_callback(read_req, smbd_echo_got_packet, state);
 
        while (true) {
                if (tevent_loop_once(state->ev) == -1) {
@@ -2752,6 +2979,66 @@ static void smbd_echo_loop(struct smbd_server_connection *sconn,
        TALLOC_FREE(state);
 }
 
+static void smbd_echo_got_packet(struct tevent_req *req)
+{
+       struct smbd_echo_state *state = tevent_req_callback_data(
+               req, struct smbd_echo_state);
+       NTSTATUS status;
+       char *buf = NULL;
+       size_t buflen = 0;
+       uint32_t seqnum = 0;
+       bool reply;
+
+       status = smbd_echo_read_recv(req, state, &buf, &buflen, &seqnum);
+       TALLOC_FREE(req);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(1, ("smbd_echo_read_recv returned %s\n",
+                         nt_errstr(status)));
+               exit(1);
+       }
+
+       reply = smbd_echo_reply(state, (uint8_t *)buf, buflen, seqnum);
+       if (!reply) {
+               size_t num_pending;
+               struct iovec *tmp;
+               struct iovec *iov;
+
+               num_pending = talloc_array_length(state->pending);
+               tmp = talloc_realloc(state, state->pending, struct iovec,
+                                    num_pending+1);
+               if (tmp == NULL) {
+                       DEBUG(1, ("talloc_realloc failed\n"));
+                       exit(1);
+               }
+               state->pending = tmp;
+
+               if (buflen >= smb_size) {
+                       /*
+                        * place the seqnum in the packet so that the main process
+                        * can reply with signing
+                        */
+                       SIVAL(buf, smb_ss_field, seqnum);
+                       SIVAL(buf, smb_ss_field+4, NT_STATUS_V(NT_STATUS_OK));
+               }
+
+               iov = &state->pending[num_pending];
+               iov->iov_base = buf;
+               iov->iov_len = buflen;
+
+               DEBUG(10,("echo_handler[%d]: forward to main\n",
+                         (int)getpid()));
+               smbd_echo_activate_writer(state);
+       }
+
+       req = smbd_echo_read_send(state, state->ev, state->sconn);
+       if (req == NULL) {
+               DEBUG(1, ("smbd_echo_read_send failed\n"));
+               exit(1);
+       }
+       tevent_req_set_callback(req, smbd_echo_got_packet, state);
+}
+
+
 /*
  * Handle SMBecho requests in a forked child process
  */
@@ -2772,7 +3059,7 @@ bool fork_echo_handler(struct smbd_server_connection *sconn)
                goto fail;
        }
 
-       child = sys_fork();
+       child = fork();
        if (child == 0) {
                NTSTATUS status;
 
@@ -2780,8 +3067,8 @@ 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(),
-                                          procid_self(), false);
+                                          sconn->ev_ctx,
+                                          false);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(1, ("reinit_after_fork failed: %s\n",
                                  nt_errstr(status)));
@@ -2794,16 +3081,16 @@ bool fork_echo_handler(struct smbd_server_connection *sconn)
        listener_pipe[1] = -1;
        sconn->smb1.echo_handler.trusted_fd = listener_pipe[0];
 
-       DEBUG(10,("fork_echo_handler: main[%d] echo_child[%d]\n", (int)sys_getpid(), child));
+       DEBUG(10,("fork_echo_handler: main[%d] echo_child[%d]\n", (int)getpid(), child));
 
        /*
         * 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 = tevent_add_fd(sconn->ev_ctx,
                                        sconn,
                                        sconn->smb1.echo_handler.trusted_fd,
-                                       EVENT_FD_READ,
+                                       TEVENT_FD_READ,
                                        smbd_server_echo_handler,
                                        sconn);
        if (sconn->smb1.echo_handler.trusted_fde == NULL) {
@@ -2829,47 +3116,230 @@ fail:
        return false;
 }
 
-#if CLUSTER_SUPPORT
+static bool uid_in_use(const struct user_struct *user, uid_t uid)
+{
+       while (user) {
+               if (user->session_info &&
+                   (user->session_info->unix_token->uid == uid)) {
+                       return true;
+               }
+               user = user->next;
+       }
+       return false;
+}
 
-static NTSTATUS smbd_register_ips(struct smbd_server_connection *sconn,
-                                 struct sockaddr_storage *srv,
-                                 struct sockaddr_storage *clnt)
+static bool gid_in_use(const struct user_struct *user, gid_t gid)
 {
-       struct ctdbd_connection *cconn;
-       char tmp_addr[INET6_ADDRSTRLEN];
-       char *addr;
+       while (user) {
+               if (user->session_info != NULL) {
+                       int i;
+                       struct security_unix_token *utok;
 
-       cconn = messaging_ctdbd_connection();
-       if (cconn == NULL) {
-               return NT_STATUS_NO_MEMORY;
+                       utok = user->session_info->unix_token;
+                       if (utok->gid == gid) {
+                               return true;
+                       }
+                       for(i=0; i<utok->ngroups; i++) {
+                               if (utok->groups[i] == gid) {
+                                       return true;
+                               }
+                       }
+               }
+               user = user->next;
        }
+       return false;
+}
 
-       client_socket_addr(sconn->sock, tmp_addr, sizeof(tmp_addr));
-       addr = talloc_strdup(cconn, tmp_addr);
-       if (addr == NULL) {
-               return NT_STATUS_NO_MEMORY;
+static bool sid_in_use(const struct user_struct *user,
+                      const struct dom_sid *psid)
+{
+       while (user) {
+               struct security_token *tok;
+
+               if (user->session_info == NULL) {
+                       continue;
+               }
+               tok = user->session_info->security_token;
+               if (tok == NULL) {
+                       /*
+                        * Not sure session_info->security_token can
+                        * ever be NULL. This check might be not
+                        * necessary.
+                        */
+                       continue;
+               }
+               if (security_token_has_sid(tok, psid)) {
+                       return true;
+               }
+               user = user->next;
        }
-       return ctdbd_register_ips(cconn, srv, clnt, release_ip, addr);
+       return false;
 }
 
-#endif
+static bool id_in_use(const struct user_struct *user,
+                     const struct id_cache_ref *id)
+{
+       switch(id->type) {
+       case UID:
+               return uid_in_use(user, id->id.uid);
+       case GID:
+               return gid_in_use(user, id->id.gid);
+       case SID:
+               return sid_in_use(user, &id->id.sid);
+       default:
+               break;
+       }
+       return false;
+}
+
+static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
+                              void *private_data,
+                              uint32_t msg_type,
+                              struct server_id server_id,
+                              DATA_BLOB* data)
+{
+       const char *msg = (data && data->data)
+               ? (const char *)data->data : "<NULL>";
+       struct id_cache_ref id;
+       struct smbd_server_connection *sconn =
+               talloc_get_type_abort(private_data,
+               struct smbd_server_connection);
+
+       if (!id_cache_ref_parse(msg, &id)) {
+               DEBUG(0, ("Invalid ?ID: %s\n", msg));
+               return;
+       }
+
+       if (id_in_use(sconn->users, &id)) {
+               exit_server_cleanly(msg);
+       }
+       id_cache_delete_from_cache(&id);
+}
+
+NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
+                                       enum protocol_types protocol)
+{
+       NTSTATUS status;
+
+       set_Protocol(protocol);
+       conn->protocol = protocol;
+
+       if (protocol >= PROTOCOL_SMB2_02) {
+               status = smb2srv_session_table_init(conn);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+
+               status = smb2srv_open_table_init(conn);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+       } else {
+               status = smb1srv_session_table_init(conn);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+
+               status = smb1srv_tcon_table_init(conn);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+
+               status = smb1srv_open_table_init(conn);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+       }
+
+       return NT_STATUS_OK;
+}
+
+static void smbd_tevent_trace_callback(enum tevent_trace_point point,
+                                      void *private_data)
+{
+       struct smbXsrv_connection *conn =
+               talloc_get_type_abort(private_data,
+               struct smbXsrv_connection);
+
+       switch (point) {
+       case TEVENT_TRACE_BEFORE_WAIT:
+               /*
+                * This just removes compiler warning
+                * without profile support
+                */
+               conn->smbd_idle_profstamp = 0;
+               START_PROFILE_STAMP(smbd_idle, conn->smbd_idle_profstamp);
+               break;
+       case TEVENT_TRACE_AFTER_WAIT:
+               END_PROFILE_STAMP(smbd_idle, conn->smbd_idle_profstamp);
+               break;
+       }
+}
 
 /****************************************************************************
  Process commands from the client
 ****************************************************************************/
 
-void smbd_process(struct smbd_server_connection *sconn)
+void smbd_process(struct tevent_context *ev_ctx,
+                 struct messaging_context *msg_ctx,
+                 int sock_fd,
+                 bool interactive)
 {
        TALLOC_CTX *frame = talloc_stackframe();
+       struct smbXsrv_connection *conn;
+       struct smbd_server_connection *sconn;
        struct sockaddr_storage ss;
        struct sockaddr *sa = NULL;
        socklen_t sa_socklen;
        struct tsocket_address *local_address = NULL;
        struct tsocket_address *remote_address = NULL;
+       const char *locaddr = NULL;
        const char *remaddr = NULL;
+       char *rhost;
        int ret;
 
-       if (lp_maxprotocol() == PROTOCOL_SMB2) {
+       conn = talloc_zero(ev_ctx, struct smbXsrv_connection);
+       if (conn == NULL) {
+               DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
+               exit_server_cleanly("talloc_zero(struct smbXsrv_connection).\n");
+       }
+
+       conn->ev_ctx = ev_ctx;
+       conn->msg_ctx = msg_ctx;
+
+       sconn = talloc_zero(conn, struct smbd_server_connection);
+       if (!sconn) {
+               exit_server("failed to create smbd_server_connection");
+       }
+
+       conn->sconn = sconn;
+       sconn->conn = conn;
+
+       /*
+        * TODO: remove this...:-)
+        */
+       global_smbXsrv_connection = conn;
+
+       sconn->ev_ctx = ev_ctx;
+       sconn->msg_ctx = msg_ctx;
+       sconn->sock = sock_fd;
+       sconn->smb1.echo_handler.trusted_fd = -1;
+       sconn->smb1.echo_handler.socket_lock_fd = -1;
+
+       if (!interactive) {
+               smbd_setup_sig_term_handler(sconn);
+               smbd_setup_sig_hup_handler(sconn);
+
+               if (!serverid_register(messaging_server_id(msg_ctx),
+                                      FLAG_MSG_GENERAL|FLAG_MSG_SMBD
+                                      |FLAG_MSG_DBWRAP
+                                      |FLAG_MSG_PRINT_GENERAL)) {
+                       exit_server_cleanly("Could not register myself in "
+                                           "serverid.tdb");
+               }
+       }
+
+       if (lp_srv_maxprotocol() >= PROTOCOL_SMB2_02) {
                /*
                 * We're not making the decision here,
                 * we're just allowing the client
@@ -2923,12 +3393,27 @@ void smbd_process(struct smbd_server_connection *sconn)
        sconn->local_address = local_address;
        sconn->remote_address = remote_address;
 
+       if (tsocket_address_is_inet(local_address, "ip")) {
+               locaddr = tsocket_address_inet_addr_string(
+                               sconn->local_address,
+                               talloc_tos());
+               if (locaddr == NULL) {
+                       DEBUG(0,("%s: tsocket_address_inet_addr_string local failed - %s\n",
+                                __location__, strerror(errno)));
+                       exit_server_cleanly("tsocket_address_inet_addr_string local failed.\n");
+               }
+       } else {
+               locaddr = "0.0.0.0";
+       }
+
        if (tsocket_address_is_inet(remote_address, "ip")) {
                remaddr = tsocket_address_inet_addr_string(
                                sconn->remote_address,
                                talloc_tos());
                if (remaddr == NULL) {
-
+                       DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
+                                __location__, strerror(errno)));
+                       exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
                }
        } else {
                remaddr = "0.0.0.0";
@@ -2937,7 +3422,7 @@ void smbd_process(struct smbd_server_connection *sconn)
        /* this is needed so that we get decent entries
           in smbstatus for port 445 connects */
        set_remote_machine_name(remaddr, false);
-       reload_services(sconn->msg_ctx, sconn->sock, true);
+       reload_services(sconn, conn_snum_used, true);
 
        /*
         * Before the first packet, check the global hosts allow/ hosts deny
@@ -2946,9 +3431,26 @@ void smbd_process(struct smbd_server_connection *sconn)
         * the hosts allow list.
         */
 
+       ret = get_remote_hostname(remote_address,
+                                 &rhost,
+                                 talloc_tos());
+       if (ret < 0) {
+               DEBUG(0,("%s: get_remote_hostname failed - %s\n",
+                       __location__, strerror(errno)));
+               exit_server_cleanly("get_remote_hostname failed.\n");
+       }
+       if (strequal(rhost, "UNKNOWN")) {
+               rhost = talloc_strdup(talloc_tos(), remaddr);
+       }
+       sconn->remote_hostname = talloc_move(sconn, &rhost);
+
+       sub_set_socket_ids(remaddr,
+                          sconn->remote_hostname,
+                          locaddr);
+
        if (!allow_access(lp_hostsdeny(-1), lp_hostsallow(-1),
-                         sconn->client_id.name,
-                         sconn->client_id.addr)) {
+                         sconn->remote_hostname,
+                         remaddr)) {
                /*
                 * send a negative session response "not listening on calling
                 * name"
@@ -2966,7 +3468,9 @@ void smbd_process(struct smbd_server_connection *sconn)
                   tsocket_address_string(remote_address, talloc_tos()),
                   tsocket_address_string(local_address, talloc_tos())));
 
-       init_modules();
+       if (lp_preload_modules()) {
+               smb_load_modules(lp_preload_modules());
+       }
 
        smb_perfcount_init();
 
@@ -2974,33 +3478,48 @@ void smbd_process(struct smbd_server_connection *sconn)
                exit_server("Could not open account policy tdb.\n");
        }
 
-       if (*lp_rootdir()) {
-               if (chroot(lp_rootdir()) != 0) {
-                       DEBUG(0,("Failed to change root to %s\n", lp_rootdir()));
+       if (*lp_rootdir(talloc_tos())) {
+               if (chroot(lp_rootdir(talloc_tos())) != 0) {
+                       DEBUG(0,("Failed to change root to %s\n",
+                                lp_rootdir(talloc_tos())));
                        exit_server("Failed to chroot()");
                }
                if (chdir("/") == -1) {
-                       DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir()));
+                       DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir(talloc_tos())));
                        exit_server("Failed to chroot()");
                }
-               DEBUG(0,("Changed root to %s\n", lp_rootdir()));
+               DEBUG(0,("Changed root to %s\n", lp_rootdir(talloc_tos())));
        }
 
        if (!srv_init_signing(sconn)) {
                exit_server("Failed to init smb_signing");
        }
 
+       if (!file_init(sconn)) {
+               exit_server("file_init() failed");
+       }
+
        /* Setup oplocks */
-       if (!init_oplocks(sconn->msg_ctx))
+       if (!init_oplocks(sconn))
                exit_server("Failed to init oplocks");
 
        /* register our message handlers */
-       messaging_register(sconn->msg_ctx, NULL,
+       messaging_register(sconn->msg_ctx, sconn,
                           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);
+       messaging_register(sconn->msg_ctx, sconn,
+                          MSG_SMB_FILE_RENAME, msg_file_was_renamed);
+
+       id_cache_register_msgs(sconn->msg_ctx);
+       messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
+       messaging_register(sconn->msg_ctx, sconn,
+                          ID_CACHE_KILL, smbd_id_cache_kill);
+
+       messaging_deregister(sconn->msg_ctx,
+                            MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
+       messaging_register(sconn->msg_ctx, sconn,
+                          MSG_SMB_CONF_UPDATED, smbd_conf_updated);
 
        /*
         * Use the default MSG_DEBUG handler to avoid rebroadcasting
@@ -3012,22 +3531,22 @@ 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(ev_ctx, NULL,
                                timeval_set(lp_keepalive(), 0),
                                "keepalive", keepalive_fn,
-                               NULL))) {
+                               sconn))) {
                DEBUG(0, ("Could not add keepalive event\n"));
                exit(1);
        }
 
-       if (!(event_add_idle(smbd_event_context(), NULL,
+       if (!(event_add_idle(ev_ctx, 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,
+       if (!(event_add_idle(ev_ctx, NULL,
                             timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
                             "housekeeping", housekeeping_fn, sconn))) {
                DEBUG(0, ("Could not add housekeeping event\n"));
@@ -3065,26 +3584,17 @@ void smbd_process(struct smbd_server_connection *sconn)
 
        sconn->nbt.got_session = false;
 
-       sconn->smb1.negprot.max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
+       sconn->smb1.negprot.max_recv = MIN(lp_max_xmit(),BUFFER_SIZE);
 
        sconn->smb1.sessions.done_sesssetup = false;
        sconn->smb1.sessions.max_send = BUFFER_SIZE;
        sconn->smb1.sessions.last_session_tag = UID_FIELD_INVALID;
-       /* users from session setup */
-       sconn->smb1.sessions.session_userlist = NULL;
-       /* workgroup from session setup. */
-       sconn->smb1.sessions.session_workgroup = NULL;
-       /* this holds info on user ids that are already validated for this VC */
-       sconn->smb1.sessions.validated_users = NULL;
-       sconn->smb1.sessions.next_vuid = VUID_OFFSET;
-       sconn->smb1.sessions.num_validated_vuids = 0;
-
-       conn_init(sconn);
+
        if (!init_dptrs(sconn)) {
                exit_server("init_dptrs() failed");
        }
 
-       sconn->smb1.fde = event_add_fd(smbd_event_context(),
+       sconn->smb1.fde = event_add_fd(ev_ctx,
                                                  sconn,
                                                  sconn->sock,
                                                  EVENT_FD_READ,
@@ -3094,21 +3604,25 @@ void smbd_process(struct smbd_server_connection *sconn)
                exit_server("failed to create smbd_server_connection fde");
        }
 
+       sconn->conn->local_address = sconn->local_address;
+       sconn->conn->remote_address = sconn->remote_address;
+       sconn->conn->remote_hostname = sconn->remote_hostname;
+       sconn->conn->protocol = PROTOCOL_NONE;
+
        TALLOC_FREE(frame);
 
-       while (True) {
-               NTSTATUS status;
+       tevent_set_trace_callback(ev_ctx, smbd_tevent_trace_callback, conn);
 
+       while (True) {
                frame = talloc_stackframe_pool(8192);
 
                errno = 0;
-
-               status = smbd_server_connection_loop_once(sconn);
-               if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY) &&
-                   !NT_STATUS_IS_OK(status)) {
-                       DEBUG(3, ("smbd_server_connection_loop_once failed: %s,"
-                                 " exiting\n", nt_errstr(status)));
-                       break;
+               if (tevent_loop_once(ev_ctx) == -1) {
+                       if (errno != EINTR) {
+                               DEBUG(3, ("tevent_loop_once failed: %s,"
+                                         " exiting\n", strerror(errno) ));
+                               break;
+                       }
                }
 
                TALLOC_FREE(frame);
@@ -3119,7 +3633,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