Fix chain_reply for pipe reads
[metze/samba/wip.git] / source3 / smbd / process.c
index 03216a0700154582bcc0ad75b59da5ea1292ad44..a025bb4197d2faff0c00ca21ffe4953702466a75 100644 (file)
 */
 
 #include "includes.h"
+#include "smbd/globals.h"
 
-extern int smb_echo_count;
-
-/*
- * Size of data we can send to client. Set
- *  by the client for all protocols above CORE.
- *  Set by us for CORE protocol.
- */
-int max_send = BUFFER_SIZE;
-/*
- * Size of the data we can receive. Set by us.
- * Can be modified by the max xmit parameter.
- */
-int max_recv = BUFFER_SIZE;
-
-SIG_ATOMIC_T reload_after_sighup = 0;
-SIG_ATOMIC_T got_sig_term = 0;
 extern bool global_machine_password_needs_changing;
-extern int max_send;
+
+static void construct_reply_common(struct smb_request *req, const char *inbuf,
+                                  char *outbuf);
 
 /* Accessor function for smb_read_error for smbd functions. */
 
@@ -105,7 +92,11 @@ static bool valid_smb_header(const uint8_t *inbuf)
        if (is_encrypted_packet(inbuf)) {
                return true;
        }
-       return (strncmp(smb_base(inbuf),"\377SMB",4) == 0);
+       /*
+        * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
+        * but it just looks weird to call strncmp for this one.
+        */
+       return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
 }
 
 /* Socket functions for smbd packet processing. */
@@ -120,9 +111,7 @@ static bool valid_packet_size(size_t len)
        if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
                DEBUG(0,("Invalid packet length! (%lu bytes).\n",
                                        (unsigned long)len));
-               if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
-                       return false;
-               }
+               return false;
        }
        return true;
 }
@@ -166,7 +155,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
        ssize_t toread;
        NTSTATUS status;
 
-       memcpy(writeX_header, lenbuf, sizeof(lenbuf));
+       memcpy(writeX_header, lenbuf, 4);
 
        status = read_socket_with_timeout(
                fd, writeX_header + 4,
@@ -252,6 +241,8 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
                        timeout, toread);
 
                if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(10, ("receive_smb_raw_talloc_partial_read: %s\n",
+                                  nt_errstr(status)));
                        return status;
                }
        }
@@ -279,17 +270,11 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
 
        if (CVAL(lenbuf,0) == 0 &&
                        min_recv_size &&
-                       smb_len_large(lenbuf) > min_recv_size && /* Could be a UNIX large writeX. */
+                       smb_len_large(lenbuf) > (min_recv_size + STANDARD_WRITE_AND_X_HEADER_SIZE) && /* Could be a UNIX large writeX. */
                        !srv_is_signing_active()) {
 
-               status = receive_smb_raw_talloc_partial_read(
-                       mem_ctx, lenbuf, fd, buffer, timeout, p_unread, &len);
-
-               if (!NT_STATUS_IS_OK(status)) {
-                       DEBUG(10, ("receive_smb_raw: %s\n",
-                                  nt_errstr(status)));
-                       return status;
-               }
+               return receive_smb_raw_talloc_partial_read(
+                       mem_ctx, lenbuf, fd, buffer, timeout, p_unread, plen);
        }
 
        if (!valid_packet_size(len)) {
@@ -373,15 +358,21 @@ void init_smb_request(struct smb_request *req,
                        (unsigned int)req_size ));
                exit_server_cleanly("Invalid SMB request");
        }
+       req->cmd    = CVAL(inbuf, smb_com);
        req->flags2 = SVAL(inbuf, smb_flg2);
        req->smbpid = SVAL(inbuf, smb_pid);
        req->mid    = SVAL(inbuf, smb_mid);
        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->buflen = smb_buflen(inbuf);
+       req->buf    = (const uint8_t *)smb_buf(inbuf);
        req->unread_bytes = unread_bytes;
        req->encrypted = encrypted;
        req->conn = conn_find(req->tid);
