s3:smbd: handle SMB2 in deadtime_fn() and avoid disconnecting non idle clients
[nivanova/samba-autobuild/.git] / source3 / smbd / process.c
index b26bc150dbdbcc1c558b6892b7bd8d3d7aa880fd..dd120f9bd2785beb62556bdfe37c34d63ff6f45f 100644 (file)
 
 #include "includes.h"
 #include "smbd/globals.h"
+#include "../librpc/gen_ndr/srv_dfs.h"
+#include "../librpc/gen_ndr/srv_dssetup.h"
+#include "../librpc/gen_ndr/srv_echo.h"
+#include "../librpc/gen_ndr/srv_eventlog.h"
+#include "../librpc/gen_ndr/srv_initshutdown.h"
+#include "../librpc/gen_ndr/srv_lsa.h"
+#include "../librpc/gen_ndr/srv_netlogon.h"
+#include "../librpc/gen_ndr/srv_ntsvcs.h"
+#include "../librpc/gen_ndr/srv_samr.h"
+#include "../librpc/gen_ndr/srv_spoolss.h"
+#include "../librpc/gen_ndr/srv_srvsvc.h"
+#include "../librpc/gen_ndr/srv_svcctl.h"
+#include "../librpc/gen_ndr/srv_winreg.h"
+#include "../librpc/gen_ndr/srv_wkssvc.h"
 
 extern bool global_machine_password_needs_changing;
 
 static void construct_reply_common(struct smb_request *req, const char *inbuf,
                                   char *outbuf);
 
+bool smbd_lock_socket(struct smbd_server_connection *sconn)
+{
+       bool ok;
+
+       if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
+               return true;
+       }
+
+       DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
+
+       ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
+                       SMB_F_SETLKW, 0, 0, F_WRLCK);
+       if (!ok) {
+               return false;
+       }
+
+       DEBUG(10,("pid[%d] got for socket lock\n", (int)sys_getpid()));
+
+       return true;
+}
+
+bool smbd_unlock_socket(struct smbd_server_connection *sconn)
+{
+       bool ok;
+
+       if (smbd_server_conn->smb1.echo_handler.socket_lock_fd == -1) {
+               return true;
+       }
+
+       ok = fcntl_lock(smbd_server_conn->smb1.echo_handler.socket_lock_fd,
+                       SMB_F_SETLKW, 0, 0, F_UNLCK);
+       if (!ok) {
+               return false;
+       }
+
+       DEBUG(10,("pid[%d] unlocked socket\n", (int)sys_getpid()));
+
+       return true;
+}
+
 /* Accessor function for smb_read_error for smbd functions. */
 
 /****************************************************************************
@@ -41,6 +95,12 @@ bool srv_send_smb(int fd, char *buffer,
        size_t nwritten=0;
        ssize_t ret;
        char *buf_out = buffer;
+       bool ok;
+
+       ok = smbd_lock_socket(smbd_server_conn);
+       if (!ok) {
+               exit_server_cleanly("failed to lock socket");
+       }
 
        if (do_signing) {
                /* Sign the outgoing packet if required. */
@@ -61,8 +121,8 @@ bool srv_send_smb(int fd, char *buffer,
 
        ret = write_data(fd,buf_out+nwritten,len - nwritten);
        if (ret <= 0) {
-               DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
-                        (int)len,(int)ret, strerror(errno) ));
+               DEBUG(0,("pid[%d] Error writing %d bytes to client. %d. (%s)\n",
+                       (int)sys_getpid(), (int)len,(int)ret, strerror(errno) ));
                srv_free_enc_buffer(buf_out);
                goto out;
        }
@@ -71,6 +131,12 @@ bool srv_send_smb(int fd, char *buffer,
        srv_free_enc_buffer(buf_out);
 out:
        SMB_PERFCOUNT_END(pcd);
+
+       ok = smbd_unlock_socket(smbd_server_conn);
+       if (!ok) {
+               exit_server_cleanly("failed to unlock socket");
+       }
+
        return true;
 }
 
@@ -128,7 +194,7 @@ static NTSTATUS read_packet_remainder(int fd, char *buffer,
                return NT_STATUS_OK;
        }
 
-       return read_socket_with_timeout(fd, buffer, len, len, timeout, NULL);
+       return read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
 }
 
 /****************************************************************************
@@ -162,7 +228,7 @@ static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
 
        memcpy(writeX_header, lenbuf, 4);
 
-       status = read_socket_with_timeout(
+       status = read_fd_with_timeout(
                fd, writeX_header + 4,
                STANDARD_WRITE_AND_X_HEADER_SIZE,
                STANDARD_WRITE_AND_X_HEADER_SIZE,
@@ -276,7 +342,8 @@ static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
        if (CVAL(lenbuf,0) == 0 && min_recv_size &&
            (smb_len_large(lenbuf) > /* Could be a UNIX large writeX. */
                (min_recv_size + STANDARD_WRITE_AND_X_HEADER_SIZE)) &&
-           !srv_is_signing_active(smbd_server_conn)) {
+           !srv_is_signing_active(smbd_server_conn) &&
+           smbd_server_conn->smb1.echo_handler.trusted_fde == NULL) {
 
                return receive_smb_raw_talloc_partial_read(
                        mem_ctx, lenbuf, fd, buffer, timeout, p_unread, plen);
@@ -313,7 +380,8 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,     int fd,
                                   char **buffer, unsigned int timeout,
                                   size_t *p_unread, bool *p_encrypted,
                                   size_t *p_len,
-                                  uint32_t *seqnum)
+                                  uint32_t *seqnum,
+                                  bool trusted_channel)
 {
        size_t len = 0;
        NTSTATUS status;
@@ -338,7 +406,7 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,     int fd,
        }
 
        /* Check the incoming SMB signature. */
-       if (!srv_check_sign_mac(smbd_server_conn, *buffer, seqnum)) {
+       if (!srv_check_sign_mac(smbd_server_conn, *buffer, seqnum, trusted_channel)) {
                DEBUG(0, ("receive_smb: SMB Signature verification failed on "
                          "incoming packet!\n"));
                return NT_STATUS_INVALID_NETWORK_RESPONSE;
@@ -352,10 +420,9 @@ static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,    int fd,
  * Initialize a struct smb_request from an inbuf
  */
 
-void init_smb_request(struct smb_request *req,
-                       const uint8 *inbuf,
-                       size_t unread_bytes,
-                       bool encrypted)
+static bool init_smb_request(struct smb_request *req, const uint8 *inbuf,
+                            size_t unread_bytes, bool encrypted,
+                            uint32_t seqnum)
 {
        struct smbd_server_connection *sconn = smbd_server_conn;
        size_t req_size = smb_len(inbuf) + 4;
@@ -363,13 +430,13 @@ void init_smb_request(struct smb_request *req,
        if (req_size < smb_size) {
                DEBUG(0,("init_smb_request: invalid request size %u\n",
                        (unsigned int)req_size ));
-               exit_server_cleanly("Invalid SMB request");
+               return false;
        }
        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->seqnum = 0;
+       req->seqnum = seqnum;
        req->vuid   = SVAL(inbuf, smb_uid);
        req->tid    = SVAL(inbuf, smb_tid);
        req->wct    = CVAL(inbuf, smb_wct);
@@ -381,6 +448,7 @@ void init_smb_request(struct smb_request *req,
        req->conn = conn_find(sconn,req->tid);
        req->chain_fsp = NULL;
        req->chain_outbuf = NULL;
+       req->done = false;
        smb_init_perfcount_data(&req->pcd);
 
        /* Ensure we have at least wct words and 2 bytes of bcc. */
@@ -388,7 +456,7 @@ void init_smb_request(struct smb_request *req,
                DEBUG(0,("init_smb_request: invalid wct number %u (size %u)\n",
                        (unsigned int)req->wct,
                        (unsigned int)req_size));
-               exit_server_cleanly("Invalid SMB request");
+               return false;
        }
        /* Ensure bcc is correct. */
        if (((uint8 *)smb_buf(inbuf)) + req->buflen > inbuf + req_size) {
@@ -397,10 +465,11 @@ void init_smb_request(struct smb_request *req,
                        (unsigned int)req->buflen,
                        (unsigned int)req->wct,
                        (unsigned int)req_size));
-               exit_server_cleanly("Invalid SMB request");
+               return false;
        }
 
        req->outbuf = NULL;
+       return true;
 }
 
 static void process_smb(struct smbd_server_connection *conn,
@@ -416,6 +485,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);
        TALLOC_CTX *mem_ctx = talloc_tos();
+       uint16_t mid = SVAL(msg->buf.data,smb_mid);
        uint8_t *inbuf;
 
        inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
@@ -428,11 +498,21 @@ static void smbd_deferred_open_timer(struct event_context *ev,
        /* 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)));
+               (unsigned int)mid ));
+
+       /* Mark the message as processed so this is not
+        * re-processed in error. */
+       msg->processed = true;
 
        process_smb(smbd_server_conn, inbuf,
                    msg->buf.length, 0,
                    msg->seqnum, msg->encrypted, &msg->pcd);
+
+       /* If it's still there and was processed, remove it. */
+       msg = get_open_deferred_message(mid);
+       if (msg && msg->processed) {
+               remove_deferred_open_smb_message(mid);
+       }
 }
 
 /****************************************************************************
@@ -465,6 +545,7 @@ static bool push_queued_message(struct smb_request *req,
        msg->request_time = request_time;
        msg->seqnum = req->seqnum;
        msg->encrypted = req->encrypted;
+       msg->processed = false;
        SMB_PERFCOUNT_DEFER_OP(&req->pcd, &msg->pcd);
 
        if (private_data) {
@@ -506,7 +587,7 @@ void remove_deferred_open_smb_message(uint16 mid)
 
        for (pml = deferred_open_queue; pml; pml = pml->next) {
                if (mid == SVAL(pml->buf.data,smb_mid)) {
-                       DEBUG(10,("remove_sharing_violation_open_smb_message: "
+                       DEBUG(10,("remove_deferred_open_smb_message: "
                                  "deleting mid %u len %u\n",
                                  (unsigned int)mid,
                                  (unsigned int)pml->buf.length ));
@@ -536,6 +617,15 @@ void schedule_deferred_open_smb_message(uint16 mid)
                if (mid == msg_mid) {
                        struct timed_event *te;
 
+                       if (pml->processed) {
+                               /* A processed message should not be
+                                * rescheduled. */
+                               DEBUG(0,("schedule_deferred_open_smb_message: LOGIC ERROR "
+                                       "message mid %u was already processed\n",
+                                       msg_mid ));
+                               continue;
+                       }
+
                        DEBUG(10,("schedule_deferred_open_smb_message: scheduling mid %u\n",
                                mid ));
 
@@ -562,7 +652,7 @@ void schedule_deferred_open_smb_message(uint16 mid)
 }
 
 /****************************************************************************
- Return true if this mid is on the deferred queue.
+ Return true if this mid is on the deferred queue and was not yet processed.
 ****************************************************************************/
 
 bool open_was_deferred(uint16 mid)
@@ -570,7 +660,7 @@ bool open_was_deferred(uint16 mid)
        struct pending_message_list *pml;
 
        for (pml = deferred_open_queue; pml; pml = pml->next) {
-               if (SVAL(pml->buf.data,smb_mid) == mid) {
+               if (SVAL(pml->buf.data,smb_mid) == mid && !pml->processed) {
                        return True;
                }
        }
@@ -1299,14 +1389,15 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                        if (type == SMBntcreateX) {
                                reply_nterror(req, NT_STATUS_INVALID_HANDLE);
                        } else {
-                               reply_doserror(req, ERRSRV, ERRinvnid);
+                               reply_nterror(req, NT_STATUS_NETWORK_NAME_DELETED);
                        }
                        return NULL;
                }
 
                if (!change_to_user(conn,session_tag)) {
-                       reply_nterror(req, NT_STATUS_DOS(ERRSRV, ERRbaduid));
-                       remove_deferred_open_smb_message(req->mid);
+                       DEBUG(0, ("Error: Could not change to user. Removing "
+                           "deferred open, mid=%d.\n", req->mid));
+                       reply_force_doserror(req, ERRSRV, ERRbaduid);
                        return conn;
                }
 
@@ -1320,7 +1411,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
 
                /* IPC services are limited */
                if (IS_IPC(conn) && !(flags & CAN_IPC)) {
-                       reply_doserror(req, ERRSRV,ERRaccess);
+                       reply_nterror(req, NT_STATUS_ACCESS_DENIED);
                        return conn;
                }
        } else {
@@ -1345,7 +1436,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
                if (!set_current_service(conn,SVAL(req->inbuf,smb_flg),
                                         (flags & (AS_USER|DO_CHDIR)
                                          ?True:False))) {
-                       reply_doserror(req, ERRSRV, ERRaccess);
+                       reply_nterror(req, NT_STATUS_ACCESS_DENIED);
                        return conn;
                }
                conn->num_smb_operations++;
@@ -1356,7 +1447,7 @@ static connection_struct *switch_message(uint8 type, struct smb_request *req, in
            && (!change_to_guest() ||
                !check_access(smbd_server_fd(), lp_hostsallow(-1),
                              lp_hostsdeny(-1)))) {
-               reply_doserror(req, ERRSRV, ERRaccess);
+               reply_nterror(req, NT_STATUS_ACCESS_DENIED);
                return conn;
        }
 
@@ -1379,9 +1470,12 @@ static void construct_reply(char *inbuf, int size, size_t unread_bytes,
                smb_panic("could not allocate smb_request");
        }
 
-       init_smb_request(req, (uint8 *)inbuf, unread_bytes, encrypted);
+       if (!init_smb_request(req, (uint8 *)inbuf, unread_bytes, encrypted,
+                             seqnum)) {
+               exit_server_cleanly("Invalid SMB request");
+       }
+
        req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
-       req->seqnum = seqnum;
 
        /* we popped this message off the queue - keep original perf data */
        if (deferred_pcd)
@@ -1403,6 +1497,11 @@ static void construct_reply(char *inbuf, int size, size_t unread_bytes,
                req->unread_bytes = 0;
        }
 
+       if (req->done) {
+               TALLOC_FREE(req);
+               return;
+       }
+
        if (req->outbuf == NULL) {
                return;
        }
@@ -1512,7 +1611,7 @@ 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, req->cmd);
        SIVAL(outbuf,smb_rcls,0);
        SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); 