+       req->chain_fsp = NULL;
+       req->chain_outbuf = NULL;
 
        /* Ensure we have at least wct words and 2 bytes of bcc. */
        if (smb_size + req->wct*2 > req_size) {
@@ -391,24 +382,47 @@ void init_smb_request(struct smb_request *req,
                exit_server_cleanly("Invalid SMB request");
        }
        /* Ensure bcc is correct. */
-       if (((uint8 *)smb_buf(inbuf)) + smb_buflen(inbuf) > inbuf + req_size) {
+       if (((uint8 *)smb_buf(inbuf)) + req->buflen > inbuf + req_size) {
                DEBUG(0,("init_smb_request: invalid bcc number %u "
                        "(wct = %u, size %u)\n",
-                       (unsigned int)smb_buflen(inbuf),
+                       (unsigned int)req->buflen,
                        (unsigned int)req->wct,
                        (unsigned int)req_size));
                exit_server_cleanly("Invalid SMB request");
        }
-       req->inbuf  = inbuf;
        req->outbuf = NULL;
 }
 
-/****************************************************************************
- structure to hold a linked list of queued messages.
- for processing.
-****************************************************************************/
+static void process_smb(struct smbd_server_connection *conn,
+                       uint8_t *inbuf, size_t nread, size_t unread_bytes,
+                       bool encrypted);
 
-static struct pending_message_list *deferred_open_queue;
+static void smbd_deferred_open_timer(struct event_context *ev,
+                                    struct timed_event *te,
+                                    struct timeval _tval,
+                                    void *private_data)
+{
+       struct pending_message_list *msg = talloc_get_type(private_data,
+                                          struct pending_message_list);
+       TALLOC_CTX *mem_ctx = talloc_tos();
+       uint8_t *inbuf;
+
+       inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
+                                        msg->buf.length);
+       if (inbuf == NULL) {
+               exit_server("smbd_deferred_open_timer: talloc failed\n");
+               return;
+       }
+
+       /* We leave this message on the queue so the open code can
+          know this is a retry. */
+       DEBUG(5,("smbd_deferred_open_timer: trigger mid %u.\n",
+               (unsigned int)SVAL(msg->buf.data,smb_mid)));
+
+       process_smb(smbd_server_conn, inbuf,
+                   msg->buf.length, 0,
+                   msg->encrypted);
+}
 
 /****************************************************************************
  Function to push a message onto the tail of a linked list of smb messages ready
@@ -438,7 +452,6 @@ static bool push_queued_message(struct smb_request *req,
        }
 
        msg->request_time = request_time;
-       msg->end_time = end_time;
        msg->encrypted = req->encrypted;
 
        if (private_data) {
@@ -451,6 +464,17 @@ 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);
+       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 *);
 
        DEBUG(10,("push_message: pushed message length %u on "
@@ -492,13 +516,29 @@ void schedule_deferred_open_smb_message(uint16 mid)
 
        for (pml = deferred_open_queue; pml; pml = pml->next) {
                uint16 msg_mid = SVAL(pml->buf.data,smb_mid);
+
                DEBUG(10,("schedule_deferred_open_smb_message: [%d] msg_mid = %u\n", i++,
                        (unsigned int)msg_mid ));
+
                if (mid == msg_mid) {
+                       struct timed_event *te;
+
                        DEBUG(10,("schedule_deferred_open_smb_message: scheduling mid %u\n",
                                mid ));
-                       pml->end_time.tv_sec = 0;
-                       pml->end_time.tv_usec = 0;
+
+                       te = event_add_timed(smbd_event_context(),
+                                            pml,
+                                            timeval_zero(),
+                                            smbd_deferred_open_timer,
+                                            pml);
+                       if (!te) {
+                               DEBUG(10,("schedule_deferred_open_smb_message: "
+                                         "event_add_timed() failed, skipping mid %u\n",
+                                         mid ));
+                       }
+
+                       TALLOC_FREE(pml->te);
+                       pml->te = te;
                        DLIST_PROMOTE(deferred_open_queue, pml);
                        return;
                }
@@ -580,26 +620,33 @@ struct idle_event {
        void *private_data;
 };
 
-static void idle_event_handler(struct event_context *ctx,
-                              struct timed_event *te,
-                              const struct timeval *now,
-                              void *private_data)
+static void smbd_idle_event_handler(struct event_context *ctx,
+                                   struct timed_event *te,
+                                   struct timeval now,
+                                   void *private_data)
 {
        struct idle_event *event =
                talloc_get_type_abort(private_data, struct idle_event);
 
        TALLOC_FREE(event->te);
 
-       if (!event->handler(now, event->private_data)) {
+       DEBUG(10,("smbd_idle_event_handler: %s %p called\n",
+                 event->name, event->te));
+
+       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;
        }
 
+       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),
-                                   event->name,
-                                   idle_event_handler, event);
+                                   timeval_sum(&now, &event->interval),
+                                   smbd_idle_event_handler, event);
 
        /* We can't do much but fail here. */
        SMB_ASSERT(event->te != NULL);
@@ -634,14 +681,14 @@ struct idle_event *event_add_idle(struct event_context *event_ctx,
 
        result->te = event_add_timed(event_ctx, result,
                                     timeval_sum(&now, &interval),
-                                    result->name,
-                                    idle_event_handler, result);
+                                    smbd_idle_event_handler, result);
        if (result->te == NULL) {
                DEBUG(0, ("event_add_timed failed\n"));
                TALLOC_FREE(result);
                return NULL;
        }
 
+       DEBUG(10,("event_add_idle: %s %p\n", result->name, result->te));
        return result;
 }
 
@@ -650,13 +697,13 @@ struct idle_event *event_add_idle(struct event_context *event_ctx,
  notify events etc.
 ****************************************************************************/
 
-static void async_processing(fd_set *pfds)
+static void async_processing(void)
 {
        DEBUG(10,("async_processing: Doing async processing.\n"));
 
        process_aio_queue();
 
-       process_kernel_oplocks(smbd_messaging_context(), pfds);
+       process_kernel_oplocks(smbd_messaging_context());
 
        /* Do the aio check again after receive_local_message as it does a
           select and may have eaten our signal. */
@@ -676,20 +723,6 @@ static void async_processing(fd_set *pfds)
        }
 }
 
-/****************************************************************************
- Add a fd to the set we will be select(2)ing on.
-****************************************************************************/
-
-static int select_on_fd(int fd, int maxfd, fd_set *fds)
-{
-       if (fd != -1) {
-               FD_SET(fd, fds);
-               maxfd = MAX(maxfd, fd);
-       }
-
-       return maxfd;
-}
-
 /****************************************************************************
   Do a select on an two fd's - with timeout. 
 
@@ -711,82 +744,15 @@ static int select_on_fd(int fd, int maxfd, fd_set *fds)
 The timeout is in milliseconds
 ****************************************************************************/
 
-static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
-                                      size_t *buffer_len, int timeout,
-                                      size_t *p_unread, bool *p_encrypted)
+static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *conn)
 {
        fd_set r_fds, w_fds;
        int selrtn;
        struct timeval to;
        int maxfd = 0;
-       size_t len = 0;
-       NTSTATUS status;
-
-       *p_unread = 0;
-
- again:
-
-       if (timeout >= 0) {
-               to.tv_sec = timeout / 1000;
-               to.tv_usec = (timeout % 1000) * 1000;
-       } else {
-               to.tv_sec = SMBD_SELECT_TIMEOUT;
-               to.tv_usec = 0;
-       }
-
-       /*
-        * Note that this call must be before processing any SMB
-        * messages as we need to synchronously process any messages
-        * we may have sent to ourselves from the previous SMB.
-        */
-       message_dispatch(smbd_messaging_context());
 
-       /*
-        * Check to see if we already have a message on the deferred open queue
-        * and it's time to schedule.
-        */
-       if(deferred_open_queue != NULL) {
-               bool pop_message = False;
-               struct pending_message_list *msg = deferred_open_queue;
-
-               if (timeval_is_zero(&msg->end_time)) {
-                       pop_message = True;
-               } else {
-                       struct timeval tv;
-                       SMB_BIG_INT tdif;
-
-                       GetTimeOfDay(&tv);
-                       tdif = usec_time_diff(&msg->end_time, &tv);
-                       if (tdif <= 0) {
-                               /* Timed out. Schedule...*/
-                               pop_message = True;
-                               DEBUG(10,("receive_message_or_smb: queued message timed out.\n"));
-                       } else {
-                               /* Make a more accurate select timeout. */
-                               to.tv_sec = tdif / 1000000;
-                               to.tv_usec = tdif % 1000000;
-                               DEBUG(10,("receive_message_or_smb: select with timeout of [%u.%06u]\n",
-                                       (unsigned int)to.tv_sec, (unsigned int)to.tv_usec ));
-                       }
-               }
-
-               if (pop_message) {
-
-                       *buffer = (char *)talloc_memdup(mem_ctx, msg->buf.data,
-                                                       msg->buf.length);
-                       if (*buffer == NULL) {
-                               DEBUG(0, ("talloc failed\n"));
-                               return NT_STATUS_NO_MEMORY;
-                       }
-                       *buffer_len = msg->buf.length;
-                       *p_encrypted = msg->encrypted;
-
-                       /* We leave this message on the queue so the open code can
-                          know this is a retry. */
-                       DEBUG(5,("receive_message_or_smb: returning deferred open smb message.\n"));
-                       return NT_STATUS_OK;
-               }
-       }
+       to.tv_sec = SMBD_SELECT_TIMEOUT;
+       to.tv_usec = 0;
 
        /*
         * Setup the select fd sets.
@@ -804,15 +770,15 @@ static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
         * This is hideously complex - *MUST* be simplified for 3.0 ! JRA.
         */
 
-       if (oplock_message_waiting(&r_fds)) {
+       if (oplock_message_waiting()) {
                DEBUG(10,("receive_message_or_smb: oplock_message is waiting.\n"));
-               async_processing(&r_fds);
+               async_processing();
                /*
                 * After async processing we must go and do the select again, as
                 * the state of the flag in fds for the server file descriptor is
                 * indeterminate - we may have done I/O on it in the oplock processing. JRA.
                 */
-               goto again;
+               return NT_STATUS_RETRY;
        }
 
        /*
@@ -828,20 +794,15 @@ static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
                                         &r_fds, &w_fds, &to, &maxfd);
        }
 
-       if (timeval_is_zero(&to)) {
-               /* Process a timed event now... */
-               if (run_events(smbd_event_context(), 0, NULL, NULL)) {
-                       goto again;
-               }
+       /* Process a signal and timed events now... */
+       if (run_events(smbd_event_context(), 0, NULL, NULL)) {
+               return NT_STATUS_RETRY;
        }
-       
+
        {
                int sav;
                START_PROFILE(smbd_idle);
 
-               maxfd = select_on_fd(smbd_server_fd(), maxfd, &r_fds);
-               maxfd = select_on_fd(oplock_notify_fd(), maxfd, &r_fds);
-
                selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&to);
                sav = errno;
 
@@ -850,69 +811,36 @@ static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
        }
 
        if (run_events(smbd_event_context(), selrtn, &r_fds, &w_fds)) {
-               goto again;
+               return NT_STATUS_RETRY;
        }
 
-       /*
-        * We've just woken up from a protentially long select sleep.
-        * Ensure we process local messages as we need to synchronously
-        * process any messages from other smbd's to avoid file rename race
-        * conditions. This call is cheap if there are no messages waiting.
-        * JRA.
-        */
-       message_dispatch(smbd_messaging_context());
-
        /* if we get EINTR then maybe we have received an oplock
           signal - treat this as select returning 1. This is ugly, but
           is the best we can do until the oplock code knows more about
           signals */
        if (selrtn == -1 && errno == EINTR) {
-               async_processing(&r_fds);
+               async_processing();
                /*
                 * After async processing we must go and do the select again, as
                 * the state of the flag in fds for the server file descriptor is
                 * indeterminate - we may have done I/O on it in the oplock processing. JRA.
                 */
-               goto again;
+               return NT_STATUS_RETRY;
        }
 
        /* Check if error */
        if (selrtn == -1) {
                /* something is wrong. Maybe the socket is dead? */
                return map_nt_error_from_unix(errno);
-       } 
-    
-       /* Did we timeout ? */
-       if (selrtn == 0) {
-               return NT_STATUS_IO_TIMEOUT;
        }
 
-       /*
-        * Ensure we process oplock break messages by preference.
-        * This is IMPORTANT ! Otherwise we can starve other processes
-        * sending us an oplock break message. JRA.
-        */
-
-       if (oplock_message_waiting(&r_fds)) {
-               async_processing(&r_fds);
-               /*
-                * After async processing we must go and do the select again, as
-                * the state of the flag in fds for the server file descriptor is
-                * indeterminate - we may have done I/O on it in the oplock processing. JRA.
-                */
-               goto again;
-       }
-
-       status = receive_smb_talloc(mem_ctx, smbd_server_fd(), buffer, 0,
-                                   p_unread, p_encrypted, &len);
-
-       if (!NT_STATUS_IS_OK(status)) {
-               return status;
+       /* Did we timeout ? */
+       if (selrtn == 0) {
+               return NT_STATUS_RETRY;
        }
 
-       *buffer_len = len;
-
-       return NT_STATUS_OK;
+       /* should not be reached */
+       return NT_STATUS_INTERNAL_ERROR;
 }
 
 /*
@@ -957,7 +885,7 @@ void respond_to_all_remaining_local_messages(void)
                return;
        }
 
-       process_kernel_oplocks(smbd_messaging_context(), NULL);
+       process_kernel_oplocks(smbd_messaging_context());
 
        return;
 }
@@ -984,7 +912,7 @@ force write permissions on print services.
 */
 static const struct smb_message_struct {
        const char *name;
-       void (*fn_new)(struct smb_request *req);
+       void (*fn)(struct smb_request *req);
        int flags;
 } smb_messages[256] = {
 
@@ -1251,7 +1179,9 @@ static const struct smb_message_struct {
  allocate and initialize a reply packet
 ********************************************************************/
 
-void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
+static bool create_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
+                         const char *inbuf, char **outbuf, uint8_t num_words,
+                         uint32_t num_bytes)
 {
        /*
          * Protect against integer wrap
@@ -1259,28 +1189,40 @@ void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
        if ((num_bytes > 0xffffff)
            || ((num_bytes + smb_size + num_words*2) > 0xffffff)) {
                char *msg;
-               asprintf(&msg, "num_bytes too large: %u",
-                        (unsigned)num_bytes);
+               if (asprintf(&msg, "num_bytes too large: %u",
+                            (unsigned)num_bytes) == -1) {
+                       msg = CONST_DISCARD(char *, "num_bytes too large");
+               }
                smb_panic(msg);
        }
 
-       if (!(req->outbuf = TALLOC_ARRAY(
-                     req, uint8,
-                     smb_size + num_words*2 + num_bytes))) {
-               smb_panic("could not allocate output buffer\n");
+       *outbuf = TALLOC_ARRAY(mem_ctx, char,
+                              smb_size + num_words*2 + num_bytes);
+       if (*outbuf == NULL) {
+               return false;
        }
 
-       construct_reply_common((char *)req->inbuf, (char *)req->outbuf);
-       srv_set_message((char *)req->outbuf, num_words, num_bytes, false);
+       construct_reply_common(req, inbuf, *outbuf);
+       srv_set_message(*outbuf, num_words, num_bytes, false);
        /*
         * Zero out the word area, the caller has to take care of the bcc area
         * himself
         */
        if (num_words != 0) {
-               memset(req->outbuf + smb_vwv0, 0, num_words*2);
+               memset(*outbuf + smb_vwv0, 0, num_words*2);
        }
 
-       return;
+       return true;
+}
+
+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,
+                          num_bytes)) {
+               smb_panic("could not allocate output buffer\n");
+       }
+       req->outbuf = (uint8_t *)outbuf;
 }
 
 