@@ -1566,6 +1665,180 @@ static void fixup_chain_error_packet(struct smb_request *req)
        SCVAL(req->outbuf, smb_vwv0, 0xff);
 }
 
+/**
+ * @brief Find the smb_cmd offset of the last command pushed
+ * @param[in] buf      The buffer we're building up
+ * @retval             Where can we put our next andx cmd?
+ *
+ * While chaining requests, the "next" request we're looking at needs to put
+ * its SMB_Command before the data the previous request already built up added
+ * to the chain. Find the offset to the place where we have to put our cmd.
+ */
+
+static bool find_andx_cmd_ofs(uint8_t *buf, size_t *pofs)
+{
+       uint8_t cmd;
+       size_t ofs;
+
+       cmd = CVAL(buf, smb_com);
+
+       SMB_ASSERT(is_andx_req(cmd));
+
+       ofs = smb_vwv0;
+
+       while (CVAL(buf, ofs) != 0xff) {
+
+               if (!is_andx_req(CVAL(buf, ofs))) {
+                       return false;
+               }
+
+               /*
+                * ofs is from start of smb header, so add the 4 length
+                * bytes. The next cmd is right after the wct field.
+                */
+               ofs = SVAL(buf, ofs+2) + 4 + 1;
+
+               SMB_ASSERT(ofs+4 < talloc_get_size(buf));
+       }
+
+       *pofs = ofs;
+       return true;
+}
+
+/**
+ * @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.
+ */
+
+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)
+{
+       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);
+
+       /*
+        * old_size == smb_wct means we're pushing the first request in for
+        * libsmb/
+        */
+
+       first_request = (old_size == smb_wct);
+
+       if (!first_request && ((old_size % 4) != 0)) {
+               /*
+                * Align the wct field of subsequent requests to a 4-byte
+                * boundary
+                */
+               chain_padding = 4 - (old_size % 4);
+       }
+
+       /*
+        * 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.
+        */
+
+       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;
+
+       if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
+               DEBUG(1, ("splice_chain: %u bytes won't fit\n",
+                         (unsigned)new_size));
+               return false;
+       }
+
+       outbuf = TALLOC_REALLOC_ARRAY(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;
+               }
+
+               SCVAL(outbuf, andx_cmd_ofs, smb_command);
+               SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
+       }
+
+       ofs = old_size;
+
+       /*
+        * Push the chained request:
+        *
+        * wct field
+        */
+
+       SCVAL(outbuf, ofs, wct);
+       ofs += 1;
+
+       /*
+        * vwv array
+        */
+
+       memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
+       ofs += sizeof(uint16_t) * wct;
+
+       /*
+        * bcc (byte count)
+        */
+
+       SSVAL(outbuf, ofs, num_bytes + bytes_padding);
+       ofs += sizeof(uint16_t);
+
+       /*
+        * padding
+        */
+
+       if (bytes_padding != 0) {
+               memset(outbuf + ofs, 0, bytes_padding);
+               ofs += bytes_padding;
+       }
+
+       /*
+        * The bytes field
+        */
+
+       memcpy(outbuf + ofs, bytes, num_bytes);
+
+       return true;
+}
+
 /****************************************************************************
  Construct a chained reply and add it to the already made reply
 ****************************************************************************/