@@ -1298,9 +1240,8 @@ static void smb_dump(const char *name, int type, const char *data, ssize_t len)
 
        if (len < 4) len = smb_len(data)+4;
        for (i=1;i<100;i++) {
-               asprintf(&fname, "/tmp/%s.%d.%s", name, i,
-                               type ? "req" : "resp");
-               if (!fname) {
+               if (asprintf(&fname, "/tmp/%s.%d.%s", name, i,
+                            type ? "req" : "resp") == -1) {
                        return;
                }
                fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
@@ -1335,8 +1276,6 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
        uint16 session_tag;
        connection_struct *conn = NULL;
 
-       static uint16 last_session_tag = UID_FIELD_INVALID;
-
        errno = 0;
 
        /* Make sure this is an SMB packet. smb_size contains NetBIOS header
@@ -1348,7 +1287,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                exit_server_cleanly("Non-SMB packet");
        }
 
-       if (smb_messages[type].fn_new == NULL) {
+       if (smb_messages[type].fn == NULL) {
                DEBUG(0,("Unknown message type %d!\n",type));
                smb_dump("Unknown", 1, (char *)req->inbuf, size);
                reply_unknown_new(req, type);
@@ -1386,7 +1325,11 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                if(session_tag != UID_FIELD_INVALID) {
                        vuser = get_valid_user_struct(session_tag);
                        if (vuser) {
-                               set_current_user_info(&vuser->user);
+                               set_current_user_info(
+                                       vuser->server_info->sanitized_username,
+                                       vuser->server_info->unix_name,
+                                       pdb_get_domain(vuser->server_info
+                                                      ->sam_account));
                        }
                }
        }
@@ -1410,6 +1353,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
 
                if (!change_to_user(conn,session_tag)) {
                        reply_nterror(req, NT_STATUS_DOS(ERRSRV, ERRbaduid));
+                       remove_deferred_open_smb_message(req->mid);
                        return conn;
                }
 
@@ -1438,8 +1382,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                        /* encrypted required from now on. */
                        conn->encrypt_level = Required;
                } else if (ENCRYPTION_REQUIRED(conn)) {
-                       uint8 com = CVAL(req->inbuf,smb_com);
-                       if (com != SMBtrans2 && com != SMBtranss2) {
+                       if (req->cmd != SMBtrans2 && req->cmd != SMBtranss2) {
                                exit_server_cleanly("encryption required "
                                        "on connection");
                                return conn;
@@ -1464,7 +1407,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                return conn;
        }
 
-       smb_messages[type].fn_new(req);
+       smb_messages[type].fn(req);
        return req->conn;
 }
 
@@ -1474,20 +1417,18 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
 
 static void construct_reply(char *inbuf, int size, size_t unread_bytes, bool encrypted)
 {
-       uint8 type = CVAL(inbuf,smb_com);
        connection_struct *conn;
        struct smb_request *req;
 
        chain_size = 0;
-       file_chain_reset();
-       reset_chain_p();
 
        if (!(req = talloc(talloc_tos(), struct smb_request))) {
                smb_panic("could not allocate smb_request");
        }
        init_smb_request(req, (uint8 *)inbuf, unread_bytes, encrypted);
+       req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
 
-       conn = switch_message(type, req, size);
+       conn = switch_message(req->cmd, req, size);
 
        if (req->unread_bytes) {
                /* writeX failed. drain socket. */
@@ -1521,32 +1462,14 @@ static void construct_reply(char *inbuf, int size, size_t unread_bytes, bool enc
  Process an smb from the client
 ****************************************************************************/
 
-static void process_smb(char *inbuf, size_t nread, size_t unread_bytes, bool encrypted)
+static void process_smb(struct smbd_server_connection *conn,
+                       uint8_t *inbuf, size_t nread, size_t unread_bytes,
+                       bool encrypted)
 {
-       static int trans_num;
        int msg_type = CVAL(inbuf,0);
 
        DO_PROFILE_INC(smb_count);
 
-       if (trans_num == 0) {
-               char addr[INET6_ADDRSTRLEN];
-
-               /* on the first packet, check the global hosts allow/ hosts
-               deny parameters before doing any parsing of the packet
-               passed to us by the client.  This prevents attacks on our
-               parsing code from hosts not in the hosts allow list */
-
-               if (!check_access(smbd_server_fd(), lp_hostsallow(-1),
-                                 lp_hostsdeny(-1))) {
-                       /* send a negative session response "not listening on calling name" */
-                       static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
-                       DEBUG( 1, ( "Connection denied from %s\n",
-                               client_addr(get_client_fd(),addr,sizeof(addr)) ) );
-                       (void)srv_send_smb(smbd_server_fd(),(char *)buf,false);
-                       exit_server_cleanly("connection denied");
-               }
-       }
-
        DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
                    smb_len(inbuf) ) );
        DEBUG( 3, ( "Transaction %d of length %d (%u toread)\n", trans_num,
@@ -1557,15 +1480,31 @@ static void process_smb(char *inbuf, size_t nread, size_t unread_bytes, bool enc
                /*
                 * NetBIOS session request, keepalive, etc.
                 */
-               reply_special(inbuf);
-               return;
+               reply_special((char *)inbuf);
+               goto done;
        }
 
-       show_msg(inbuf);
+       show_msg((char *)inbuf);
 
-       construct_reply(inbuf,nread,unread_bytes,encrypted);
+       construct_reply((char *)inbuf,nread,unread_bytes,encrypted);
 
        trans_num++;
+
+done:
+       conn->num_requests++;
+
+       /* The timeout_processing function isn't run nearly
+          often enough to implement 'max log size' without
+          overrunning the size of the file by many megabytes.
+          This is especially true if we are running at debug
+          level 10.  Checking every 50 SMBs is a nice
+          tradeoff of performance vs log file size overrun. */
+
+       if ((conn->num_requests % 50) == 0 &&
+           need_to_check_log_size()) {
+               change_to_root_user();
+               check_log_size();
+       }
 }
 
 /****************************************************************************
@@ -1586,8 +1525,6 @@ const char *smb_fn_name(int type)
  Helper functions for contruct_reply.
 ****************************************************************************/
 
-static uint32 common_flags2 = FLAGS2_LONG_PATH_COMPONENTS|FLAGS2_32_BIT_ERROR_CODES;
-
 void add_to_common_flags2(uint32 v)
 {
        common_flags2 |= v;
@@ -1598,11 +1535,12 @@ void remove_from_common_flags2(uint32 v)
        common_flags2 &= ~v;
 }
 
-void construct_reply_common(const char *inbuf, char *outbuf)
+static void construct_reply_common(struct smb_request *req, const char *inbuf,
+                                  char *outbuf)
 {
        srv_set_message(outbuf,0,0,false);
        
-       SCVAL(outbuf,smb_com,CVAL(inbuf,smb_com));
+       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,
@@ -1616,221 +1554,252 @@ void construct_reply_common(const char *inbuf, char *outbuf)
        SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
 }
 
+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 a chained reply and add it to the already made reply
 ****************************************************************************/
 
 void chain_reply(struct smb_request *req)
 {
-       static char *orig_inbuf;
+       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 */
 
-       /*
-        * Dirty little const_discard: We mess with req->inbuf, which is
-        * declared as const. If maybe at some point this routine gets
-        * rewritten, this const_discard could go away.
-        */
-       char *inbuf = CONST_DISCARD(char *, req->inbuf);
-       int size = smb_len(req->inbuf)+4;
-
-       int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
-       unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
-       char *inbuf2;
-       int outsize2;
-       int new_size;
-       char inbuf_saved[smb_wct];
-       char *outbuf = (char *)req->outbuf;
-       size_t outsize = smb_len(outbuf) + 4;
-       size_t outsize_padded;
-       size_t ofs, to_move;
-
-       struct smb_request *req2;
-       size_t caller_outputlen;
-       char *caller_output;
-
-       /* Maybe its not chained, or it's an error packet. */
-       if (smb_com2 == 0xFF || SVAL(outbuf,smb_rcls) != 0) {
-               SCVAL(outbuf,smb_vwv0,0xFF);
-               return;
-       }
+       uint8_t wct;
+       uint16_t *vwv;
+       uint16_t buflen;
+       uint8_t *buf;
 
-       if (chain_size == 0) {
-               /* this is the first part of the chain */
-               orig_inbuf = inbuf;
+       if (IVAL(req->outbuf, smb_rcls) != 0) {
+               fixup_chain_error_packet(req);
        }
 
        /*
-        * We need to save the output the caller added to the chain so that we
-        * can splice it into the final output buffer later.
+        * 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.
         */
 
-       caller_outputlen = outsize - smb_wct;
-
-       caller_output = (char *)memdup(outbuf + smb_wct, caller_outputlen);
-
-       if (caller_output == NULL) {
-               /* TODO: NT_STATUS_NO_MEMORY */
-               smb_panic("could not dup outbuf");
+       if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
+               goto error;
        }
 
        /*
-        * The original Win95 redirector dies on a reply to
-        * a lockingX and read chain unless the chain reply is
-        * 4 byte aligned. JRA.
+        * 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.
         */
 
-       outsize_padded = (outsize + 3) & ~3;
+       SCVAL(req->outbuf, smb_vwv0, 0xff);
+       SCVAL(req->outbuf, smb_vwv0+1, 0);
+       SSVAL(req->outbuf, smb_vwv1, 0);
 
-       /*
-        * remember how much the caller added to the chain, only counting
-        * stuff after the parameter words
-        */
-       chain_size += outsize_padded - smb_wct;
+       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).
+                */
+               req->chain_outbuf = TALLOC_REALLOC_ARRAY(
+                       req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
+               if (req->chain_outbuf == NULL) {
+                       goto error;
+               }
+               req->outbuf = NULL;
+       } else {
+               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;
+               }
+               TALLOC_FREE(req->outbuf);
+       }
 
        /*
-        * work out pointers into the original packets. The
-        * headers on these need to be filled in
+        * We use the old request's vwv field to grab the next chained command
+        * and offset into the chained fields.
         */
-       inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
 
-       /* remember the original command type */
-       smb_com1 = CVAL(orig_inbuf,smb_com);
+       chain_cmd = CVAL(req->vwv+0, 0);
+       chain_offset = SVAL(req->vwv+1, 0);
 
-       /* save the data which will be overwritten by the new headers */
-       memcpy(inbuf_saved,inbuf2,smb_wct);
-
-       /* give the new packet the same header as the last part of the SMB */
-       memmove(inbuf2,inbuf,smb_wct);
-
-       /* create the in buffer */
-       SCVAL(inbuf2,smb_com,smb_com2);
-
-       /* work out the new size for the in buffer. */
-       new_size = size - (inbuf2 - inbuf);
-       if (new_size < 0) {
-               DEBUG(0,("chain_reply: chain packet size incorrect "
-                        "(orig size = %d, offset = %d)\n",
-                        size, (int)(inbuf2 - inbuf) ));
-               exit_server_cleanly("Bad chained packet");
+       if (chain_cmd == 0xff) {
+               /*
+                * End of chain, no more requests from the client. So ship the
+                * replies.
+                */
+               smb_setlen((char *)(req->chain_outbuf),
+                          talloc_get_size(req->chain_outbuf) - 4);
+               if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
+                                 IS_CONN_ENCRYPTED(req->conn)
+                                 ||req->encrypted)) {
+                       exit_server_cleanly("chain_reply: srv_send_smb "
+                                           "failed.");
+               }
                return;
        }
 
-       /* And set it in the header. */
-       smb_setlen(inbuf2, new_size - 4);
-
-       DEBUG(3,("Chained message\n"));
-       show_msg(inbuf2);
-
-       if (!(req2 = talloc(talloc_tos(), struct smb_request))) {
-               smb_panic("could not allocate smb_request");
-       }
-       init_smb_request(req2, (uint8 *)inbuf2,0, req->encrypted);
-
-       /* process the request */
-       switch_message(smb_com2, req2, new_size);
-
        /*
-        * We don't accept deferred operations in chained requests.
+        * Check if the client tries to fool us. The request so far uses the
+        * space to the end of the byte buffer in the request just
+        * processed. The chain_offset can't point into that area. If that was
+        * the case, we could end up with an endless processing of the chain,
+        * we would always handle the same request.
         */
-       SMB_ASSERT(req2->outbuf != NULL);
-       outsize2 = smb_len(req2->outbuf)+4;
+
+       already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf));
+       if (chain_offset < already_used) {
+               goto error;
+       }
 
        /*
-        * Move away the new command output so that caller_output fits in,
-        * copy in the caller_output saved above.
+        * Next check: Make sure the chain offset does not point beyond the
+        * overall smb request length.
         */
 
-       SMB_ASSERT(outsize_padded >= smb_wct);
+       length_needed = chain_offset+1; /* wct */
+       if (length_needed > smblen) {
+               goto error;
+       }
 
        /*
-        * "ofs" is the space we need for caller_output. Equal to
-        * caller_outputlen plus the padding.
+        * 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.
         */
 
-       ofs = outsize_padded - smb_wct;
+       wct = CVAL(smb_base(req->inbuf), chain_offset);
 
        /*
-        * "to_move" is the amount of bytes the secondary routine gave us
+        * Next consistency check: Make the new vwv array fits in the overall
+        * smb request.
         */
 
-       to_move = outsize2 - smb_wct;
-
-       if (to_move + ofs + smb_wct + chain_size > max_send) {
-               smb_panic("replies too large -- would have to cut");
+       length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
+       if (length_needed > smblen) {
+               goto error;
        }
+       vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
 
        /*
-        * In the "new" API "outbuf" is allocated via reply_outbuf, just for
-        * the first request in the chain. So we have to re-allocate it. In
-        * the "old" API the only outbuf ever used is the global OutBuffer
-        * which is always large enough.
+        * Now grab the new byte buffer....
         */
 
-       outbuf = TALLOC_REALLOC_ARRAY(NULL, outbuf, char,
-                                     to_move + ofs + smb_wct);
-       if (outbuf == NULL) {
-               smb_panic("could not realloc outbuf");
-       }
-
-       req->outbuf = (uint8 *)outbuf;
-
-       memmove(outbuf + smb_wct + ofs, req2->outbuf + smb_wct, to_move);
-       memcpy(outbuf + smb_wct, caller_output, caller_outputlen);
+       buflen = SVAL(vwv+wct, 0);
 
        /*
-        * copy the new reply header over the old one but preserve the smb_com
-        * field
+        * .. and check that it fits.
         */
-       memmove(outbuf, req2->outbuf, smb_wct);
-       SCVAL(outbuf, smb_com, smb_com1);
 
-       /*
-        * We've just copied in the whole "wct" area from the secondary
-        * function. Fix up the chaining: com2 and the offset need to be
-        * readjusted.
-        */
+       length_needed += buflen;
+       if (length_needed > smblen) {
+               goto error;
+       }
+       buf = (uint8_t *)(vwv+wct+1);
 
-       SCVAL(outbuf, smb_vwv0, smb_com2);
-       SSVAL(outbuf, smb_vwv1, chain_size + smb_wct - 4);
+       req->cmd = chain_cmd;
+       req->wct = wct;
+       req->vwv = vwv;
+       req->buflen = buflen;
+       req->buf = buf;
 
-       if (outsize_padded > outsize) {
+       switch_message(chain_cmd, req, smblen);
 
+       if (req->outbuf == NULL) {
                /*
-                * Due to padding we have some uninitialized bytes after the
-                * caller's output
+                * This happens if the chained command has suspended itself or
+                * if it has called srv_send_smb() itself.
                 */
-
-               memset(outbuf + outsize, 0, outsize_padded - outsize);
+               return;
        }
 
-       smb_setlen(outbuf, outsize2 + chain_size - 4);
-
        /*
-        * restore the saved data, being careful not to overwrite any data
-        * from the reply header
+        * 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.
         */
-       memcpy(inbuf2,inbuf_saved,smb_wct);
+       goto done;
 
-       SAFE_FREE(caller_output);
-       TALLOC_FREE(req2);
-
-       return;
-}
+ error:
+       /*
+        * We end up here if there's any error in the chain syntax. Report a
+        * DOS error, just like Windows does.
+        */
+       reply_nterror(req, NT_STATUS_DOS(ERRSRV, ERRerror));
+       fixup_chain_error_packet(req);
 
-/****************************************************************************
- Setup the needed select timeout in milliseconds.
-****************************************************************************/
+ done:
+       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");
+       }
+       TALLOC_FREE(req->outbuf);
 
-static int setup_select_timeout(void)
-{
-       int select_timeout;
+       smb_setlen((char *)(req->chain_outbuf),
+                  talloc_get_size(req->chain_outbuf) - 4);
 
-       select_timeout = SMBD_SELECT_TIMEOUT*1000;
+       show_msg((char *)(req->chain_outbuf));
 
-       if (print_notify_messages_pending()) {
-               select_timeout = MIN(select_timeout, 1000);
+       if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
+                         IS_CONN_ENCRYPTED(req->conn)||req->encrypted)) {
+               exit_server_cleanly("construct_reply: srv_send_smb failed.");
        }
-
-       return select_timeout;
 }
 
 /****************************************************************************
@@ -1839,9 +1808,6 @@ static int setup_select_timeout(void)
 
 void check_reload(time_t t)
 {
-       static pid_t mypid = 0;
-       static time_t last_smb_conf_reload_time = 0;
-       static time_t last_printer_reload_time = 0;
        time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
 
        if(last_smb_conf_reload_time == 0) {
@@ -1886,97 +1852,55 @@ void check_reload(time_t t)
        }
 }
 
-/****************************************************************************
- Process any timeout housekeeping. Return False if the caller should exit.
-****************************************************************************/
-
-static void timeout_processing(int *select_timeout,
-                              time_t *last_timeout_processing_time)
+static void smbd_server_connection_write_handler(struct smbd_server_connection *conn)
 {
-       time_t t;
-
-       *last_timeout_processing_time = t = time(NULL);
-
-       /* become root again if waiting */
-       change_to_root_user();
-
-       /* check if we need to reload services */
-       check_reload(t);
-
-       if(global_machine_password_needs_changing && 
-                       /* for ADS we need to do a regular ADS password change, not a domain
-                                       password change */
-                       lp_security() == SEC_DOMAIN) {
-
-               unsigned char trust_passwd_hash[16];
-               time_t lct;
-               void *lock;
-
-               /*
-                * We're in domain level security, and the code that
-                * read the machine password flagged that the machine
-                * password needs changing.
-                */
-
-               /*
-                * First, open the machine password file with an exclusive lock.
-                */
-
-               lock = secrets_get_trust_account_lock(NULL, lp_workgroup());
-
-               if (lock == NULL) {
-                       DEBUG(0,("process: unable to lock the machine account password for \
-machine %s in domain %s.\n", global_myname(), lp_workgroup() ));
-                       return;
-               }
-
-               if(!secrets_fetch_trust_account_password(lp_workgroup(), trust_passwd_hash, &lct, NULL)) {
-                       DEBUG(0,("process: unable to read the machine account password for \
-machine %s in domain %s.\n", global_myname(), lp_workgroup()));
-                       TALLOC_FREE(lock);
-                       return;
-               }
+       /* TODO: make write nonblocking */
+}
 
-               /*
-                * Make sure someone else hasn't already done this.
-                */
+static void smbd_server_connection_read_handler(struct smbd_server_connection *conn)
+{
+       uint8_t *inbuf = NULL;
+       size_t inbuf_len = 0;
+       size_t unread_bytes = 0;
+       bool encrypted = false;
+       TALLOC_CTX *mem_ctx = talloc_tos();
+       NTSTATUS status;
 
-               if(t < lct + lp_machine_password_timeout()) {
-                       global_machine_password_needs_changing = False;
-                       TALLOC_FREE(lock);
-                       return;
-               }
+       /* TODO: make this completely nonblocking */
 
-               /* always just contact the PDC here */
-    
-               change_trust_account_password( lp_workgroup(), NULL);
-               global_machine_password_needs_changing = False;
-               TALLOC_FREE(lock);
+       status = receive_smb_talloc(mem_ctx, smbd_server_fd(),
+                                   (char **)(void *)&inbuf,
+                                   0, /* timeout */
+                                   &unread_bytes,
+                                   &encrypted,
+                                   &inbuf_len);
+       if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
+               goto process;
+       }
+       if (NT_STATUS_IS_ERR(status)) {
+               exit_server_cleanly("failed to receive smb request");
+       }
+       if (!NT_STATUS_IS_OK(status)) {
+               return;
        }
 
-       /* update printer queue caches if necessary */
-  
-       update_monitored_printq_cache();
-  
-       /*
-        * Now we are root, check if the log files need pruning.
-        * Force a log file check.
-        */
-       force_check_log_size();
-       check_log_size();
-
-       /* Send any queued printer notify message to interested smbd's. */
-
-       print_notify_send_messages(smbd_messaging_context(), 0);
-
-       /*
-        * Modify the select timeout depending upon
-        * what we have remaining in our queues.
-        */
+process:
+       process_smb(conn, inbuf, inbuf_len, unread_bytes, encrypted);
+}
 
-       *select_timeout = setup_select_timeout();
+static void smbd_server_connection_handler(struct event_context *ev,
+                                          struct fd_event *fde,
+                                          uint16_t flags,
+                                          void *private_data)
+{
+       struct smbd_server_connection *conn = talloc_get_type(private_data,
+                                             struct smbd_server_connection);
 
-       return;
+       if (flags & EVENT_FD_WRITE) {
+               smbd_server_connection_write_handler(conn);
+       } else if (flags & EVENT_FD_READ) {
+               smbd_server_connection_read_handler(conn);
+       }
 }
 
 /****************************************************************************
@@ -1985,109 +1909,58 @@ machine %s in domain %s.\n", global_myname(), lp_workgroup()));
 
 void smbd_process(void)
 {
-       time_t last_timeout_processing_time = time(NULL);
-       unsigned int num_smbs = 0;
-       size_t unread_bytes = 0;
-
-       max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
-
-       while (True) {
-               int select_timeout = setup_select_timeout();
-               int num_echos;
-               char *inbuf = NULL;
-               size_t inbuf_len = 0;
-               bool encrypted = false;
-               TALLOC_CTX *frame = talloc_stackframe_pool(8192);
-
-               errno = 0;
-
-               /* Did someone ask for immediate checks on things like blocking locks ? */
-               if (select_timeout == 0) {
-                       timeout_processing(&select_timeout,
-                                          &last_timeout_processing_time);
-                       num_smbs = 0; /* Reset smb counter. */
-               }
-
-               run_events(smbd_event_context(), 0, NULL, NULL);
-
-               while (True) {
-                       NTSTATUS status;
-
-                       status = receive_message_or_smb(
-                               talloc_tos(), &inbuf, &inbuf_len,
-                               select_timeout, &unread_bytes, &encrypted);
-
-                       if (NT_STATUS_IS_OK(status)) {
-                               break;
-                       }
-
-                       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
-                               timeout_processing(
-                                       &select_timeout,
-                                       &last_timeout_processing_time);
-                               continue;
-                       }
-
-                       DEBUG(3, ("receive_message_or_smb failed: %s, "
-                                 "exiting\n", nt_errstr(status)));
-                       return;
-
-                       num_smbs = 0; /* Reset smb counter. */
-               }
+       /*
+        * Before the first packet, check the global hosts allow/ hosts deny
+        * parameters before doing any parsing of packets passed to us by the
+        * client. This prevents attacks on our parsing code from hosts not in
+        * the hosts allow list.
+        */
 
+       if (!check_access(smbd_server_fd(), lp_hostsallow(-1),
+                         lp_hostsdeny(-1))) {
+               char addr[INET6_ADDRSTRLEN];
 
                /*
-                * Ensure we do timeout processing if the SMB we just got was
-                * only an echo request. This allows us to set the select
-                * timeout in 'receive_message_or_smb()' to any value we like
-                * without worrying that the client will send echo requests
-                * faster than the select timeout, thus starving out the
-                * essential processing (change notify, blocking locks) that
-                * the timeout code does. JRA.
+                * send a negative session response "not listening on calling
+                * name"
                 */
-               num_echos = smb_echo_count;
+               unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
+               DEBUG( 1, ("Connection denied from %s\n",
+                          client_addr(get_client_fd(),addr,sizeof(addr)) ) );
+               (void)srv_send_smb(smbd_server_fd(),(char *)buf,false);
+               exit_server_cleanly("connection denied");
+       }
 
-               process_smb(inbuf, inbuf_len, unread_bytes, encrypted);
+       max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
 
-               TALLOC_FREE(inbuf);
+       smbd_server_conn = talloc_zero(smbd_event_context(), struct smbd_server_connection);
+       if (!smbd_server_conn) {
+               exit_server("failed to create smbd_server_connection");
+       }
+       smbd_server_conn->fde = event_add_fd(smbd_event_context(),
+                                            smbd_server_conn,
+                                            smbd_server_fd(),
+                                            EVENT_FD_READ,
+                                            smbd_server_connection_handler,
+                                            smbd_server_conn);
+       if (!smbd_server_conn->fde) {
+               exit_server("failed to create smbd_server_connection fde");
+       }
 