@@ -1596,6 +1869,15 @@ void chain_reply(struct smb_request *req)
         */
 
        if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
+               if (req->chain_outbuf == NULL) {
+                       req->chain_outbuf = TALLOC_REALLOC_ARRAY(
+                               req, req->outbuf, uint8_t,
+                               smb_len(req->outbuf) + 4);
+                       if (req->chain_outbuf == NULL) {
+                               smb_panic("talloc failed");
+                       }
+               }
+               req->outbuf = NULL;
                goto error;
        }
 
@@ -1623,7 +1905,7 @@ void chain_reply(struct smb_request *req)
                req->chain_outbuf = TALLOC_REALLOC_ARRAY(
                        req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
                if (req->chain_outbuf == NULL) {
-                       goto error;
+                       smb_panic("talloc failed");
                }
                req->outbuf = NULL;
        } else {
@@ -1669,8 +1951,8 @@ void chain_reply(struct smb_request *req)
                        exit_server_cleanly("chain_reply: srv_send_smb "
                                            "failed.");
                }
-               TALLOC_FREE(req);
-
+               TALLOC_FREE(req->chain_outbuf);
+               req->done = true;
                return;
        }
 
@@ -1767,10 +2049,25 @@ void chain_reply(struct smb_request *req)
         * 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));
+       reply_force_doserror(req, ERRSRV, ERRerror);
        fixup_chain_error_packet(req);
 
  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));
+
+       /*
+        * 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));
+
        if (!smb_splice_chain(&req->chain_outbuf,
                              CVAL(req->outbuf, smb_com),
                              CVAL(req->outbuf, smb_wct),
@@ -1792,7 +2089,8 @@ void chain_reply(struct smb_request *req)
                          &req->pcd)) {
                exit_server_cleanly("construct_reply: srv_send_smb failed.");
        }
-       TALLOC_FREE(req);
+       TALLOC_FREE(req->chain_outbuf);
+       req->done = true;
 }
 
 /****************************************************************************
@@ -1829,11 +2127,11 @@ void check_reload(time_t t)
        }
 
        /* 'printcap cache time = 0' disable the feature */
-       
+
        if ( printcap_cache_time != 0 )
        { 
                /* see if it's time to reload or if the clock has been set back */
-               
+
                if ( (t >= last_printer_reload_time+printcap_cache_time) 
                        || (t-last_printer_reload_time  < 0) ) 
                {
@@ -1844,12 +2142,29 @@ void check_reload(time_t t)
        }
 }
 
+static bool fd_is_readable(int fd)
+{
+       fd_set fds;
+       struct timeval timeout = {0, };
+       int ret;
+
+       FD_ZERO(&fds);
+       FD_SET(fd, &fds);
+
+       ret = sys_select(fd+1, &fds, NULL, NULL, &timeout);
+       if (ret == -1) {
+               return false;
+       }
+       return FD_ISSET(fd, &fds);
+}
+
 static void smbd_server_connection_write_handler(struct smbd_server_connection *conn)
 {
        /* TODO: make write nonblocking */
 }
 