-               if (smb_echo_count != num_echos) {
-                       timeout_processing(&select_timeout,
-                                          &last_timeout_processing_time);
-                       num_smbs = 0; /* Reset smb counter. */
-               }
+       while (True) {
+               NTSTATUS status;
+               TALLOC_CTX *frame = talloc_stackframe_pool(8192);
 
-               num_smbs++;
+               errno = 0;
 
-               /*
-                * If we are getting smb requests in a constant stream
-                * with no echos, make sure we attempt timeout processing
-                * every select_timeout milliseconds - but only check for this
-                * every 200 smb requests.
-                */
-               
-               if ((num_smbs % 200) == 0) {
-                       time_t new_check_time = time(NULL);
-                       if(new_check_time - last_timeout_processing_time >= (select_timeout/1000)) {
-                               timeout_processing(
-                                       &select_timeout,
-                                       &last_timeout_processing_time);
-                               num_smbs = 0; /* Reset smb counter. */
-                               last_timeout_processing_time = new_check_time; /* Reset time. */
-                       }
+               status = smbd_server_connection_loop_once(smbd_server_conn);
+               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)));
+                       return;
                }
 
-               /* The timeout_processing function isn't run nearly
-                  often enough to implement 'max log size' without
-                  overrunning the size of the file by many megabytes.
-                  This is especially true if we are running at debug
-                  level 10.  Checking every 50 SMBs is a nice
-                  tradeoff of performance vs log file size overrun. */
-
-               if ((num_smbs % 50) == 0 && need_to_check_log_size()) {
-                       change_to_root_user();
-                       check_log_size();
-               }
                TALLOC_FREE(frame);
        }
 }