-static void smbd_server_connection_read_handler(struct smbd_server_connection *conn)
+static void smbd_server_connection_read_handler(
+       struct smbd_server_connection *conn, int fd)
 {
        uint8_t *inbuf = NULL;
        size_t inbuf_len = 0;
@@ -1859,14 +2174,48 @@ static void smbd_server_connection_read_handler(struct smbd_server_connection *c
        NTSTATUS status;
        uint32_t seqnum;
 
-       /* TODO: make this completely nonblocking */
+       bool ok;
+
+       bool from_client = (smbd_server_fd() == fd)?true:false;
+
+       if (from_client) {
+               ok = smbd_lock_socket(conn);
+               if (!ok) {
+                       exit_server_cleanly("failed to lock socket");
+               }
+
+               if (!fd_is_readable(smbd_server_fd())) {
+                       DEBUG(10,("the echo listener was faster\n"));
+                       ok = smbd_unlock_socket(conn);
+                       if (!ok) {
+                               exit_server_cleanly("failed to unlock");
+                       }
+                       return;
+               }
+
+               /* TODO: make this completely nonblocking */
+               status = receive_smb_talloc(mem_ctx, fd,
+                                           (char **)(void *)&inbuf,
+                                           0, /* timeout */
+                                           &unread_bytes,
+                                           &encrypted,
+                                           &inbuf_len, &seqnum,
+                                           false /* trusted channel */);
+               ok = smbd_unlock_socket(conn);
+               if (!ok) {
+                       exit_server_cleanly("failed to unlock");
+               }
+       } else {
+               /* TODO: make this completely nonblocking */
+               status = receive_smb_talloc(mem_ctx, fd,
+                                           (char **)(void *)&inbuf,
+                                           0, /* timeout */
+                                           &unread_bytes,
+                                           &encrypted,
+                                           &inbuf_len, &seqnum,
+                                           true /* trusted channel */);
+       }
 
-       status = receive_smb_talloc(mem_ctx, smbd_server_fd(),
-                                   (char **)(void *)&inbuf,
-                                   0, /* timeout */
-                                   &unread_bytes,
-                                   &encrypted,
-                                   &inbuf_len, &seqnum);
        if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
                goto process;
        }
@@ -1893,10 +2242,25 @@ static void smbd_server_connection_handler(struct event_context *ev,
        if (flags & EVENT_FD_WRITE) {
                smbd_server_connection_write_handler(conn);
        } else if (flags & EVENT_FD_READ) {
-               smbd_server_connection_read_handler(conn);
+               smbd_server_connection_read_handler(conn, smbd_server_fd());
        }
 }
 
+static void smbd_server_echo_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);
+
+       if (flags & EVENT_FD_WRITE) {
+               smbd_server_connection_write_handler(conn);
+       } else if (flags & EVENT_FD_READ) {
+               smbd_server_connection_read_handler(
+                       conn, conn->smb1.echo_handler.trusted_fd);
+       }
+}
 
 /****************************************************************************
 received when we should release a specific IP
@@ -1957,7 +2321,22 @@ static int client_get_tcp_info(struct sockaddr_storage *server,
  */
 static bool keepalive_fn(const struct timeval *now, void *private_data)
 {
-       if (!send_keepalive(smbd_server_fd())) {
+       bool ok;
+       bool ret;
+
+       ok = smbd_lock_socket(smbd_server_conn);
+       if (!ok) {
+               exit_server_cleanly("failed to lock socket");
+       }
+
+       ret = send_keepalive(smbd_server_fd());
+
+       ok = smbd_unlock_socket(smbd_server_conn);
+       if (!ok) {
+               exit_server_cleanly("failed to unlock socket");
+       }
+
+       if (!ret) {
                DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
                return False;
        }
@@ -1970,9 +2349,21 @@ static bool keepalive_fn(const struct timeval *now, void *private_data)
 static bool deadtime_fn(const struct timeval *now, void *private_data)
 {
        struct smbd_server_connection *sconn = smbd_server_conn;
+
+       if (sconn->allow_smb2) {
+               /* TODO: implement real idle check */
+               if (sconn->smb2.sessions.list) {
+                       return true;
+               }
+               DEBUG( 2, ( "Closing idle SMB2 connection\n" ) );
+               messaging_send(smbd_messaging_context(), procid_self(),
+                              MSG_SHUTDOWN, &data_blob_null);
+               return false;
+       }
+
        if ((conn_num_open(sconn) == 0)
            || (conn_idle_all(sconn, now->tv_sec))) {
-               DEBUG( 2, ( "Closing idle connection\n" ) );
+               DEBUG( 2, ( "Closing idle SMB1 connection\n" ) );
                messaging_send(smbd_messaging_context(), procid_self(),
                               MSG_SHUTDOWN, &data_blob_null);
                return False;
@@ -2006,6 +2397,377 @@ static bool housekeeping_fn(const struct timeval *now, void *private_data)
        return true;
 }
 
+static int create_unlink_tmp(const char *dir)
+{
+       char *fname;
+       int fd;
+
+       fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
+       if (fname == NULL) {
+               errno = ENOMEM;
+               return -1;
+       }
+       fd = mkstemp(fname);
+       if (fd == -1) {
+               TALLOC_FREE(fname);
+               return -1;
+       }
+       if (unlink(fname) == -1) {
+               int sys_errno = errno;
+               close(fd);
+               TALLOC_FREE(fname);
+               errno = sys_errno;
+               return -1;
+       }
+       TALLOC_FREE(fname);
+       return fd;
+}
+
+struct smbd_echo_state {
+       struct tevent_context *ev;
+       struct iovec *pending;
+       struct smbd_server_connection *sconn;
+       int parent_pipe;
+
+       struct tevent_fd *parent_fde;
+
+       struct tevent_fd *read_fde;
+       struct tevent_req *write_req;
+};
+
+static void smbd_echo_writer_done(struct tevent_req *req);
+
+static void smbd_echo_activate_writer(struct smbd_echo_state *state)
+{
+       int num_pending;
+
+       if (state->write_req != NULL) {
+               return;
+       }
+
+       num_pending = talloc_array_length(state->pending);
+       if (num_pending == 0) {
+               return;
+       }
+
+       state->write_req = writev_send(state, state->ev, NULL,
+                                      state->parent_pipe, false,
+                                      state->pending, num_pending);
+       if (state->write_req == NULL) {
+               DEBUG(1, ("writev_send failed\n"));
+               exit(1);
+       }
+
+       talloc_steal(state->write_req, state->pending);
+       state->pending = NULL;
+
+       tevent_req_set_callback(state->write_req, smbd_echo_writer_done,
+                               state);
+}
+
+static void smbd_echo_writer_done(struct tevent_req *req)
+{
+       struct smbd_echo_state *state = tevent_req_callback_data(
+               req, struct smbd_echo_state);
+       ssize_t written;
+       int err;
+
+       written = writev_recv(req, &err);
+       TALLOC_FREE(req);
+       state->write_req = NULL;
+       if (written == -1) {
+               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()));
+       smbd_echo_activate_writer(state);
+}
+
+static bool smbd_echo_reply(int fd,
+                           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 < smb_size) {
+               DEBUG(10, ("Got short packet: %d bytes\n", (int)inbuf_len));
+               return false;
+       }
+       if (!valid_smb_header(inbuf)) {
+               DEBUG(10, ("Got invalid SMB header\n"));
+               return false;
+       }
+
+       if (!init_smb_request(&req, inbuf, 0, false, seqnum)) {
+               return false;
+       }
+       req.inbuf = inbuf;
+
+       DEBUG(10, ("smbecho handler got cmd %d (%s)\n", (int)req.cmd,
+                  smb_messages[req.cmd].name
+                  ? smb_messages[req.cmd].name : "unknown"));
+
+       if (req.cmd != SMBecho) {
+               return false;
+       }
+       if (req.wct < 1) {
+               return false;
+       }
+
+       num_replies = SVAL(req.vwv+0, 0);
+       if (num_replies != 1) {
+               /* Not a Windows "Hey, you're still there?" request */
+               return false;
+       }
+
+       if (!create_outbuf(talloc_tos(), &req, (char *)req.inbuf, &outbuf,
+                          1, req.buflen)) {
+               DEBUG(10, ("create_outbuf failed\n"));
+               return false;
+       }
+       req.outbuf = (uint8_t *)outbuf;
+
+       SSVAL(req.outbuf, smb_vwv0, num_replies);
+
+       if (req.buflen > 0) {
+               memcpy(smb_buf(req.outbuf), req.buf, req.buflen);
+       }
+
+       out_len = smb_len(req.outbuf) + 4;
+
+       ok = srv_send_smb(smbd_server_fd(),
+                         (char *)outbuf,
+                         true, seqnum+1,
+                         false, &req.pcd);
+       TALLOC_FREE(outbuf);
+       if (!ok) {
+               exit(1);
+       }
+
+       return true;
+}
+
+static void smbd_echo_exit(struct tevent_context *ev,
+                          struct tevent_fd *fde, uint16_t flags,
+                          void *private_data)
+{
+       DEBUG(2, ("smbd_echo_exit: lost connection to parent\n"));
+       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;
+       uint32_t seqnum = 0;
+       bool reply;
+       bool ok;
+       bool encrypted = false;
+
+       ok = smbd_lock_socket(sconn);
+       if (!ok) {
+               DEBUG(0, ("%s: failed to lock socket\n",
+                       __location__));
+               exit(1);
+       }
+
+       if (!fd_is_readable(smbd_server_fd())) {
+               DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
+                         (int)sys_getpid()));
+               ok = smbd_unlock_socket(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, smbd_server_fd(),
+                                   (char **)(void *)&state->pending[num_pending].iov_base,
+                                   0 /* timeout */,
+                                   &unread,
+                                   &encrypted,
+                                   &state->pending[num_pending].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);
+       }
+
+       ok = smbd_unlock_socket(sconn);
+       if (!ok) {
+               DEBUG(1, ("%s: failed to unlock socket in\n",
+                       __location__));
+               exit(1);
+       }
+
+       /*
+        * 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));
+
+       reply = smbd_echo_reply(smbd_server_fd(),
+                               (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);
+       } else {
+               DEBUG(10,("echo_handler[%d]: forward to main\n", (int)sys_getpid()));
+               smbd_echo_activate_writer(state);
+       }
+}
+
+static void smbd_echo_loop(struct smbd_server_connection *sconn,
+                          int parent_pipe)
+{
+       struct smbd_echo_state *state;
+
+       state = talloc_zero(sconn, struct smbd_echo_state);
+       if (state == NULL) {
+               DEBUG(1, ("talloc failed\n"));
+               return;
+       }
+       state->sconn = sconn;
+       state->parent_pipe = parent_pipe;
+       state->ev = s3_tevent_context_init(state);
+       if (state->ev == NULL) {
+               DEBUG(1, ("tevent_context_init failed\n"));
+               TALLOC_FREE(state);
+               return;
+       }
+       state->parent_fde = tevent_add_fd(state->ev, state, parent_pipe,
+                                       TEVENT_FD_READ, smbd_echo_exit,
+                                       state);
+       if (state->parent_fde == NULL) {
+               DEBUG(1, ("tevent_add_fd failed\n"));
+               TALLOC_FREE(state);
+               return;
+       }
+       state->read_fde = tevent_add_fd(state->ev, state, smbd_server_fd(),
+                                       TEVENT_FD_READ, smbd_echo_reader,
+                                       state);
+       if (state->read_fde == NULL) {
+               DEBUG(1, ("tevent_add_fd failed\n"));
+               TALLOC_FREE(state);
+               return;
+       }
+
+       while (true) {
+               if (tevent_loop_once(state->ev) == -1) {
+                       DEBUG(1, ("tevent_loop_once failed: %s\n",
+                                 strerror(errno)));
+                       break;
+               }
+       }
+       TALLOC_FREE(state);
+}
+
+/*
+ * Handle SMBecho requests in a forked child process
+ */
+static bool fork_echo_handler(struct smbd_server_connection *sconn)
+{
+       int listener_pipe[2];
+       int res;
+       pid_t child;
+
+       res = pipe(listener_pipe);
+       if (res == -1) {
+               DEBUG(1, ("pipe() failed: %s\n", strerror(errno)));
+               return false;
+       }
+       sconn->smb1.echo_handler.socket_lock_fd = create_unlink_tmp(lp_lockdir());
+       if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
+               DEBUG(1, ("Could not create lock fd: %s\n", strerror(errno)));
+               goto fail;
+       }
+
+       child = sys_fork();
+       if (child == 0) {
+               NTSTATUS status;
+
+               close(listener_pipe[0]);
+
+               status = reinit_after_fork(smbd_messaging_context(),
+                                          smbd_event_context(), false);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(1, ("reinit_after_fork failed: %s\n",
+                                 nt_errstr(status)));
+                       exit(1);
+               }
+               smbd_echo_loop(sconn, listener_pipe[1]);
+               exit(0);
+       }
+       close(listener_pipe[1]);
+       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));
+
+       /*
+        * 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,
+                                       sconn->smb1.echo_handler.trusted_fd,
+                                       EVENT_FD_READ,
+                                       smbd_server_echo_handler,
+                                       sconn);
+       if (sconn->smb1.echo_handler.trusted_fde == NULL) {
+               DEBUG(1, ("event_add_fd failed\n"));
+               goto fail;
+       }
+
+       return true;
+
+fail:
+       if (listener_pipe[0] != -1) {
+               close(listener_pipe[0]);
+       }
+       if (listener_pipe[1] != -1) {
+               close(listener_pipe[1]);
+       }
+       sconn->smb1.echo_handler.trusted_fd = -1;
+       if (sconn->smb1.echo_handler.socket_lock_fd != -1) {
+               close(sconn->smb1.echo_handler.socket_lock_fd);
+       }
+       sconn->smb1.echo_handler.trusted_fd = -1;
+       sconn->smb1.echo_handler.socket_lock_fd = -1;
+       return false;
+}
+
 /****************************************************************************
  Process commands from the client
 ****************************************************************************/
@@ -2015,13 +2777,9 @@ void smbd_process(void)
        TALLOC_CTX *frame = talloc_stackframe();
        char remaddr[INET6_ADDRSTRLEN];
 
-       smbd_server_conn = talloc_zero(smbd_event_context(), struct smbd_server_connection);
-       if (!smbd_server_conn) {
-               exit_server("failed to create smbd_server_connection");
-       }
-
        if (lp_maxprotocol() == PROTOCOL_SMB2 &&
-           lp_security() != SEC_SHARE) {
+           lp_security() != SEC_SHARE &&
+           !lp_async_smb_echo_handler()) {
                smbd_server_conn->allow_smb2 = true;
        }
 
@@ -2088,6 +2846,10 @@ void smbd_process(void)
                exit_server("Failed to init smb_signing");
        }
 
+       if (lp_async_smb_echo_handler() && !fork_echo_handler(smbd_server_conn)) {
+               exit_server("Failed to fork echo handler");
+       }
+
        /* Setup oplocks */
        if (!init_oplocks(smbd_messaging_context()))
                exit_server("Failed to init oplocks");
@@ -2189,6 +2951,9 @@ void smbd_process(void)
 #endif
 
        conn_init(smbd_server_conn);
+       if (!init_dptrs(smbd_server_conn)) {
+               exit_server("init_dptrs() failed");
+       }
 
        smbd_server_conn->smb1.fde = event_add_fd(smbd_event_context(),
                                                  smbd_server_conn,