Ignore:
Timestamp:
Nov 24, 2016, 1:14:11 PM (9 years ago)
Author:
Silvan Scherrer
Message:

Samba Server: update vendor to version 4.4.3

File:
1 edited

Legend:

Unmodified
Added
Removed
  • vendor/current/source3/smbd/process.c

    r860 r988  
    2828#include "ctdbd_conn.h"
    2929#include "../lib/util/select.h"
    30 #include "printing/pcap.h"
     30#include "printing/queue_process.h"
    3131#include "system/select.h"
    3232#include "passdb.h"
     
    3636#include "rpc_server/spoolss/srv_spoolss_nt.h"
    3737#include "libsmb/libsmb.h"
    38 
    39 extern bool global_machine_password_needs_changing;
    40 
    41 static void construct_reply_common(struct smb_request *req, const char *inbuf,
     38#include "../lib/util/tevent_ntstatus.h"
     39#include "../libcli/security/dom_sid.h"
     40#include "../libcli/security/security_token.h"
     41#include "lib/id_cache.h"
     42#include "lib/util/sys_rw_data.h"
     43#include "serverid.h"
     44#include "system/threads.h"
     45
     46/* Internal message queue for deferred opens. */
     47struct pending_message_list {
     48        struct pending_message_list *next, *prev;
     49        struct timeval request_time; /* When was this first issued? */
     50        struct smbd_server_connection *sconn;
     51        struct smbXsrv_connection *xconn;
     52        struct tevent_timer *te;
     53        struct smb_perfcount_data pcd;
     54        uint32_t seqnum;
     55        bool encrypted;
     56        bool processed;
     57        DATA_BLOB buf;
     58        struct deferred_open_record *open_rec;
     59};
     60
     61static void construct_reply_common(uint8_t cmd, const uint8_t *inbuf,
    4262                                   char *outbuf);
    43 static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid);
    44 
    45 static bool smbd_lock_socket_internal(struct smbd_server_connection *sconn)
    46 {
    47         bool ok;
    48 
    49         if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
     63static struct pending_message_list *get_deferred_open_message_smb(
     64        struct smbd_server_connection *sconn, uint64_t mid);
     65static bool smb_splice_chain(uint8_t **poutbuf, const uint8_t *andx_buf);
     66
     67static void smbd_echo_init(struct smbXsrv_connection *xconn)
     68{
     69        xconn->smb1.echo_handler.trusted_fd = -1;
     70        xconn->smb1.echo_handler.socket_lock_fd = -1;
     71#ifdef HAVE_ROBUST_MUTEXES
     72        xconn->smb1.echo_handler.socket_mutex = NULL;
     73#endif
     74}
     75
     76static bool smbd_echo_active(struct smbXsrv_connection *xconn)
     77{
     78        if (xconn->smb1.echo_handler.socket_lock_fd != -1) {
    5079                return true;
    5180        }
    5281
    53         sconn->smb1.echo_handler.ref_count++;
    54 
    55         if (sconn->smb1.echo_handler.ref_count > 1) {
     82#ifdef HAVE_ROBUST_MUTEXES
     83        if (xconn->smb1.echo_handler.socket_mutex != NULL) {
    5684                return true;
    5785        }
    58 
    59         DEBUG(10,("pid[%d] wait for socket lock\n", (int)sys_getpid()));
    60 
    61         do {
    62                 ok = fcntl_lock(
    63                         sconn->smb1.echo_handler.socket_lock_fd,
    64                         SMB_F_SETLKW, 0, 0, F_WRLCK);
    65         } while (!ok && (errno == EINTR));
    66 
    67         if (!ok) {
    68                 DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
    69                 return false;
    70         }
    71 
    72         DEBUG(10,("pid[%d] got for socket lock\n", (int)sys_getpid()));
     86#endif
     87
     88        return false;
     89}
     90
     91static bool smbd_lock_socket_internal(struct smbXsrv_connection *xconn)
     92{
     93        if (!smbd_echo_active(xconn)) {
     94                return true;
     95        }
     96
     97        xconn->smb1.echo_handler.ref_count++;
     98
     99        if (xconn->smb1.echo_handler.ref_count > 1) {
     100                return true;
     101        }
     102
     103        DEBUG(10,("pid[%d] wait for socket lock\n", (int)getpid()));
     104
     105#ifdef HAVE_ROBUST_MUTEXES
     106        if (xconn->smb1.echo_handler.socket_mutex != NULL) {
     107                int ret = EINTR;
     108
     109                while (ret == EINTR) {
     110                        ret = pthread_mutex_lock(
     111                                xconn->smb1.echo_handler.socket_mutex);
     112                        if (ret == 0) {
     113                                break;
     114                        }
     115                }
     116                if (ret != 0) {
     117                        DEBUG(1, ("pthread_mutex_lock failed: %s\n",
     118                                  strerror(ret)));
     119                        return false;
     120                }
     121        }
     122#endif
     123
     124        if (xconn->smb1.echo_handler.socket_lock_fd != -1) {
     125                bool ok;
     126
     127                do {
     128                        ok = fcntl_lock(
     129                                xconn->smb1.echo_handler.socket_lock_fd,
     130                                F_SETLKW, 0, 0, F_WRLCK);
     131                } while (!ok && (errno == EINTR));
     132
     133                if (!ok) {
     134                        DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
     135                        return false;
     136                }
     137        }
     138
     139        DEBUG(10,("pid[%d] got socket lock\n", (int)getpid()));
    73140
    74141        return true;
    75142}
    76143
    77 void smbd_lock_socket(struct smbd_server_connection *sconn)
    78 {
    79         if (!smbd_lock_socket_internal(sconn)) {
     144void smbd_lock_socket(struct smbXsrv_connection *xconn)
     145{
     146        if (!smbd_lock_socket_internal(xconn)) {
    80147                exit_server_cleanly("failed to lock socket");
    81148        }
    82149}
    83150
    84 static bool smbd_unlock_socket_internal(struct smbd_server_connection *sconn)
    85 {
    86         bool ok;
    87 
    88         if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
     151static bool smbd_unlock_socket_internal(struct smbXsrv_connection *xconn)
     152{
     153        if (!smbd_echo_active(xconn)) {
    89154                return true;
    90155        }
    91156
    92         sconn->smb1.echo_handler.ref_count--;
    93 
    94         if (sconn->smb1.echo_handler.ref_count > 0) {
     157        xconn->smb1.echo_handler.ref_count--;
     158
     159        if (xconn->smb1.echo_handler.ref_count > 0) {
    95160                return true;
    96161        }
    97162
    98         do {
    99                 ok = fcntl_lock(
    100                         sconn->smb1.echo_handler.socket_lock_fd,
    101                         SMB_F_SETLKW, 0, 0, F_UNLCK);
    102         } while (!ok && (errno == EINTR));
    103 
    104         if (!ok) {
    105                 DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
    106                 return false;
    107         }
    108 
    109         DEBUG(10,("pid[%d] unlocked socket\n", (int)sys_getpid()));
     163#ifdef HAVE_ROBUST_MUTEXES
     164        if (xconn->smb1.echo_handler.socket_mutex != NULL) {
     165                int ret = EINTR;
     166
     167                while (ret == EINTR) {
     168                        ret = pthread_mutex_unlock(
     169                                xconn->smb1.echo_handler.socket_mutex);
     170                        if (ret == 0) {
     171                                break;
     172                        }
     173                }
     174                if (ret != 0) {
     175                        DEBUG(1, ("pthread_mutex_unlock failed: %s\n",
     176                                  strerror(ret)));
     177                        return false;
     178                }
     179        }
     180#endif
     181
     182        if (xconn->smb1.echo_handler.socket_lock_fd != -1) {
     183                bool ok;
     184
     185                do {
     186                        ok = fcntl_lock(
     187                                xconn->smb1.echo_handler.socket_lock_fd,
     188                                F_SETLKW, 0, 0, F_UNLCK);
     189                } while (!ok && (errno == EINTR));
     190
     191                if (!ok) {
     192                        DEBUG(1, ("fcntl_lock failed: %s\n", strerror(errno)));
     193                        return false;
     194                }
     195        }
     196
     197        DEBUG(10,("pid[%d] unlocked socket\n", (int)getpid()));
    110198
    111199        return true;
    112200}
    113201
    114 void smbd_unlock_socket(struct smbd_server_connection *sconn)
    115 {
    116         if (!smbd_unlock_socket_internal(sconn)) {
     202void smbd_unlock_socket(struct smbXsrv_connection *xconn)
     203{
     204        if (!smbd_unlock_socket_internal(xconn)) {
    117205                exit_server_cleanly("failed to unlock socket");
    118206        }
     
    125213****************************************************************************/
    126214
    127 bool srv_send_smb(struct smbd_server_connection *sconn, char *buffer,
     215bool srv_send_smb(struct smbXsrv_connection *xconn, char *buffer,
    128216                  bool do_signing, uint32_t seqnum,
    129217                  bool do_encrypt,
     
    131219{
    132220        size_t len = 0;
    133         size_t nwritten=0;
    134221        ssize_t ret;
    135222        char *buf_out = buffer;
    136223
    137         smbd_lock_socket(sconn);
     224        if (!NT_STATUS_IS_OK(xconn->transport.status)) {
     225                /*
     226                 * we're not supposed to do any io
     227                 */
     228                return true;
     229        }
     230
     231        smbd_lock_socket(xconn);
    138232
    139233        if (do_signing) {
    140234                /* Sign the outgoing packet if required. */
    141                 srv_calculate_sign_mac(sconn, buf_out, seqnum);
     235                srv_calculate_sign_mac(xconn, buf_out, seqnum);
    142236        }
    143237
    144238        if (do_encrypt) {
    145                 NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
     239                NTSTATUS status = srv_encrypt_buffer(xconn, buffer, &buf_out);
    146240                if (!NT_STATUS_IS_OK(status)) {
    147241                        DEBUG(0, ("send_smb: SMB encryption failed "
    148242                                "on outgoing packet! Error %s\n",
    149243                                nt_errstr(status) ));
     244                        ret = -1;
    150245                        goto out;
    151246                }
     
    154249        len = smb_len_large(buf_out) + 4;
    155250
    156         ret = write_data(sconn->sock, buf_out+nwritten, len - nwritten);
     251        ret = write_data(xconn->transport.sock, buf_out, len);
    157252        if (ret <= 0) {
    158 
    159                 char addr[INET6_ADDRSTRLEN];
     253                int saved_errno = errno;
    160254                /*
    161255                 * Try and give an error message saying what
     
    163257                 */
    164258                DEBUG(1,("pid[%d] Error writing %d bytes to client %s. %d. (%s)\n",
    165                          (int)sys_getpid(), (int)len,
    166                          get_peer_addr(sconn->sock, addr, sizeof(addr)),
    167                          (int)ret, strerror(errno) ));
    168 
    169                 srv_free_enc_buffer(buf_out);
     259                         (int)getpid(), (int)len,
     260                         smbXsrv_connection_dbg(xconn),
     261                         (int)ret, strerror(saved_errno)));
     262                errno = saved_errno;
     263
     264                srv_free_enc_buffer(xconn, buf_out);
    170265                goto out;
    171266        }
    172267
    173268        SMB_PERFCOUNT_SET_MSGLEN_OUT(pcd, len);
    174         srv_free_enc_buffer(buf_out);
     269        srv_free_enc_buffer(xconn, buf_out);
    175270out:
    176271        SMB_PERFCOUNT_END(pcd);
    177272
    178         smbd_unlock_socket(sconn);
    179         return true;
     273        smbd_unlock_socket(xconn);
     274        return (ret > 0);
    180275}
    181276
     
    219314         */
    220315
    221         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
     316        if (len > (LARGE_WRITEX_BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
    222317                DEBUG(0,("Invalid packet length! (%lu bytes).\n",
    223318                                        (unsigned long)len));
     
    265360static NTSTATUS receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
    266361                                                    const char lenbuf[4],
    267                                                     struct smbd_server_connection *sconn,
     362                                                    struct smbXsrv_connection *xconn,
    268363                                                    int sock,
    269364                                                    char **buffer,
     
    288383        if (!NT_STATUS_IS_OK(status)) {
    289384                DEBUG(0, ("read_fd_with_timeout failed for client %s read "
    290                           "error = %s.\n", sconn->client_id.addr,
     385                          "error = %s.\n",
     386                          smbXsrv_connection_dbg(xconn),
    291387                          nt_errstr(status)));
    292388                return status;
     
    298394         */
    299395
    300         if (is_valid_writeX_buffer(sconn, (uint8_t *)writeX_header)) {
     396        if (is_valid_writeX_buffer(xconn, (uint8_t *)writeX_header)) {
    301397                /*
    302398                 * If the data offset is beyond what
     
    322418                /* Copy the header we've written. */
    323419
    324                 *buffer = (char *)TALLOC_MEMDUP(mem_ctx,
     420                *buffer = (char *)talloc_memdup(mem_ctx,
    325421                                writeX_header,
    326422                                sizeof(writeX_header));
     
    347443         */
    348444
    349         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
     445        *buffer = talloc_array(mem_ctx, char, len+4);
    350446
    351447        if (*buffer == NULL) {
     
    379475
    380476static NTSTATUS receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
    381                                        struct smbd_server_connection *sconn,
     477                                       struct smbXsrv_connection *xconn,
    382478                                       int sock,
    383479                                       char **buffer, unsigned int timeout,
     
    400496            (smb_len_large(lenbuf) > /* Could be a UNIX large writeX. */
    401497                (min_recv_size + STANDARD_WRITE_AND_X_HEADER_SIZE)) &&
    402             !srv_is_signing_active(sconn) &&
    403             sconn->smb1.echo_handler.trusted_fde == NULL) {
     498            !srv_is_signing_active(xconn) &&
     499            xconn->smb1.echo_handler.trusted_fde == NULL) {
    404500
    405501                return receive_smb_raw_talloc_partial_read(
    406                         mem_ctx, lenbuf, sconn, sock, buffer, timeout,
     502                        mem_ctx, lenbuf, xconn, sock, buffer, timeout,
    407503                        p_unread, plen);
    408504        }
     
    416512         */
    417513
    418         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
     514        *buffer = talloc_array(mem_ctx, char, len+4);
    419515
    420516        if (*buffer == NULL) {
     
    436532
    437533static NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
    438                                    struct smbd_server_connection *sconn,
     534                                   struct smbXsrv_connection *xconn,
    439535                                   int sock,
    440536                                   char **buffer, unsigned int timeout,
     
    449545        *p_encrypted = false;
    450546
    451         status = receive_smb_raw_talloc(mem_ctx, sconn, sock, buffer, timeout,
     547        status = receive_smb_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
    452548                                        p_unread, &len);
    453549        if (!NT_STATUS_IS_OK(status)) {
     
    455551                      ("receive_smb_raw_talloc failed for client %s "
    456552                       "read error = %s.\n",
    457                        sconn->client_id.addr, nt_errstr(status)));
     553                       smbXsrv_connection_dbg(xconn),
     554                       nt_errstr(status)) );
    458555                return status;
    459556        }
    460557
    461558        if (is_encrypted_packet((uint8_t *)*buffer)) {
    462                 status = srv_decrypt_buffer(*buffer);
     559                status = srv_decrypt_buffer(xconn, *buffer);
    463560                if (!NT_STATUS_IS_OK(status)) {
    464561                        DEBUG(0, ("receive_smb_talloc: SMB decryption failed on "
     
    471568
    472569        /* Check the incoming SMB signature. */
    473         if (!srv_check_sign_mac(sconn, *buffer, seqnum, trusted_channel)) {
     570        if (!srv_check_sign_mac(xconn, *buffer, seqnum, trusted_channel)) {
    474571                DEBUG(0, ("receive_smb: SMB Signature verification failed on "
    475572                          "incoming packet!\n"));
     
    487584static bool init_smb_request(struct smb_request *req,
    488585                             struct smbd_server_connection *sconn,
    489                              const uint8 *inbuf,
     586                             struct smbXsrv_connection *xconn,
     587                             const uint8_t *inbuf,
    490588                             size_t unread_bytes, bool encrypted,
    491589                             uint32_t seqnum)
    492590{
     591        struct smbXsrv_tcon *tcon;
     592        NTSTATUS status;
     593        NTTIME now;
    493594        size_t req_size = smb_len(inbuf) + 4;
     595
    494596        /* Ensure we have at least smb_size bytes. */
    495597        if (req_size < smb_size) {
     
    498600                return false;
    499601        }
     602
     603        req->request_time = timeval_current();
     604        now = timeval_to_nttime(&req->request_time);
     605
    500606        req->cmd    = CVAL(inbuf, smb_com);
    501607        req->flags2 = SVAL(inbuf, smb_flg2);
     
    506612        req->tid    = SVAL(inbuf, smb_tid);
    507613        req->wct    = CVAL(inbuf, smb_wct);
    508         req->vwv    = (uint16_t *)(inbuf+smb_vwv);
     614        req->vwv    = (const uint16_t *)(inbuf+smb_vwv);
    509615        req->buflen = smb_buflen(inbuf);
    510         req->buf    = (const uint8_t *)smb_buf(inbuf);
     616        req->buf    = (const uint8_t *)smb_buf_const(inbuf);
    511617        req->unread_bytes = unread_bytes;
    512618        req->encrypted = encrypted;
    513619        req->sconn = sconn;
    514         req->conn = conn_find(sconn,req->tid);
     620        req->xconn = xconn;
     621        req->conn = NULL;
     622        if (xconn != NULL) {
     623                status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
     624                if (NT_STATUS_IS_OK(status)) {
     625                        req->conn = tcon->compat;
     626                }
     627        }
    515628        req->chain_fsp = NULL;
    516         req->chain_outbuf = NULL;
    517         req->done = false;
    518629        req->smb2req = NULL;
     630        req->priv_paths = NULL;
     631        req->chain = NULL;
     632        req->posix_pathnames = lp_posix_pathnames();
    519633        smb_init_perfcount_data(&req->pcd);
    520634
     
    527641        }
    528642        /* Ensure bcc is correct. */
    529         if (((uint8 *)smb_buf(inbuf)) + req->buflen > inbuf + req_size) {
     643        if (((const uint8_t *)smb_buf_const(inbuf)) + req->buflen > inbuf + req_size) {
    530644                DEBUG(0,("init_smb_request: invalid bcc number %u "
    531645                        "(wct = %u, size %u)\n",
     
    540654}
    541655
    542 static void process_smb(struct smbd_server_connection *conn,
     656static void process_smb(struct smbXsrv_connection *xconn,
    543657                        uint8_t *inbuf, size_t nread, size_t unread_bytes,
    544658                        uint32_t seqnum, bool encrypted,
    545659                        struct smb_perfcount_data *deferred_pcd);
    546660
    547 static void smbd_deferred_open_timer(struct event_context *ev,
    548                                      struct timed_event *te,
     661static void smbd_deferred_open_timer(struct tevent_context *ev,
     662                                     struct tevent_timer *te,
    549663                                     struct timeval _tval,
    550664                                     void *private_data)
     
    552666        struct pending_message_list *msg = talloc_get_type(private_data,
    553667                                           struct pending_message_list);
     668        struct smbd_server_connection *sconn = msg->sconn;
     669        struct smbXsrv_connection *xconn = msg->xconn;
    554670        TALLOC_CTX *mem_ctx = talloc_tos();
    555671        uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
     
    572688        msg->processed = true;
    573689
    574         process_smb(smbd_server_conn, inbuf,
     690        process_smb(xconn, inbuf,
    575691                    msg->buf.length, 0,
    576692                    msg->seqnum, msg->encrypted, &msg->pcd);
    577693
    578694        /* If it's still there and was processed, remove it. */
    579         msg = get_deferred_open_message_smb(mid);
     695        msg = get_deferred_open_message_smb(sconn, mid);
    580696        if (msg && msg->processed) {
    581                 remove_deferred_open_message_smb(mid);
     697                remove_deferred_open_message_smb(xconn, mid);
    582698        }
    583699}
     
    591707                                struct timeval request_time,
    592708                                struct timeval end_time,
    593                                 char *private_data, size_t private_len)
     709                                struct deferred_open_record *open_rec)
    594710{
    595711        int msg_len = smb_len(req->inbuf) + 4;
    596712        struct pending_message_list *msg;
    597713
    598         msg = TALLOC_ZERO_P(NULL, struct pending_message_list);
     714        msg = talloc_zero(NULL, struct pending_message_list);
    599715
    600716        if(msg == NULL) {
     
    602718                return False;
    603719        }
     720        msg->sconn = req->sconn;
     721        msg->xconn = req->xconn;
    604722
    605723        msg->buf = data_blob_talloc(msg, req->inbuf, msg_len);
     
    616734        SMB_PERFCOUNT_DEFER_OP(&req->pcd, &msg->pcd);
    617735
    618         if (private_data) {
    619                 msg->private_data = data_blob_talloc(msg, private_data,
    620                                                      private_len);
    621                 if (msg->private_data.data == NULL) {
    622                         DEBUG(0,("push_message: malloc fail (3)\n"));
    623                         TALLOC_FREE(msg);
    624                         return False;
    625                 }
    626         }
    627 
    628         msg->te = event_add_timed(smbd_event_context(),
    629                                   msg,
    630                                   end_time,
    631                                   smbd_deferred_open_timer,
    632                                   msg);
     736        if (open_rec) {
     737                msg->open_rec = talloc_move(msg, &open_rec);
     738        }
     739
     740#if 0
     741        msg->te = tevent_add_timer(msg->sconn->ev_ctx,
     742                                   msg,
     743                                   end_time,
     744                                   smbd_deferred_open_timer,
     745                                   msg);
    633746        if (!msg->te) {
    634747                DEBUG(0,("push_message: event_add_timed failed\n"));
     
    636749                return false;
    637750        }
    638 
    639         DLIST_ADD_END(deferred_open_queue, msg, struct pending_message_list *);
     751#endif
     752
     753        DLIST_ADD_END(req->sconn->deferred_open_queue, msg);
    640754
    641755        DEBUG(10,("push_message: pushed message length %u on "
     
    649763****************************************************************************/
    650764
    651 void remove_deferred_open_message_smb(uint64_t mid)
    652 {
     765void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     766                                      uint64_t mid)
     767{
     768        struct smbd_server_connection *sconn = xconn->client->sconn;
    653769        struct pending_message_list *pml;
    654770
    655         if (smbd_server_conn->using_smb2) {
    656                 remove_deferred_open_message_smb2(smbd_server_conn, mid);
     771        if (sconn->using_smb2) {
     772                remove_deferred_open_message_smb2(xconn, mid);
    657773                return;
    658774        }
    659775
    660         for (pml = deferred_open_queue; pml; pml = pml->next) {
     776        for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
    661777                if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
    662778                        DEBUG(10,("remove_deferred_open_message_smb: "
     
    664780                                  (unsigned long long)mid,
    665781                                  (unsigned int)pml->buf.length ));
    666                         DLIST_REMOVE(deferred_open_queue, pml);
     782                        DLIST_REMOVE(sconn->deferred_open_queue, pml);
    667783                        TALLOC_FREE(pml);
    668784                        return;
     
    676792****************************************************************************/
    677793
    678 void schedule_deferred_open_message_smb(uint64_t mid)
    679 {
     794bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     795                                        uint64_t mid)
     796{
     797        struct smbd_server_connection *sconn = xconn->client->sconn;
    680798        struct pending_message_list *pml;
    681799        int i = 0;
    682800
    683         if (smbd_server_conn->using_smb2) {
    684                 schedule_deferred_open_message_smb2(smbd_server_conn, mid);
    685                 return;
    686         }
    687 
    688         for (pml = deferred_open_queue; pml; pml = pml->next) {
     801        if (sconn->using_smb2) {
     802                return schedule_deferred_open_message_smb2(xconn, mid);
     803        }
     804
     805        for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
    689806                uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
    690807
     
    695812
    696813                if (mid == msg_mid) {
    697                         struct timed_event *te;
     814                        struct tevent_timer *te;
    698815
    699816                        if (pml->processed) {
     
    710827                                (unsigned long long)mid ));
    711828
    712                         te = event_add_timed(smbd_event_context(),
    713                                              pml,
    714                                              timeval_zero(),
    715                                              smbd_deferred_open_timer,
    716                                              pml);
     829                        te = tevent_add_timer(pml->sconn->ev_ctx,
     830                                              pml,
     831                                              timeval_zero(),
     832                                              smbd_deferred_open_timer,
     833                                              pml);
    717834                        if (!te) {
    718835                                DEBUG(10,("schedule_deferred_open_message_smb: "
     
    724841                        TALLOC_FREE(pml->te);
    725842                        pml->te = te;
    726                         DLIST_PROMOTE(deferred_open_queue, pml);
    727                         return;
     843                        DLIST_PROMOTE(sconn->deferred_open_queue, pml);
     844                        return true;
    728845                }
    729846        }
     
    732849                "find message mid %llu\n",
    733850                (unsigned long long)mid ));
     851
     852        return false;
    734853}
    735854
     
    738857****************************************************************************/
    739858
    740 bool open_was_deferred(uint64_t mid)
    741 {
     859bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
     860{
     861        struct smbd_server_connection *sconn = xconn->client->sconn;
    742862        struct pending_message_list *pml;
    743863
    744         if (smbd_server_conn->using_smb2) {
    745                 return open_was_deferred_smb2(smbd_server_conn, mid);
    746         }
    747 
    748         for (pml = deferred_open_queue; pml; pml = pml->next) {
     864        if (sconn->using_smb2) {
     865                return open_was_deferred_smb2(xconn, mid);
     866        }
     867
     868        for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
    749869                if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
    750870                        return True;
     
    758878****************************************************************************/
    759879
    760 static struct pending_message_list *get_deferred_open_message_smb(uint64_t mid)
     880static struct pending_message_list *get_deferred_open_message_smb(
     881        struct smbd_server_connection *sconn, uint64_t mid)
    761882{
    762883        struct pending_message_list *pml;
    763884
    764         for (pml = deferred_open_queue; pml; pml = pml->next) {
     885        for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
    765886                if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
    766887                        return pml;
     
    776897bool get_deferred_open_message_state(struct smb_request *smbreq,
    777898                                struct timeval *p_request_time,
    778                                 void **pp_state)
     899                                struct deferred_open_record **open_rec)
    779900{
    780901        struct pending_message_list *pml;
    781902
    782         if (smbd_server_conn->using_smb2) {
     903        if (smbreq->sconn->using_smb2) {
    783904                return get_deferred_open_message_state_smb2(smbreq->smb2req,
    784905                                        p_request_time,
    785                                         pp_state);
    786         }
    787 
    788         pml = get_deferred_open_message_smb(smbreq->mid);
     906                                        open_rec);
     907        }
     908
     909        pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
    789910        if (!pml) {
    790911                return false;
     
    793914                *p_request_time = pml->request_time;
    794915        }
    795         if (pp_state) {
    796                 *pp_state = (void *)pml->private_data.data;
     916        if (open_rec != NULL) {
     917                *open_rec = pml->open_rec;
    797918        }
    798919        return true;
     
    808929                               struct timeval timeout,
    809930                               struct file_id id,
    810                                char *private_data, size_t priv_len)
     931                               struct deferred_open_record *open_rec)
    811932{
    812933        struct timeval end_time;
     
    817938                                                timeout,
    818939                                                id,
    819                                                 private_data,
    820                                                 priv_len);
     940                                                open_rec);
    821941        }
    822942
     
    838958                (unsigned int)end_time.tv_usec));
    839959
    840         return push_queued_message(req, request_time, end_time,
    841                                    private_data, priv_len);
    842 }
    843 
    844 struct idle_event {
    845         struct timed_event *te;
    846         struct timeval interval;
    847         char *name;
    848         bool (*handler)(const struct timeval *now, void *private_data);
    849         void *private_data;
    850 };
    851 
    852 static void smbd_idle_event_handler(struct event_context *ctx,
    853                                     struct timed_event *te,
    854                                     struct timeval now,
    855                                     void *private_data)
    856 {
    857         struct idle_event *event =
    858                 talloc_get_type_abort(private_data, struct idle_event);
    859 
    860         TALLOC_FREE(event->te);
    861 
    862         DEBUG(10,("smbd_idle_event_handler: %s %p called\n",
    863                   event->name, event->te));
    864 
    865         if (!event->handler(&now, event->private_data)) {
    866                 DEBUG(10,("smbd_idle_event_handler: %s %p stopped\n",
    867                           event->name, event->te));
    868                 /* Don't repeat, delete ourselves */
    869                 TALLOC_FREE(event);
    870                 return;
    871         }
    872 
    873         DEBUG(10,("smbd_idle_event_handler: %s %p rescheduled\n",
    874                   event->name, event->te));
    875 
    876         event->te = event_add_timed(ctx, event,
    877                                     timeval_sum(&now, &event->interval),
    878                                     smbd_idle_event_handler, event);
    879 
    880         /* We can't do much but fail here. */
    881         SMB_ASSERT(event->te != NULL);
    882 }
    883 
    884 struct idle_event *event_add_idle(struct event_context *event_ctx,
    885                                   TALLOC_CTX *mem_ctx,
    886                                   struct timeval interval,
    887                                   const char *name,
    888                                   bool (*handler)(const struct timeval *now,
    889                                                   void *private_data),
     960        return push_queued_message(req, request_time, end_time, open_rec);
     961}
     962
     963static void smbd_sig_term_handler(struct tevent_context *ev,
     964                                  struct tevent_signal *se,
     965                                  int signum,
     966                                  int count,
     967                                  void *siginfo,
    890968                                  void *private_data)
    891969{
    892         struct idle_event *result;
    893         struct timeval now = timeval_current();
    894 
    895         result = TALLOC_P(mem_ctx, struct idle_event);
    896         if (result == NULL) {
    897                 DEBUG(0, ("talloc failed\n"));
    898                 return NULL;
    899         }
    900 
    901         result->interval = interval;
    902         result->handler = handler;
    903         result->private_data = private_data;
    904 
    905         if (!(result->name = talloc_asprintf(result, "idle_evt(%s)", name))) {
    906                 DEBUG(0, ("talloc failed\n"));
    907                 TALLOC_FREE(result);
    908                 return NULL;
    909         }
    910 
    911         result->te = event_add_timed(event_ctx, result,
    912                                      timeval_sum(&now, &interval),
    913                                      smbd_idle_event_handler, result);
    914         if (result->te == NULL) {
    915                 DEBUG(0, ("event_add_timed failed\n"));
    916                 TALLOC_FREE(result);
    917                 return NULL;
    918         }
    919 
    920         DEBUG(10,("event_add_idle: %s %p\n", result->name, result->te));
    921         return result;
    922 }
    923 
    924 static NTSTATUS smbd_server_connection_loop_once(struct smbd_server_connection *conn)
    925 {
    926         int timeout;
    927         int num_pfds = 0;
    928         int ret;
    929         bool retry;
    930 
    931         timeout = SMBD_SELECT_TIMEOUT * 1000;
    932 
    933         /*
    934          * Are there any timed events waiting ? If so, ensure we don't
    935          * select for longer than it would take to wait for them.
    936          */
    937 
    938         event_add_to_poll_args(smbd_event_context(), conn,
    939                                &conn->pfds, &num_pfds, &timeout);
    940 
    941         /* Process a signal and timed events now... */
    942         if (run_events_poll(smbd_event_context(), 0, NULL, 0)) {
    943                 return NT_STATUS_RETRY;
    944         }
    945 
    946         {
    947                 int sav;
    948                 START_PROFILE(smbd_idle);
    949 
    950                 ret = sys_poll(conn->pfds, num_pfds, timeout);
    951                 sav = errno;
    952 
    953                 END_PROFILE(smbd_idle);
    954                 errno = sav;
    955         }
    956 
    957         if (ret == -1) {
    958                 if (errno == EINTR) {
    959                         return NT_STATUS_RETRY;
    960                 }
    961                 return map_nt_error_from_unix(errno);
    962         }
    963 
    964         retry = run_events_poll(smbd_event_context(), ret, conn->pfds,
    965                                 num_pfds);
    966         if (retry) {
    967                 return NT_STATUS_RETRY;
    968         }
    969 
    970         /* Did we timeout ? */
    971         if (ret == 0) {
    972                 return NT_STATUS_RETRY;
    973         }
    974 
    975         /* should not be reached */
    976         return NT_STATUS_INTERNAL_ERROR;
     970        exit_server_cleanly("termination signal");
     971}
     972
     973void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
     974{
     975        struct tevent_signal *se;
     976
     977        se = tevent_add_signal(sconn->ev_ctx,
     978                               sconn,
     979                               SIGTERM, 0,
     980                               smbd_sig_term_handler,
     981                               sconn);
     982        if (!se) {
     983                exit_server("failed to setup SIGTERM handler");
     984        }
     985}
     986
     987static void smbd_sig_hup_handler(struct tevent_context *ev,
     988                                  struct tevent_signal *se,
     989                                  int signum,
     990                                  int count,
     991                                  void *siginfo,
     992                                  void *private_data)
     993{
     994        struct smbd_server_connection *sconn =
     995                talloc_get_type_abort(private_data,
     996                struct smbd_server_connection);
     997
     998        change_to_root_user();
     999        DEBUG(1,("Reloading services after SIGHUP\n"));
     1000        reload_services(sconn, conn_snum_used, false);
     1001}
     1002
     1003void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
     1004{
     1005        struct tevent_signal *se;
     1006
     1007        se = tevent_add_signal(sconn->ev_ctx,
     1008                               sconn,
     1009                               SIGHUP, 0,
     1010                               smbd_sig_hup_handler,
     1011                               sconn);
     1012        if (!se) {
     1013                exit_server("failed to setup SIGHUP handler");
     1014        }
     1015}
     1016
     1017static void smbd_conf_updated(struct messaging_context *msg,
     1018                              void *private_data,
     1019                              uint32_t msg_type,
     1020                              struct server_id server_id,
     1021                              DATA_BLOB *data)
     1022{
     1023        struct smbd_server_connection *sconn =
     1024                talloc_get_type_abort(private_data,
     1025                struct smbd_server_connection);
     1026
     1027        DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
     1028                  "updated. Reloading.\n"));
     1029        change_to_root_user();
     1030        reload_services(sconn, conn_snum_used, false);
    9771031}
    9781032
     
    12891343
    12901344static bool create_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
    1291                           const char *inbuf, char **outbuf, uint8_t num_words,
    1292                           uint32_t num_bytes)
    1293 {
     1345                          const uint8_t *inbuf, char **outbuf,
     1346                          uint8_t num_words, uint32_t num_bytes)
     1347{
     1348        size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
     1349
    12941350        /*
    1295          * Protect against integer wrap
    1296          */
    1297         if ((num_bytes > 0xffffff)
    1298             || ((num_bytes + smb_size + num_words*2) > 0xffffff)) {
     1351         * Protect against integer wrap.
     1352         * The SMB layer reply can be up to 0xFFFFFF bytes.
     1353         */
     1354        if ((num_bytes > 0xffffff) || (smb_len > 0xffffff)) {
    12991355                char *msg;
    13001356                if (asprintf(&msg, "num_bytes too large: %u",
    13011357                             (unsigned)num_bytes) == -1) {
    1302                         msg = CONST_DISCARD(char *, "num_bytes too large");
     1358                        msg = discard_const_p(char, "num_bytes too large");
    13031359                }
    13041360                smb_panic(msg);
    13051361        }
    13061362
    1307         *outbuf = TALLOC_ARRAY(mem_ctx, char,
    1308                                smb_size + num_words*2 + num_bytes);
     1363        /*
     1364         * Here we include the NBT header for now.
     1365         */
     1366        *outbuf = talloc_array(mem_ctx, char,
     1367                               NBT_HDR_SIZE + smb_len);
    13091368        if (*outbuf == NULL) {
    13101369                return false;
    13111370        }
    13121371
    1313         construct_reply_common(req, inbuf, *outbuf);
     1372        construct_reply_common(req->cmd, inbuf, *outbuf);
    13141373        srv_set_message(*outbuf, num_words, num_bytes, false);
    13151374        /*
     
    13181377         */
    13191378        if (num_words != 0) {
    1320                 memset(*outbuf + smb_vwv0, 0, num_words*2);
     1379                memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
    13211380        }
    13221381
     
    13241383}
    13251384
    1326 void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
     1385void reply_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
    13271386{
    13281387        char *outbuf;
    1329         if (!create_outbuf(req, req, (char *)req->inbuf, &outbuf, num_words,
     1388        if (!create_outbuf(req, req, req->inbuf, &outbuf, num_words,
    13301389                           num_bytes)) {
    13311390                smb_panic("could not allocate output buffer\n");
     
    13391398********************************************************************/
    13401399
    1341 static void smb_dump(const char *name, int type, const char *data, ssize_t len)
    1342 {
     1400static void smb_dump(const char *name, int type, const char *data)
     1401{
     1402        size_t len;
    13431403        int fd, i;
    13441404        char *fname = NULL;
     
    13471407        }
    13481408
    1349         if (len < 4) len = smb_len(data)+4;
     1409        len = smb_len_tcp(data)+4;
    13501410        for (i=1;i<100;i++) {
    1351                 if (asprintf(&fname, "/tmp/%s.%d.%s", name, i,
    1352                              type ? "req" : "resp") == -1) {
     1411                fname = talloc_asprintf(talloc_tos(),
     1412                                "/tmp/%s.%d.%s",
     1413                                name,
     1414                                i,
     1415                                type ? "req" : "resp");
     1416                if (fname == NULL) {
    13531417                        return;
    13541418                }
    13551419                fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
    13561420                if (fd != -1 || errno != EEXIST) break;
     1421                TALLOC_FREE(fname);
    13571422        }
    13581423        if (fd != -1) {
     
    13631428                DEBUG(0,("created %s len %lu\n", fname, (unsigned long)len));
    13641429        }
    1365         SAFE_FREE(fname);
     1430        TALLOC_FREE(fname);
     1431}
     1432
     1433static void smb1srv_update_crypto_flags(struct smbXsrv_session *session,
     1434                                        struct smb_request *req,
     1435                                        uint8_t type,
     1436                                        bool *update_session_globalp,
     1437                                        bool *update_tcon_globalp)
     1438{
     1439        connection_struct *conn = req->conn;
     1440        struct smbXsrv_tcon *tcon = conn ? conn->tcon : NULL;
     1441        uint8_t encrypt_flag = SMBXSRV_PROCESSED_UNENCRYPTED_PACKET;
     1442        uint8_t sign_flag = SMBXSRV_PROCESSED_UNSIGNED_PACKET;
     1443        bool update_session = false;
     1444        bool update_tcon = false;
     1445
     1446        if (req->encrypted) {
     1447                encrypt_flag = SMBXSRV_PROCESSED_ENCRYPTED_PACKET;
     1448        }
     1449
     1450        if (srv_is_signing_active(req->xconn)) {
     1451                sign_flag = SMBXSRV_PROCESSED_SIGNED_PACKET;
     1452        } else if ((type == SMBecho) || (type == SMBsesssetupX)) {
     1453                /*
     1454                 * echo can be unsigned. Sesssion setup except final
     1455                 * session setup response too
     1456                 */
     1457                sign_flag &= ~SMBXSRV_PROCESSED_UNSIGNED_PACKET;
     1458        }
     1459
     1460        update_session |= smbXsrv_set_crypto_flag(
     1461                &session->global->encryption_flags, encrypt_flag);
     1462        update_session |= smbXsrv_set_crypto_flag(
     1463                &session->global->signing_flags, sign_flag);
     1464
     1465        if (tcon) {
     1466                update_tcon |= smbXsrv_set_crypto_flag(
     1467                        &tcon->global->encryption_flags, encrypt_flag);
     1468                update_tcon |= smbXsrv_set_crypto_flag(
     1469                        &tcon->global->signing_flags, sign_flag);
     1470        }
     1471
     1472        if (update_session) {
     1473                session->global->channels[0].encryption_cipher = SMB_ENCRYPTION_GSSAPI;
     1474        }
     1475
     1476        *update_session_globalp = update_session;
     1477        *update_tcon_globalp = update_tcon;
     1478        return;
    13661479}
    13671480
     
    13791492****************************************************************************/
    13801493
    1381 static connection_struct *switch_message(uint8 type, struct smb_request *req, int size)
     1494static connection_struct *switch_message(uint8_t type, struct smb_request *req)
    13821495{
    13831496        int flags;
    1384         uint16 session_tag;
     1497        uint64_t session_tag;
    13851498        connection_struct *conn = NULL;
    1386         struct smbd_server_connection *sconn = req->sconn;
     1499        struct smbXsrv_connection *xconn = req->xconn;
     1500        NTTIME now = timeval_to_nttime(&req->request_time);
     1501        struct smbXsrv_session *session = NULL;
     1502        NTSTATUS status;
    13871503
    13881504        errno = 0;
    13891505
    1390         /* Make sure this is an SMB packet. smb_size contains NetBIOS header
    1391          * so subtract 4 from it. */
    1392         if ((size < (smb_size - 4)) ||
    1393             !valid_smb_header(req->inbuf)) {
    1394                 DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
    1395                          smb_len(req->inbuf)));
    1396                 exit_server_cleanly("Non-SMB packet");
     1506        if (!xconn->smb1.negprot.done) {
     1507                switch (type) {
     1508                        /*
     1509                         * Without a negprot the request must
     1510                         * either be a negprot, or one of the
     1511                         * evil old SMB mailslot messaging types.
     1512                         */
     1513                        case SMBnegprot:
     1514                        case SMBsendstrt:
     1515                        case SMBsendend:
     1516                        case SMBsendtxt:
     1517                                break;
     1518                        default:
     1519                                exit_server_cleanly("The first request "
     1520                                        "should be a negprot");
     1521                }
    13971522        }
    13981523
    13991524        if (smb_messages[type].fn == NULL) {
    14001525                DEBUG(0,("Unknown message type %d!\n",type));
    1401                 smb_dump("Unknown", 1, (char *)req->inbuf, size);
     1526                smb_dump("Unknown", 1, (const char *)req->inbuf);
    14021527                reply_unknown_new(req, type);
    14031528                return NULL;
     
    14071532
    14081533        /* In share mode security we must ignore the vuid. */
    1409         session_tag = (lp_security() == SEC_SHARE)
    1410                 ? UID_FIELD_INVALID : req->vuid;
     1534        session_tag = req->vuid;
    14111535        conn = req->conn;
    14121536
    14131537        DEBUG(3,("switch message %s (pid %d) conn 0x%lx\n", smb_fn_name(type),
    1414                  (int)sys_getpid(), (unsigned long)conn));
    1415 
    1416         smb_dump(smb_fn_name(type), 1, (char *)req->inbuf, size);
     1538                 (int)getpid(), (unsigned long)conn));
     1539
     1540        smb_dump(smb_fn_name(type), 1, (const char *)req->inbuf);
    14171541
    14181542        /* Ensure this value is replaced in the incoming packet. */
    1419         SSVAL(req->inbuf,smb_uid,session_tag);
     1543        SSVAL(discard_const_p(uint8_t, req->inbuf),smb_uid,session_tag);
    14201544
    14211545        /*
     
    14281552         */
    14291553
    1430         if (session_tag != sconn->smb1.sessions.last_session_tag) {
    1431                 user_struct *vuser = NULL;
    1432 
    1433                 sconn->smb1.sessions.last_session_tag = session_tag;
    1434                 if(session_tag != UID_FIELD_INVALID) {
    1435                         vuser = get_valid_user_struct(sconn, session_tag);
    1436                         if (vuser) {
    1437                                 set_current_user_info(
    1438                                         vuser->session_info->sanitized_username,
    1439                                         vuser->session_info->unix_name,
    1440                                         vuser->session_info->info3->base.domain.string);
    1441                         }
     1554        /*
     1555         * lookup an existing session
     1556         *
     1557         * Note: for now we only check for NT_STATUS_NETWORK_SESSION_EXPIRED
     1558         * here, the main check is still in change_to_user()
     1559         */
     1560        status = smb1srv_session_lookup(xconn,
     1561                                        session_tag,
     1562                                        now,
     1563                                        &session);
     1564        if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
     1565                switch (type) {
     1566                case SMBsesssetupX:
     1567                        status = NT_STATUS_OK;
     1568                        break;
     1569                default:
     1570                        DEBUG(1,("Error: session %llu is expired, mid=%llu.\n",
     1571                                 (unsigned long long)session_tag,
     1572                                 (unsigned long long)req->mid));
     1573                        reply_nterror(req, NT_STATUS_NETWORK_SESSION_EXPIRED);
     1574                        return conn;
     1575                }
     1576        }
     1577
     1578        if (session_tag != xconn->client->last_session_id) {
     1579                struct user_struct *vuser = NULL;
     1580
     1581                xconn->client->last_session_id = session_tag;
     1582                if (session) {
     1583                        vuser = session->compat;
     1584                }
     1585                if (vuser) {
     1586                        set_current_user_info(
     1587                                vuser->session_info->unix_info->sanitized_username,
     1588                                vuser->session_info->unix_info->unix_name,
     1589                                vuser->session_info->info->domain_name);
    14421590                }
    14431591        }
     
    14911639                        conn->encrypted_tid = true;
    14921640                        /* encrypted required from now on. */
    1493                         conn->encrypt_level = Required;
     1641                        conn->encrypt_level = SMB_SIGNING_REQUIRED;
    14941642                } else if (ENCRYPTION_REQUIRED(conn)) {
    14951643                        if (req->cmd != SMBtrans2 && req->cmd != SMBtranss2) {
    1496                                 exit_server_cleanly("encryption required "
    1497                                         "on connection");
     1644                                DEBUG(1,("service[%s] requires encryption"
     1645                                        "%s ACCESS_DENIED. mid=%llu\n",
     1646                                        lp_servicename(talloc_tos(), SNUM(conn)),
     1647                                        smb_fn_name(type),
     1648                                        (unsigned long long)req->mid));
     1649                                reply_nterror(req, NT_STATUS_ACCESS_DENIED);
    14981650                                return conn;
    14991651                        }
     
    15091661        }
    15101662
    1511         /* does this protocol need to be run as guest? */
    1512         if ((flags & AS_GUEST)
    1513             && (!change_to_guest() ||
    1514                 !allow_access(lp_hostsdeny(-1), lp_hostsallow(-1),
    1515                               sconn->client_id.name,
    1516                               sconn->client_id.addr))) {
    1517                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
    1518                 return conn;
     1663        /*
     1664         * Does this protocol need to be run as guest? (Only archane
     1665         * messenger service requests have this...)
     1666         */
     1667        if (flags & AS_GUEST) {
     1668                char *raddr;
     1669                bool ok;
     1670
     1671                if (!change_to_guest()) {
     1672                        reply_nterror(req, NT_STATUS_ACCESS_DENIED);
     1673                        return conn;
     1674                }
     1675
     1676                raddr = tsocket_address_inet_addr_string(xconn->remote_address,
     1677                                                         talloc_tos());
     1678                if (raddr == NULL) {
     1679                        reply_nterror(req, NT_STATUS_NO_MEMORY);
     1680                        return conn;
     1681                }
     1682
     1683                /*
     1684                 * Haven't we checked this in smbd_process already???
     1685                 */
     1686
     1687                ok = allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
     1688                                  xconn->remote_hostname, raddr);
     1689                TALLOC_FREE(raddr);
     1690
     1691                if (!ok) {
     1692                        reply_nterror(req, NT_STATUS_ACCESS_DENIED);
     1693                        return conn;
     1694                }
     1695        }
     1696
     1697        /*
     1698         * Update encryption and signing state tracking flags that are
     1699         * used by smbstatus to display signing and encryption status.
     1700         */
     1701        if (session != NULL) {
     1702                bool update_session_global = false;
     1703                bool update_tcon_global = false;
     1704
     1705                smb1srv_update_crypto_flags(session, req, type,
     1706                                            &update_session_global,
     1707                                            &update_tcon_global);
     1708
     1709                if (update_session_global) {
     1710                        status = smbXsrv_session_update(session);
     1711                        if (!NT_STATUS_IS_OK(status)) {
     1712                                reply_nterror(req, NT_STATUS_UNSUCCESSFUL);
     1713                                return conn;
     1714                        }
     1715                }
     1716
     1717                if (update_tcon_global) {
     1718                        status = smbXsrv_tcon_update(req->conn->tcon);
     1719                        if (!NT_STATUS_IS_OK(status)) {
     1720                                reply_nterror(req, NT_STATUS_UNSUCCESSFUL);
     1721                                return conn;
     1722                        }
     1723                }
    15191724        }
    15201725
     
    15271732****************************************************************************/
    15281733
    1529 static void construct_reply(struct smbd_server_connection *sconn,
     1734static void construct_reply(struct smbXsrv_connection *xconn,
    15301735                            char *inbuf, int size, size_t unread_bytes,
    15311736                            uint32_t seqnum, bool encrypted,
    15321737                            struct smb_perfcount_data *deferred_pcd)
    15331738{
    1534         connection_struct *conn;
     1739        struct smbd_server_connection *sconn = xconn->client->sconn;
    15351740        struct smb_request *req;
    15361741
     
    15391744        }
    15401745
    1541         if (!init_smb_request(req, sconn, (uint8 *)inbuf, unread_bytes,
     1746        if (!init_smb_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
    15421747                              encrypted, seqnum)) {
    15431748                exit_server_cleanly("Invalid SMB request");
     
    15551760        }
    15561761
    1557         conn = switch_message(req->cmd, req, size);
    1558 
    1559         if (req->unread_bytes) {
    1560                 /* writeX failed. drain socket. */
    1561                 if (drain_socket(req->sconn->sock, req->unread_bytes) !=
    1562                                 req->unread_bytes) {
    1563                         smb_panic("failed to drain pending bytes");
    1564                 }
    1565                 req->unread_bytes = 0;
    1566         }
    1567 
    1568         if (req->done) {
    1569                 TALLOC_FREE(req);
     1762        req->conn = switch_message(req->cmd, req);
     1763
     1764        if (req->outbuf == NULL) {
     1765                /*
     1766                 * Request has suspended itself, will come
     1767                 * back here.
     1768                 */
    15701769                return;
    15711770        }
    1572 
    1573         if (req->outbuf == NULL) {
    1574                 return;
    1575         }
    1576 
    15771771        if (CVAL(req->outbuf,0) == 0) {
    15781772                show_msg((char *)req->outbuf);
    15791773        }
    1580 
    1581         if (!srv_send_smb(req->sconn,
    1582                         (char *)req->outbuf,
    1583                         true, req->seqnum+1,
    1584                         IS_CONN_ENCRYPTED(conn)||req->encrypted,
    1585                         &req->pcd)) {
    1586                 exit_server_cleanly("construct_reply: srv_send_smb failed.");
    1587         }
    1588 
    1589         TALLOC_FREE(req);
    1590 
     1774        smb_request_done(req);
     1775}
     1776
     1777static void construct_reply_chain(struct smbXsrv_connection *xconn,
     1778                                  char *inbuf, int size, uint32_t seqnum,
     1779                                  bool encrypted,
     1780                                  struct smb_perfcount_data *deferred_pcd)
     1781{
     1782        struct smb_request **reqs = NULL;
     1783        struct smb_request *req;
     1784        unsigned num_reqs;
     1785        bool ok;
     1786
     1787        ok = smb1_parse_chain(talloc_tos(), (uint8_t *)inbuf, xconn, encrypted,
     1788                              seqnum, &reqs, &num_reqs);
     1789        if (!ok) {
     1790                char errbuf[smb_size];
     1791                error_packet(errbuf, 0, 0, NT_STATUS_INVALID_PARAMETER,
     1792                             __LINE__, __FILE__);
     1793                if (!srv_send_smb(xconn, errbuf, true, seqnum, encrypted,
     1794                                  NULL)) {
     1795                        exit_server_cleanly("construct_reply_chain: "
     1796                                            "srv_send_smb failed.");
     1797                }
     1798                return;
     1799        }
     1800
     1801        req = reqs[0];
     1802        req->inbuf = (uint8_t *)talloc_move(reqs, &inbuf);
     1803
     1804        req->conn = switch_message(req->cmd, req);
     1805
     1806        if (req->outbuf == NULL) {
     1807                /*
     1808                 * Request has suspended itself, will come
     1809                 * back here.
     1810                 */
     1811                return;
     1812        }
     1813        smb_request_done(req);
     1814}
     1815
     1816/*
     1817 * To be called from an async SMB handler that is potentially chained
     1818 * when it is finished for shipping.
     1819 */
     1820
     1821void smb_request_done(struct smb_request *req)
     1822{
     1823        struct smb_request **reqs = NULL;
     1824        struct smb_request *first_req;
     1825        size_t i, num_reqs, next_index;
     1826        NTSTATUS status;
     1827
     1828        if (req->chain == NULL) {
     1829                first_req = req;
     1830                goto shipit;
     1831        }
     1832
     1833        reqs = req->chain;
     1834        num_reqs = talloc_array_length(reqs);
     1835
     1836        for (i=0; i<num_reqs; i++) {
     1837                if (reqs[i] == req) {
     1838                        break;
     1839                }
     1840        }
     1841        if (i == num_reqs) {
     1842                /*
     1843                 * Invalid chain, should not happen
     1844                 */
     1845                status = NT_STATUS_INTERNAL_ERROR;
     1846                goto error;
     1847        }
     1848        next_index = i+1;
     1849
     1850        while ((next_index < num_reqs) && (IVAL(req->outbuf, smb_rcls) == 0)) {
     1851                struct smb_request *next = reqs[next_index];
     1852                struct smbXsrv_tcon *tcon;
     1853                NTTIME now = timeval_to_nttime(&req->request_time);
     1854
     1855                next->vuid = SVAL(req->outbuf, smb_uid);
     1856                next->tid  = SVAL(req->outbuf, smb_tid);
     1857                status = smb1srv_tcon_lookup(req->xconn, req->tid,
     1858                                             now, &tcon);
     1859                if (NT_STATUS_IS_OK(status)) {
     1860                        req->conn = tcon->compat;
     1861                } else {
     1862                        req->conn = NULL;
     1863                }
     1864                next->chain_fsp = req->chain_fsp;
     1865                next->inbuf = req->inbuf;
     1866
     1867                req = next;
     1868                req->conn = switch_message(req->cmd, req);
     1869
     1870                if (req->outbuf == NULL) {
     1871                        /*
     1872                         * Request has suspended itself, will come
     1873                         * back here.
     1874                         */
     1875                        return;
     1876                }
     1877                next_index += 1;
     1878        }
     1879
     1880        first_req = reqs[0];
     1881
     1882        for (i=1; i<next_index; i++) {
     1883                bool ok;
     1884
     1885                ok = smb_splice_chain(&first_req->outbuf, reqs[i]->outbuf);
     1886                if (!ok) {
     1887                        status = NT_STATUS_INTERNAL_ERROR;
     1888                        goto error;
     1889                }
     1890        }
     1891
     1892        SSVAL(first_req->outbuf, smb_uid, SVAL(req->outbuf, smb_uid));
     1893        SSVAL(first_req->outbuf, smb_tid, SVAL(req->outbuf, smb_tid));
     1894
     1895        /*
     1896         * This scary statement intends to set the
     1897         * FLAGS2_32_BIT_ERROR_CODES flg2 field in first_req->outbuf
     1898         * to the value last_req->outbuf carries
     1899         */
     1900        SSVAL(first_req->outbuf, smb_flg2,
     1901              (SVAL(first_req->outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
     1902              |(SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
     1903
     1904        /*
     1905         * Transfer the error codes from the subrequest to the main one
     1906         */
     1907        SSVAL(first_req->outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
     1908        SSVAL(first_req->outbuf, smb_err,  SVAL(req->outbuf, smb_err));
     1909
     1910        _smb_setlen_large(
     1911                first_req->outbuf, talloc_get_size(first_req->outbuf) - 4);
     1912
     1913shipit:
     1914        if (!srv_send_smb(first_req->xconn,
     1915                          (char *)first_req->outbuf,
     1916                          true, first_req->seqnum+1,
     1917                          IS_CONN_ENCRYPTED(req->conn)||first_req->encrypted,
     1918                          &first_req->pcd)) {
     1919                exit_server_cleanly("construct_reply_chain: srv_send_smb "
     1920                                    "failed.");
     1921        }
     1922        TALLOC_FREE(req);       /* non-chained case */
     1923        TALLOC_FREE(reqs);      /* chained case */
    15911924        return;
     1925
     1926error:
     1927        {
     1928                char errbuf[smb_size];
     1929                error_packet(errbuf, 0, 0, status, __LINE__, __FILE__);
     1930                if (!srv_send_smb(req->xconn, errbuf, true,
     1931                                  req->seqnum+1, req->encrypted,
     1932                                  NULL)) {
     1933                        exit_server_cleanly("construct_reply_chain: "
     1934                                            "srv_send_smb failed.");
     1935                }
     1936        }
     1937        TALLOC_FREE(req);       /* non-chained case */
     1938        TALLOC_FREE(reqs);      /* chained case */
    15921939}
    15931940
     
    15951942 Process an smb from the client
    15961943****************************************************************************/
    1597 static void process_smb(struct smbd_server_connection *sconn,
     1944static void process_smb(struct smbXsrv_connection *xconn,
    15981945                        uint8_t *inbuf, size_t nread, size_t unread_bytes,
    15991946                        uint32_t seqnum, bool encrypted,
    16001947                        struct smb_perfcount_data *deferred_pcd)
    16011948{
     1949        struct smbd_server_connection *sconn = xconn->client->sconn;
    16021950        int msg_type = CVAL(inbuf,0);
    16031951
    1604         DO_PROFILE_INC(smb_count);
     1952        DO_PROFILE_INC(request);
    16051953
    16061954        DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
     
    16091957                  sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
    16101958
    1611         if (msg_type != 0) {
     1959        if (msg_type != NBSSmessage) {
    16121960                /*
    16131961                 * NetBIOS session request, keepalive, etc.
    16141962                 */
    1615                 reply_special(sconn, (char *)inbuf, nread);
     1963                reply_special(xconn, (char *)inbuf, nread);
    16161964                goto done;
    16171965        }
     
    16211969                 * we make the decision here.. */
    16221970                if (smbd_is_smb2_header(inbuf, nread)) {
    1623                         smbd_smb2_first_negprot(sconn, inbuf, nread);
     1971                        const uint8_t *inpdu = inbuf + NBT_HDR_SIZE;
     1972                        size_t pdulen = nread - NBT_HDR_SIZE;
     1973                        smbd_smb2_process_negprot(xconn, 0, inpdu, pdulen);
    16241974                        return;
    16251975                } else if (nread >= smb_size && valid_smb_header(inbuf)
     
    16311981        }
    16321982
     1983        /* Make sure this is an SMB packet. smb_size contains NetBIOS header
     1984         * so subtract 4 from it. */
     1985        if ((nread < (smb_size - 4)) || !valid_smb_header(inbuf)) {
     1986                DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
     1987                         smb_len(inbuf)));
     1988
     1989                /* special magic for immediate exit */
     1990                if ((nread == 9) &&
     1991                    (IVAL(inbuf, 4) == 0x74697865) &&
     1992                    lp_parm_bool(-1, "smbd", "suicide mode", false)) {
     1993                        uint8_t exitcode = CVAL(inbuf, 8);
     1994                        DEBUG(1, ("Exiting immediately with code %d\n",
     1995                                  (int)exitcode));
     1996                        exit(exitcode);
     1997                }
     1998
     1999                exit_server_cleanly("Non-SMB packet");
     2000        }
     2001
    16332002        show_msg((char *)inbuf);
    16342003
    1635         construct_reply(sconn, (char *)inbuf, nread, unread_bytes, seqnum,
    1636                         encrypted, deferred_pcd);
     2004        if ((unread_bytes == 0) && smb1_is_chain(inbuf)) {
     2005                construct_reply_chain(xconn, (char *)inbuf, nread,
     2006                                      seqnum, encrypted, deferred_pcd);
     2007        } else {
     2008                construct_reply(xconn, (char *)inbuf, nread, unread_bytes,
     2009                                seqnum, encrypted, deferred_pcd);
     2010        }
     2011
    16372012        sconn->trans_num++;
    16382013
     
    16722047****************************************************************************/
    16732048
    1674 void add_to_common_flags2(uint32 v)
     2049void add_to_common_flags2(uint32_t v)
    16752050{
    16762051        common_flags2 |= v;
    16772052}
    16782053
    1679 void remove_from_common_flags2(uint32 v)
     2054void remove_from_common_flags2(uint32_t v)
    16802055{
    16812056        common_flags2 &= ~v;
    16822057}
    16832058
    1684 static void construct_reply_common(struct smb_request *req, const char *inbuf,
     2059static void construct_reply_common(uint8_t cmd, const uint8_t *inbuf,
    16852060                                   char *outbuf)
    16862061{
     2062        uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
     2063        uint16_t out_flags2 = common_flags2;
     2064
     2065        out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
     2066        out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
     2067        out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
     2068
    16872069        srv_set_message(outbuf,0,0,false);
    16882070
    1689         SCVAL(outbuf, smb_com, req->cmd);
     2071        SCVAL(outbuf, smb_com, cmd);
    16902072        SIVAL(outbuf,smb_rcls,0);
    16912073        SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES));
    1692         SSVAL(outbuf,smb_flg2,
    1693                 (SVAL(inbuf,smb_flg2) & FLAGS2_UNICODE_STRINGS) |
    1694                 common_flags2);
     2074        SSVAL(outbuf,smb_flg2, out_flags2);
    16952075        memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
     2076        memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
    16962077
    16972078        SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
     
    17032084void construct_reply_common_req(struct smb_request *req, char *outbuf)
    17042085{
    1705         construct_reply_common(req, (char *)req->inbuf, outbuf);
    1706 }
    1707 
    1708 /*
    1709  * How many bytes have we already accumulated up to the current wct field
    1710  * offset?
    1711  */
    1712 
    1713 size_t req_wct_ofs(struct smb_request *req)
    1714 {
    1715         size_t buf_size;
    1716 
    1717         if (req->chain_outbuf == NULL) {
    1718                 return smb_wct - 4;
    1719         }
    1720         buf_size = talloc_get_size(req->chain_outbuf);
    1721         if ((buf_size % 4) != 0) {
    1722                 buf_size += (4 - (buf_size % 4));
    1723         }
    1724         return buf_size - 4;
    1725 }
    1726 
    1727 /*
    1728  * Hack around reply_nterror & friends not being aware of chained requests,
    1729  * generating illegal (i.e. wct==0) chain replies.
    1730  */
    1731 
    1732 static void fixup_chain_error_packet(struct smb_request *req)
    1733 {
    1734         uint8_t *outbuf = req->outbuf;
    1735         req->outbuf = NULL;
    1736         reply_outbuf(req, 2, 0);
    1737         memcpy(req->outbuf, outbuf, smb_wct);
    1738         TALLOC_FREE(outbuf);
    1739         SCVAL(req->outbuf, smb_vwv0, 0xff);
     2086        construct_reply_common(req->cmd, req->inbuf, outbuf);
    17402087}
    17412088
     
    17572104        cmd = CVAL(buf, smb_com);
    17582105
    1759         SMB_ASSERT(is_andx_req(cmd));
     2106        if (!is_andx_req(cmd)) {
     2107                return false;
     2108        }
    17602109
    17612110        ofs = smb_vwv0;
     
    17732122                ofs = SVAL(buf, ofs+2) + 4 + 1;
    17742123
    1775                 SMB_ASSERT(ofs+4 < talloc_get_size(buf));
     2124                if (ofs+4 >= talloc_get_size(buf)) {
     2125                        return false;
     2126                }
    17762127        }
    17772128
     
    17832134 * @brief Do the smb chaining at a buffer level
    17842135 * @param[in] poutbuf           Pointer to the talloc'ed buffer to be modified
    1785  * @param[in] smb_command       The command that we want to issue
    1786  * @param[in] wct               How many words?
    1787  * @param[in] vwv               The words, already in network order
    1788  * @param[in] bytes_alignment   How shall we align "bytes"?
    1789  * @param[in] num_bytes         How many bytes?
    1790  * @param[in] bytes             The data the request ships
    1791  *
    1792  * smb_splice_chain() adds the vwv and bytes to the request already present in
    1793  * *poutbuf.
     2136 * @param[in] andx_buf          Buffer to be appended
    17942137 */
    17952138
    1796 static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
    1797                              uint8_t wct, const uint16_t *vwv,
    1798                              size_t bytes_alignment,
    1799                              uint32_t num_bytes, const uint8_t *bytes)
    1800 {
     2139static bool smb_splice_chain(uint8_t **poutbuf, const uint8_t *andx_buf)
     2140{
     2141        uint8_t smb_command     = CVAL(andx_buf, smb_com);
     2142        uint8_t wct             = CVAL(andx_buf, smb_wct);
     2143        const uint16_t *vwv     = (const uint16_t *)(andx_buf + smb_vwv);
     2144        uint32_t num_bytes      = smb_buflen(andx_buf);
     2145        const uint8_t *bytes    = (const uint8_t *)smb_buf_const(andx_buf);
     2146
    18012147        uint8_t *outbuf;
    18022148        size_t old_size, new_size;
    18032149        size_t ofs;
    18042150        size_t chain_padding = 0;
    1805         size_t bytes_padding = 0;
    1806         bool first_request;
     2151        size_t andx_cmd_ofs;
     2152
    18072153
    18082154        old_size = talloc_get_size(*poutbuf);
    18092155
    1810         /*
    1811          * old_size == smb_wct means we're pushing the first request in for
    1812          * libsmb/
    1813          */
    1814 
    1815         first_request = (old_size == smb_wct);
    1816 
    1817         if (!first_request && ((old_size % 4) != 0)) {
     2156        if ((old_size % 4) != 0) {
    18182157                /*
    18192158                 * Align the wct field of subsequent requests to a 4-byte
     
    18252164        /*
    18262165         * After the old request comes the new wct field (1 byte), the vwv's
    1827          * and the num_bytes field. After at we might need to align the bytes
    1828          * given to us to "bytes_alignment", increasing the num_bytes value.
     2166         * and the num_bytes field.
    18292167         */
    18302168
    18312169        new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
    1832 
    1833         if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
    1834                 bytes_padding = bytes_alignment - (new_size % bytes_alignment);
    1835         }
    1836 
    1837         new_size += bytes_padding + num_bytes;
     2170        new_size += num_bytes;
    18382171
    18392172        if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
    1840                 DEBUG(1, ("splice_chain: %u bytes won't fit\n",
     2173                DEBUG(1, ("smb_splice_chain: %u bytes won't fit\n",
    18412174                          (unsigned)new_size));
    18422175                return false;
    18432176        }
    18442177
    1845         outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, uint8_t, new_size);
     2178        outbuf = talloc_realloc(NULL, *poutbuf, uint8_t, new_size);
    18462179        if (outbuf == NULL) {
    18472180                DEBUG(0, ("talloc failed\n"));
     
    18502183        *poutbuf = outbuf;
    18512184
    1852         if (first_request) {
    1853                 SCVAL(outbuf, smb_com, smb_command);
    1854         } else {
    1855                 size_t andx_cmd_ofs;
    1856 
    1857                 if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
    1858                         DEBUG(1, ("invalid command chain\n"));
    1859                         *poutbuf = TALLOC_REALLOC_ARRAY(
    1860                                 NULL, *poutbuf, uint8_t, old_size);
    1861                         return false;
    1862                 }
    1863 
    1864                 if (chain_padding != 0) {
    1865                         memset(outbuf + old_size, 0, chain_padding);
    1866                         old_size += chain_padding;
    1867                 }
    1868 
    1869                 SCVAL(outbuf, andx_cmd_ofs, smb_command);
    1870                 SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
    1871         }
     2185        if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
     2186                DEBUG(1, ("invalid command chain\n"));
     2187                *poutbuf = talloc_realloc(NULL, *poutbuf, uint8_t, old_size);
     2188                return false;
     2189        }
     2190
     2191        if (chain_padding != 0) {
     2192                memset(outbuf + old_size, 0, chain_padding);
     2193                old_size += chain_padding;
     2194        }
     2195
     2196        SCVAL(outbuf, andx_cmd_ofs, smb_command);
     2197        SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
    18722198
    18732199        ofs = old_size;
     
    18872213
    18882214        memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
     2215
     2216        /*
     2217         * HACK ALERT
     2218         *
     2219         * Read&X has an offset into its data buffer at
     2220         * vwv[6]. reply_read_andx has no idea anymore that it's
     2221         * running from within a chain, so we have to fix up the
     2222         * offset here.
     2223         *
     2224         * Although it looks disgusting at this place, I want to keep
     2225         * it here. The alternative would be to push knowledge about
     2226         * the andx chain down into read&x again.
     2227         */
     2228
     2229        if (smb_command == SMBreadX) {
     2230                uint8_t *bytes_addr;
     2231
     2232                if (wct < 7) {
     2233                        /*
     2234                         * Invalid read&x response
     2235                         */
     2236                        return false;
     2237                }
     2238
     2239                bytes_addr = outbuf + ofs        /* vwv start */
     2240                        + sizeof(uint16_t) * wct /* vwv array */
     2241                        + sizeof(uint16_t)       /* bcc */
     2242                        + 1;                     /* padding byte */
     2243
     2244                SSVAL(outbuf + ofs, 6 * sizeof(uint16_t),
     2245                      bytes_addr - outbuf - 4);
     2246        }
     2247
    18892248        ofs += sizeof(uint16_t) * wct;
    18902249
     
    18932252         */
    18942253
    1895         SSVAL(outbuf, ofs, num_bytes + bytes_padding);
     2254        SSVAL(outbuf, ofs, num_bytes);
    18962255        ofs += sizeof(uint16_t);
    1897 
    1898         /*
    1899          * padding
    1900          */
    1901 
    1902         if (bytes_padding != 0) {
    1903                 memset(outbuf + ofs, 0, bytes_padding);
    1904                 ofs += bytes_padding;
    1905         }
    19062256
    19072257        /*
     
    19142264}
    19152265
    1916 /****************************************************************************
    1917  Construct a chained reply and add it to the already made reply
    1918 ****************************************************************************/
    1919 
    1920 void chain_reply(struct smb_request *req)
    1921 {
    1922         size_t smblen = smb_len(req->inbuf);
    1923         size_t already_used, length_needed;
    1924         uint8_t chain_cmd;
    1925         uint32_t chain_offset;  /* uint32_t to avoid overflow */
    1926 
     2266bool smb1_is_chain(const uint8_t *buf)
     2267{
     2268        uint8_t cmd, wct, andx_cmd;
     2269
     2270        cmd = CVAL(buf, smb_com);
     2271        if (!is_andx_req(cmd)) {
     2272                return false;
     2273        }
     2274        wct = CVAL(buf, smb_wct);
     2275        if (wct < 2) {
     2276                return false;
     2277        }
     2278        andx_cmd = CVAL(buf, smb_vwv);
     2279        return (andx_cmd != 0xFF);
     2280}
     2281
     2282bool smb1_walk_chain(const uint8_t *buf,
     2283                     bool (*fn)(uint8_t cmd,
     2284                                uint8_t wct, const uint16_t *vwv,
     2285                                uint16_t num_bytes, const uint8_t *bytes,
     2286                                void *private_data),
     2287                     void *private_data)
     2288{
     2289        size_t smblen = smb_len(buf);
     2290        const char *smb_buf = smb_base(buf);
     2291        uint8_t cmd, chain_cmd;
    19272292        uint8_t wct;
    1928         uint16_t *vwv;
    1929         uint16_t buflen;
    1930         uint8_t *buf;
    1931 
    1932         if (IVAL(req->outbuf, smb_rcls) != 0) {
    1933                 fixup_chain_error_packet(req);
    1934         }
    1935 
    1936         /*
    1937          * Any of the AndX requests and replies have at least a wct of
    1938          * 2. vwv[0] is the next command, vwv[1] is the offset from the
    1939          * beginning of the SMB header to the next wct field.
    1940          *
    1941          * None of the AndX requests put anything valuable in vwv[0] and [1],
    1942          * so we can overwrite it here to form the chain.
    1943          */
    1944 
    1945         if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
    1946                 if (req->chain_outbuf == NULL) {
    1947                         req->chain_outbuf = TALLOC_REALLOC_ARRAY(
    1948                                 req, req->outbuf, uint8_t,
    1949                                 smb_len(req->outbuf) + 4);
    1950                         if (req->chain_outbuf == NULL) {
    1951                                 smb_panic("talloc failed");
    1952                         }
    1953                 }
    1954                 req->outbuf = NULL;
    1955                 goto error;
    1956         }
    1957 
    1958         /*
    1959          * Here we assume that this is the end of the chain. For that we need
    1960          * to set "next command" to 0xff and the offset to 0. If we later find
    1961          * more commands in the chain, this will be overwritten again.
    1962          */
    1963 
    1964         SCVAL(req->outbuf, smb_vwv0, 0xff);
    1965         SCVAL(req->outbuf, smb_vwv0+1, 0);
    1966         SSVAL(req->outbuf, smb_vwv1, 0);
    1967 
    1968         if (req->chain_outbuf == NULL) {
     2293        const uint16_t *vwv;
     2294        uint16_t num_bytes;
     2295        const uint8_t *bytes;
     2296
     2297        cmd = CVAL(buf, smb_com);
     2298        wct = CVAL(buf, smb_wct);
     2299        vwv = (const uint16_t *)(buf + smb_vwv);
     2300        num_bytes = smb_buflen(buf);
     2301        bytes = (const uint8_t *)smb_buf_const(buf);
     2302
     2303        if (!fn(cmd, wct, vwv, num_bytes, bytes, private_data)) {
     2304                return false;
     2305        }
     2306
     2307        if (!is_andx_req(cmd)) {
     2308                return true;
     2309        }
     2310        if (wct < 2) {
     2311                return false;
     2312        }
     2313
     2314        chain_cmd = CVAL(vwv, 0);
     2315
     2316        while (chain_cmd != 0xff) {
     2317                uint32_t chain_offset;  /* uint32_t to avoid overflow */
     2318                size_t length_needed;
     2319                ptrdiff_t vwv_offset;
     2320
     2321                chain_offset = SVAL(vwv+1, 0);
     2322
    19692323                /*
    1970                  * In req->chain_outbuf we collect all the replies. Start the
    1971                  * chain by copying in the first reply.
    1972                  *
    1973                  * We do the realloc because later on we depend on
    1974                  * talloc_get_size to determine the length of
    1975                  * chain_outbuf. The reply_xxx routines might have
    1976                  * over-allocated (reply_pipe_read_and_X used to be such an
    1977                  * example).
     2324                 * Check if the client tries to fool us. The chain
     2325                 * offset needs to point beyond the current request in
     2326                 * the chain, it needs to strictly grow. Otherwise we
     2327                 * might be tricked into an endless loop always
     2328                 * processing the same request over and over again. We
     2329                 * used to assume that vwv and the byte buffer array
     2330                 * in a chain are always attached, but OS/2 the
     2331                 * Write&X/Read&X chain puts the Read&X vwv array
     2332                 * right behind the Write&X vwv chain. The Write&X bcc
     2333                 * array is put behind the Read&X vwv array. So now we
     2334                 * check whether the chain offset points strictly
     2335                 * behind the previous vwv array. req->buf points
     2336                 * right after the vwv array of the previous
     2337                 * request. See
     2338                 * https://bugzilla.samba.org/show_bug.cgi?id=8360 for
     2339                 * more information.
    19782340                 */
    1979                 req->chain_outbuf = TALLOC_REALLOC_ARRAY(
    1980                         req, req->outbuf, uint8_t,
    1981                         smb_len_large(req->outbuf) + 4);
    1982                 if (req->chain_outbuf == NULL) {
    1983                         smb_panic("talloc failed");
    1984                 }
    1985                 req->outbuf = NULL;
    1986         } else {
     2341
     2342                vwv_offset = ((const char *)vwv - smb_buf);
     2343                if (chain_offset <= vwv_offset) {
     2344                        return false;
     2345                }
     2346
    19872347                /*
    1988                  * Update smb headers where subsequent chained commands
    1989                  * may have updated them.
     2348                 * Next check: Make sure the chain offset does not
     2349                 * point beyond the overall smb request length.
    19902350                 */
    1991                 SSVAL(req->chain_outbuf, smb_tid, SVAL(req->outbuf, smb_tid));
    1992                 SSVAL(req->chain_outbuf, smb_uid, SVAL(req->outbuf, smb_uid));
    1993 
    1994                 if (!smb_splice_chain(&req->chain_outbuf,
    1995                                       CVAL(req->outbuf, smb_com),
    1996                                       CVAL(req->outbuf, smb_wct),
    1997                                       (uint16_t *)(req->outbuf + smb_vwv),
    1998                                       0, smb_buflen(req->outbuf),
    1999                                       (uint8_t *)smb_buf(req->outbuf))) {
    2000                         goto error;
    2001                 }
    2002                 TALLOC_FREE(req->outbuf);
    2003         }
    2004 
    2005         /*
    2006          * We use the old request's vwv field to grab the next chained command
    2007          * and offset into the chained fields.
    2008          */
    2009 
    2010         chain_cmd = CVAL(req->vwv+0, 0);
    2011         chain_offset = SVAL(req->vwv+1, 0);
    2012 
    2013         if (chain_cmd == 0xff) {
     2351
     2352                length_needed = chain_offset+1; /* wct */
     2353                if (length_needed > smblen) {
     2354                        return false;
     2355                }
     2356
    20142357                /*
    2015                  * End of chain, no more requests from the client. So ship the
    2016                  * replies.
     2358                 * Now comes the pointer magic. Goal here is to set up
     2359                 * vwv and buf correctly again. The chain offset (the
     2360                 * former vwv[1]) points at the new wct field.
    20172361                 */
    2018                 smb_setlen((char *)(req->chain_outbuf),
    2019                            talloc_get_size(req->chain_outbuf) - 4);
    2020 
    2021                 if (!srv_send_smb(req->sconn, (char *)req->chain_outbuf,
    2022                                   true, req->seqnum+1,
    2023                                   IS_CONN_ENCRYPTED(req->conn)
    2024                                   ||req->encrypted,
    2025                                   &req->pcd)) {
    2026                         exit_server_cleanly("chain_reply: srv_send_smb "
    2027                                             "failed.");
    2028                 }
    2029                 TALLOC_FREE(req->chain_outbuf);
    2030                 req->done = true;
    2031                 return;
    2032         }
    2033 
    2034         /* add a new perfcounter for this element of chain */
    2035         SMB_PERFCOUNT_ADD(&req->pcd);
    2036         SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd);
    2037         SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen);
    2038 
    2039         /*
    2040          * Check if the client tries to fool us. The chain offset
    2041          * needs to point beyond the current request in the chain, it
    2042          * needs to strictly grow. Otherwise we might be tricked into
    2043          * an endless loop always processing the same request over and
    2044          * over again. We used to assume that vwv and the byte buffer
    2045          * array in a chain are always attached, but OS/2 the
    2046          * Write&X/Read&X chain puts the Read&X vwv array right behind
    2047          * the Write&X vwv chain. The Write&X bcc array is put behind
    2048          * the Read&X vwv array. So now we check whether the chain
    2049          * offset points strictly behind the previous vwv
    2050          * array. req->buf points right after the vwv array of the
    2051          * previous request. See
    2052          * https://bugzilla.samba.org/show_bug.cgi?id=8360 for more
    2053          * information.
    2054          */
    2055 
    2056         already_used = PTR_DIFF(req->buf, smb_base(req->inbuf));
    2057         if (chain_offset <= already_used) {
    2058                 goto error;
    2059         }
    2060 
    2061         /*
    2062          * Next check: Make sure the chain offset does not point beyond the
    2063          * overall smb request length.
    2064          */
    2065 
    2066         length_needed = chain_offset+1; /* wct */
    2067         if (length_needed > smblen) {
    2068                 goto error;
    2069         }
    2070 
    2071         /*
    2072          * Now comes the pointer magic. Goal here is to set up req->vwv and
    2073          * req->buf correctly again to be able to call the subsequent
    2074          * switch_message(). The chain offset (the former vwv[1]) points at
    2075          * the new wct field.
    2076          */
    2077 
    2078         wct = CVAL(smb_base(req->inbuf), chain_offset);
    2079 
    2080         /*
    2081          * Next consistency check: Make the new vwv array fits in the overall
    2082          * smb request.
    2083          */
    2084 
    2085         length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
    2086         if (length_needed > smblen) {
    2087                 goto error;
    2088         }
    2089         vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
    2090 
    2091         /*
    2092          * Now grab the new byte buffer....
    2093          */
    2094 
    2095         buflen = SVAL(vwv+wct, 0);
    2096 
    2097         /*
    2098          * .. and check that it fits.
    2099          */
    2100 
    2101         length_needed += buflen;
    2102         if (length_needed > smblen) {
    2103                 goto error;
    2104         }
    2105         buf = (uint8_t *)(vwv+wct+1);
    2106 
    2107         req->cmd = chain_cmd;
     2362
     2363                wct = CVAL(smb_buf, chain_offset);
     2364
     2365                if (is_andx_req(chain_cmd) && (wct < 2)) {
     2366                        return false;
     2367                }
     2368
     2369                /*
     2370                 * Next consistency check: Make the new vwv array fits
     2371                 * in the overall smb request.
     2372                 */
     2373
     2374                length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
     2375                if (length_needed > smblen) {
     2376                        return false;
     2377                }
     2378                vwv = (const uint16_t *)(smb_buf + chain_offset + 1);
     2379
     2380                /*
     2381                 * Now grab the new byte buffer....
     2382                 */
     2383
     2384                num_bytes = SVAL(vwv+wct, 0);
     2385
     2386                /*
     2387                 * .. and check that it fits.
     2388                 */
     2389
     2390                length_needed += num_bytes;
     2391                if (length_needed > smblen) {
     2392                        return false;
     2393                }
     2394                bytes = (const uint8_t *)(vwv+wct+1);
     2395
     2396                if (!fn(chain_cmd, wct, vwv, num_bytes, bytes, private_data)) {
     2397                        return false;
     2398                }
     2399
     2400                if (!is_andx_req(chain_cmd)) {
     2401                        return true;
     2402                }
     2403                chain_cmd = CVAL(vwv, 0);
     2404        }
     2405        return true;
     2406}
     2407
     2408static bool smb1_chain_length_cb(uint8_t cmd,
     2409                                 uint8_t wct, const uint16_t *vwv,
     2410                                 uint16_t num_bytes, const uint8_t *bytes,
     2411                                 void *private_data)
     2412{
     2413        unsigned *count = (unsigned *)private_data;
     2414        *count += 1;
     2415        return true;
     2416}
     2417
     2418unsigned smb1_chain_length(const uint8_t *buf)
     2419{
     2420        unsigned count = 0;
     2421
     2422        if (!smb1_walk_chain(buf, smb1_chain_length_cb, &count)) {
     2423                return 0;
     2424        }
     2425        return count;
     2426}
     2427
     2428struct smb1_parse_chain_state {
     2429        TALLOC_CTX *mem_ctx;
     2430        const uint8_t *buf;
     2431        struct smbd_server_connection *sconn;
     2432        struct smbXsrv_connection *xconn;
     2433        bool encrypted;
     2434        uint32_t seqnum;
     2435
     2436        struct smb_request **reqs;
     2437        unsigned num_reqs;
     2438};
     2439
     2440static bool smb1_parse_chain_cb(uint8_t cmd,
     2441                                uint8_t wct, const uint16_t *vwv,
     2442                                uint16_t num_bytes, const uint8_t *bytes,
     2443                                void *private_data)
     2444{
     2445        struct smb1_parse_chain_state *state =
     2446                (struct smb1_parse_chain_state *)private_data;
     2447        struct smb_request **reqs;
     2448        struct smb_request *req;
     2449        bool ok;
     2450
     2451        reqs = talloc_realloc(state->mem_ctx, state->reqs,
     2452                              struct smb_request *, state->num_reqs+1);
     2453        if (reqs == NULL) {
     2454                return false;
     2455        }
     2456        state->reqs = reqs;
     2457
     2458        req = talloc(reqs, struct smb_request);
     2459        if (req == NULL) {
     2460                return false;
     2461        }
     2462
     2463        ok = init_smb_request(req, state->sconn, state->xconn, state->buf, 0,
     2464                              state->encrypted, state->seqnum);
     2465        if (!ok) {
     2466                return false;
     2467        }
     2468        req->cmd = cmd;
    21082469        req->wct = wct;
    21092470        req->vwv = vwv;
    2110         req->buflen = buflen;
    2111         req->buf = buf;
    2112 
    2113         switch_message(chain_cmd, req, smblen);
    2114 
    2115         if (req->outbuf == NULL) {
    2116                 /*
    2117                  * This happens if the chained command has suspended itself or
    2118                  * if it has called srv_send_smb() itself.
    2119                  */
    2120                 return;
    2121         }
    2122 
    2123         /*
    2124          * We end up here if the chained command was not itself chained or
    2125          * suspended, but for example a close() command. We now need to splice
    2126          * the chained commands' outbuf into the already built up chain_outbuf
    2127          * and ship the result.
    2128          */
    2129         goto done;
    2130 
    2131  error:
    2132         /*
    2133          * We end up here if there's any error in the chain syntax. Report a
    2134          * DOS error, just like Windows does.
    2135          */
    2136         reply_force_doserror(req, ERRSRV, ERRerror);
    2137         fixup_chain_error_packet(req);
    2138 
    2139  done:
    2140         /*
    2141          * This scary statement intends to set the
    2142          * FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf
    2143          * to the value req->outbuf carries
    2144          */
    2145         SSVAL(req->chain_outbuf, smb_flg2,
    2146               (SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
    2147               | (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
    2148 
    2149         /*
    2150          * Transfer the error codes from the subrequest to the main one
    2151          */
    2152         SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
    2153         SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err));
    2154 
    2155         if (!smb_splice_chain(&req->chain_outbuf,
    2156                               CVAL(req->outbuf, smb_com),
    2157                               CVAL(req->outbuf, smb_wct),
    2158                               (uint16_t *)(req->outbuf + smb_vwv),
    2159                               0, smb_buflen(req->outbuf),
    2160                               (uint8_t *)smb_buf(req->outbuf))) {
    2161                 exit_server_cleanly("chain_reply: smb_splice_chain failed\n");
    2162         }
    2163         TALLOC_FREE(req->outbuf);
    2164 
    2165         smb_setlen((char *)(req->chain_outbuf),
    2166                    talloc_get_size(req->chain_outbuf) - 4);
    2167 
    2168         show_msg((char *)(req->chain_outbuf));
    2169 
    2170         if (!srv_send_smb(req->sconn, (char *)req->chain_outbuf,
    2171                           true, req->seqnum+1,
    2172                           IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
    2173                           &req->pcd)) {
    2174                 exit_server_cleanly("chain_reply: srv_send_smb failed.");
    2175         }
    2176         TALLOC_FREE(req->chain_outbuf);
    2177         req->done = true;
     2471        req->buflen = num_bytes;
     2472        req->buf = bytes;
     2473
     2474        reqs[state->num_reqs] = req;
     2475        state->num_reqs += 1;
     2476        return true;
     2477}
     2478
     2479bool smb1_parse_chain(TALLOC_CTX *mem_ctx, const uint8_t *buf,
     2480                      struct smbXsrv_connection *xconn,
     2481                      bool encrypted, uint32_t seqnum,
     2482                      struct smb_request ***reqs, unsigned *num_reqs)
     2483{
     2484        struct smbd_server_connection *sconn = NULL;
     2485        struct smb1_parse_chain_state state;
     2486        unsigned i;
     2487
     2488        if (xconn != NULL) {
     2489                sconn = xconn->client->sconn;
     2490        }
     2491
     2492        state.mem_ctx = mem_ctx;
     2493        state.buf = buf;
     2494        state.sconn = sconn;
     2495        state.xconn = xconn;
     2496        state.encrypted = encrypted;
     2497        state.seqnum = seqnum;
     2498        state.reqs = NULL;
     2499        state.num_reqs = 0;
     2500
     2501        if (!smb1_walk_chain(buf, smb1_parse_chain_cb, &state)) {
     2502                TALLOC_FREE(state.reqs);
     2503                return false;
     2504        }
     2505        for (i=0; i<state.num_reqs; i++) {
     2506                state.reqs[i]->chain = state.reqs;
     2507        }
     2508        *reqs = state.reqs;
     2509        *num_reqs = state.num_reqs;
     2510        return true;
    21782511}
    21792512
     
    21902523
    21912524        if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
    2192                 reload_services(sconn->msg_ctx, sconn->sock, True);
     2525                reload_services(sconn, conn_snum_used, true);
    21932526                last_smb_conf_reload_time = t;
    21942527        }
     
    22052538}
    22062539
    2207 static void smbd_server_connection_write_handler(struct smbd_server_connection *conn)
     2540static void smbd_server_connection_write_handler(
     2541        struct smbXsrv_connection *xconn)
    22082542{
    22092543        /* TODO: make write nonblocking */
     
    22112545
    22122546static void smbd_server_connection_read_handler(
    2213         struct smbd_server_connection *conn, int fd)
     2547        struct smbXsrv_connection *xconn, int fd)
    22142548{
    22152549        uint8_t *inbuf = NULL;
     
    22212555        uint32_t seqnum;
    22222556
    2223         bool from_client = (conn->sock == fd);
    2224 
    2225         if (from_client) {
    2226                 smbd_lock_socket(conn);
    2227 
    2228                 if (lp_async_smb_echo_handler() && !fd_is_readable(fd)) {
     2557        bool async_echo = lp_async_smb_echo_handler();
     2558        bool from_client = false;
     2559
     2560        if (async_echo) {
     2561                if (fd_is_readable(xconn->smb1.echo_handler.trusted_fd)) {
     2562                        /*
     2563                         * This is the super-ugly hack to prefer the packets
     2564                         * forwarded by the echo handler over the ones by the
     2565                         * client directly
     2566                         */
     2567                        fd = xconn->smb1.echo_handler.trusted_fd;
     2568                }
     2569        }
     2570
     2571        from_client = (xconn->transport.sock == fd);
     2572
     2573        if (async_echo && from_client) {
     2574                smbd_lock_socket(xconn);
     2575
     2576                if (!fd_is_readable(fd)) {
    22292577                        DEBUG(10,("the echo listener was faster\n"));
    2230                         smbd_unlock_socket(conn);
     2578                        smbd_unlock_socket(xconn);
    22312579                        return;
    22322580                }
    2233 
    2234                 /* TODO: make this completely nonblocking */
    2235                 status = receive_smb_talloc(mem_ctx, conn, fd,
    2236                                             (char **)(void *)&inbuf,
    2237                                             0, /* timeout */
    2238                                             &unread_bytes,
    2239                                             &encrypted,
    2240                                             &inbuf_len, &seqnum,
    2241                                             false /* trusted channel */);
    2242                 smbd_unlock_socket(conn);
    2243         } else {
    2244                 /* TODO: make this completely nonblocking */
    2245                 status = receive_smb_talloc(mem_ctx, conn, fd,
    2246                                             (char **)(void *)&inbuf,
    2247                                             0, /* timeout */
    2248                                             &unread_bytes,
    2249                                             &encrypted,
    2250                                             &inbuf_len, &seqnum,
    2251                                             true /* trusted channel */);
     2581        }
     2582
     2583        /* TODO: make this completely nonblocking */
     2584        status = receive_smb_talloc(mem_ctx, xconn, fd,
     2585                                    (char **)(void *)&inbuf,
     2586                                    0, /* timeout */
     2587                                    &unread_bytes,
     2588                                    &encrypted,
     2589                                    &inbuf_len, &seqnum,
     2590                                    !from_client /* trusted channel */);
     2591
     2592        if (async_echo && from_client) {
     2593                smbd_unlock_socket(xconn);
    22522594        }
    22532595
     
    22632605
    22642606process:
    2265         process_smb(conn, inbuf, inbuf_len, unread_bytes,
     2607        process_smb(xconn, inbuf, inbuf_len, unread_bytes,
    22662608                    seqnum, encrypted, NULL);
    22672609}
    22682610
    2269 static void smbd_server_connection_handler(struct event_context *ev,
    2270                                            struct fd_event *fde,
     2611static void smbd_server_connection_handler(struct tevent_context *ev,
     2612                                           struct tevent_fd *fde,
    22712613                                           uint16_t flags,
    22722614                                           void *private_data)
    22732615{
    2274         struct smbd_server_connection *conn = talloc_get_type(private_data,
    2275                                               struct smbd_server_connection);
    2276 
    2277         if (flags & EVENT_FD_WRITE) {
    2278                 smbd_server_connection_write_handler(conn);
     2616        struct smbXsrv_connection *xconn =
     2617                talloc_get_type_abort(private_data,
     2618                struct smbXsrv_connection);
     2619
     2620        if (!NT_STATUS_IS_OK(xconn->transport.status)) {
     2621                /*
     2622                 * we're not supposed to do any io
     2623                 */
     2624                TEVENT_FD_NOT_READABLE(xconn->transport.fde);
     2625                TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
    22792626                return;
    22802627        }
    2281         if (flags & EVENT_FD_READ) {
    2282                 smbd_server_connection_read_handler(conn, conn->sock);
     2628
     2629        if (flags & TEVENT_FD_WRITE) {
     2630                smbd_server_connection_write_handler(xconn);
    22832631                return;
    22842632        }
    2285 }
    2286 
    2287 static void smbd_server_echo_handler(struct event_context *ev,
    2288                                      struct fd_event *fde,
     2633        if (flags & TEVENT_FD_READ) {
     2634                smbd_server_connection_read_handler(xconn, xconn->transport.sock);
     2635                return;
     2636        }
     2637}
     2638
     2639static void smbd_server_echo_handler(struct tevent_context *ev,
     2640                                     struct tevent_fd *fde,
    22892641                                     uint16_t flags,
    22902642                                     void *private_data)
    22912643{
    2292         struct smbd_server_connection *conn = talloc_get_type(private_data,
    2293                                               struct smbd_server_connection);
    2294 
    2295         if (flags & EVENT_FD_WRITE) {
    2296                 smbd_server_connection_write_handler(conn);
     2644        struct smbXsrv_connection *xconn =
     2645                talloc_get_type_abort(private_data,
     2646                struct smbXsrv_connection);
     2647
     2648        if (!NT_STATUS_IS_OK(xconn->transport.status)) {
     2649                /*
     2650                 * we're not supposed to do any io
     2651                 */
     2652                TEVENT_FD_NOT_READABLE(xconn->smb1.echo_handler.trusted_fde);
     2653                TEVENT_FD_NOT_WRITEABLE(xconn->smb1.echo_handler.trusted_fde);
    22972654                return;
    22982655        }
    2299         if (flags & EVENT_FD_READ) {
     2656
     2657        if (flags & TEVENT_FD_WRITE) {
     2658                smbd_server_connection_write_handler(xconn);
     2659                return;
     2660        }
     2661        if (flags & TEVENT_FD_READ) {
    23002662                smbd_server_connection_read_handler(
    2301                         conn, conn->smb1.echo_handler.trusted_fd);
     2663                        xconn, xconn->smb1.echo_handler.trusted_fd);
    23022664                return;
    23032665        }
     2666}
     2667
     2668struct smbd_release_ip_state {
     2669        struct smbXsrv_connection *xconn;
     2670        struct tevent_immediate *im;
     2671        char addr[INET6_ADDRSTRLEN];
     2672};
     2673
     2674static void smbd_release_ip_immediate(struct tevent_context *ctx,
     2675                                      struct tevent_immediate *im,
     2676                                      void *private_data)
     2677{
     2678        struct smbd_release_ip_state *state =
     2679                talloc_get_type_abort(private_data,
     2680                struct smbd_release_ip_state);
     2681        struct smbXsrv_connection *xconn = state->xconn;
     2682
     2683        if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
     2684                /*
     2685                 * smbd_server_connection_terminate() already triggered ?
     2686                 */
     2687                return;
     2688        }
     2689
     2690        smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
    23042691}
    23052692
     
    23072694received when we should release a specific IP
    23082695****************************************************************************/
    2309 static void release_ip(const char *ip, void *priv)
    2310 {
    2311         const char *addr = (const char *)priv;
     2696static int release_ip(uint32_t src_vnn, uint32_t dst_vnn,
     2697                      uint64_t dst_srvid,
     2698                      const uint8_t *msg, size_t msglen,
     2699                      void *private_data)
     2700{
     2701        struct smbd_release_ip_state *state =
     2702                talloc_get_type_abort(private_data,
     2703                struct smbd_release_ip_state);
     2704        struct smbXsrv_connection *xconn = state->xconn;
     2705        const char *ip;
     2706        const char *addr = state->addr;
    23122707        const char *p = addr;
     2708
     2709        if (msglen == 0) {
     2710                return 0;
     2711        }
     2712        if (msg[msglen-1] != '\0') {
     2713                return 0;
     2714        }
     2715
     2716        ip = (const char *)msg;
     2717
     2718        if (!NT_STATUS_IS_OK(xconn->transport.status)) {
     2719                /* avoid recursion */
     2720                return 0;
     2721        }
    23132722
    23142723        if (strncmp("::ffff:", addr, 7) == 0) {
     
    23202729
    23212730        if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
    2322                 /* we can't afford to do a clean exit - that involves
    2323                    database writes, which would potentially mean we
    2324                    are still running after the failover has finished -
    2325                    we have to get rid of this process ID straight
    2326                    away */
    23272731                DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
    23282732                        ip));
    2329                 /* note we must exit with non-zero status so the unclean handler gets
    2330                    called in the parent, so that the brl database is tickled */
    2331                 _exit(1);
    2332         }
    2333 }
    2334 
    2335 static void msg_release_ip(struct messaging_context *msg_ctx, void *private_data,
    2336                            uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
     2733                /*
     2734                 * With SMB2 we should do a clean disconnect,
     2735                 * the previous_session_id in the session setup
     2736                 * will cleanup the old session, tcons and opens.
     2737                 *
     2738                 * A clean disconnect is needed in order to support
     2739                 * durable handles.
     2740                 *
     2741                 * Note: typically this is never triggered
     2742                 *       as we got a TCP RST (triggered by ctdb event scripts)
     2743                 *       before we get CTDB_SRVID_RELEASE_IP.
     2744                 *
     2745                 * We used to call _exit(1) here, but as this was mostly never
     2746                 * triggered and has implication on our process model,
     2747                 * we can just use smbd_server_connection_terminate()
     2748                 * (also for SMB1).
     2749                 *
     2750                 * We don't call smbd_server_connection_terminate() directly
     2751                 * as we might be called from within ctdbd_migrate(),
     2752                 * we need to defer our action to the next event loop
     2753                 */
     2754                tevent_schedule_immediate(state->im, xconn->ev_ctx,
     2755                                          smbd_release_ip_immediate, state);
     2756
     2757                /*
     2758                 * Make sure we don't get any io on the connection.
     2759                 */
     2760                xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
     2761                return EADDRNOTAVAIL;
     2762        }
     2763
     2764        return 0;
     2765}
     2766
     2767static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
     2768                                  struct sockaddr_storage *srv,
     2769                                  struct sockaddr_storage *clnt)
     2770{
     2771        struct smbd_release_ip_state *state;
     2772        struct ctdbd_connection *cconn;
     2773        int ret;
     2774
     2775        cconn = messaging_ctdbd_connection();
     2776        if (cconn == NULL) {
     2777                return NT_STATUS_NO_MEMORY;
     2778        }
     2779
     2780        state = talloc_zero(xconn, struct smbd_release_ip_state);
     2781        if (state == NULL) {
     2782                return NT_STATUS_NO_MEMORY;
     2783        }
     2784        state->xconn = xconn;
     2785        state->im = tevent_create_immediate(state);
     2786        if (state->im == NULL) {
     2787                return NT_STATUS_NO_MEMORY;
     2788        }
     2789        if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
     2790                return NT_STATUS_NO_MEMORY;
     2791        }
     2792
     2793        ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
     2794        if (ret != 0) {
     2795                return map_nt_error_from_unix(ret);
     2796        }
     2797        return NT_STATUS_OK;
     2798}
     2799
     2800static void msg_kill_client_ip(struct messaging_context *msg_ctx,
     2801                                  void *private_data, uint32_t msg_type,
     2802                                  struct server_id server_id, DATA_BLOB *data)
    23372803{
    23382804        struct smbd_server_connection *sconn = talloc_get_type_abort(
    23392805                private_data, struct smbd_server_connection);
    2340 
    2341         release_ip((char *)data->data, sconn->client_id.addr);
    2342 }
    2343 
    2344 #ifdef CLUSTER_SUPPORT
    2345 static int client_get_tcp_info(int sock, struct sockaddr_storage *server,
    2346                                struct sockaddr_storage *client)
    2347 {
    2348         socklen_t length;
    2349         length = sizeof(*server);
    2350         if (getsockname(sock, (struct sockaddr *)server, &length) != 0) {
    2351                 return -1;
    2352         }
    2353         length = sizeof(*client);
    2354         if (getpeername(sock, (struct sockaddr *)client, &length) != 0) {
    2355                 return -1;
    2356         }
    2357         return 0;
    2358 }
    2359 #endif
     2806        const char *ip = (char *) data->data;
     2807        char *client_ip;
     2808
     2809        DBG_DEBUG("Got kill request for client IP %s\n", ip);
     2810
     2811        client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
     2812                                                     talloc_tos());
     2813        if (client_ip == NULL) {
     2814                return;
     2815        }
     2816
     2817        if (strequal(ip, client_ip)) {
     2818                DBG_WARNING("Got kill client message for %s - "
     2819                            "exiting immediately\n", ip);
     2820                exit_server_cleanly("Forced disconnect for client");
     2821        }
     2822
     2823        TALLOC_FREE(client_ip);
     2824}
    23602825
    23612826/*
     
    23642829static bool keepalive_fn(const struct timeval *now, void *private_data)
    23652830{
    2366         struct smbd_server_connection *sconn = smbd_server_conn;
     2831        struct smbd_server_connection *sconn = talloc_get_type_abort(
     2832                private_data, struct smbd_server_connection);
     2833        struct smbXsrv_connection *xconn = NULL;
    23672834        bool ret;
    23682835
     
    23722839        }
    23732840
    2374         smbd_lock_socket(smbd_server_conn);
    2375         ret = send_keepalive(sconn->sock);
    2376         smbd_unlock_socket(smbd_server_conn);
     2841        /*
     2842         * With SMB1 we only have 1 connection
     2843         */
     2844        xconn = sconn->client->connections;
     2845        smbd_lock_socket(xconn);
     2846        ret = send_keepalive(xconn->transport.sock);
     2847        smbd_unlock_socket(xconn);
    23772848
    23782849        if (!ret) {
    2379                 char addr[INET6_ADDRSTRLEN];
     2850                int saved_errno = errno;
    23802851                /*
    23812852                 * Try and give an error message saying what
     
    23842855                DEBUG(0, ("send_keepalive failed for client %s. "
    23852856                          "Error %s - exiting\n",
    2386                           get_peer_addr(sconn->sock, addr, sizeof(addr)),
    2387                           strerror(errno)));
     2857                          smbXsrv_connection_dbg(xconn),
     2858                          strerror(saved_errno)));
     2859                errno = saved_errno;
    23882860                return False;
    23892861        }
     
    24302902        check_reload(sconn, time_mono(NULL));
    24312903
    2432         /* Change machine password if neccessary. */
    2433         attempt_machine_password_change();
    2434 
    24352904        /*
    24362905         * Force a log file check.
     
    24412910}
    24422911
    2443 static int create_unlink_tmp(const char *dir)
    2444 {
    2445         char *fname;
    2446         int fd;
    2447 
    2448         fname = talloc_asprintf(talloc_tos(), "%s/listenerlock_XXXXXX", dir);
    2449         if (fname == NULL) {
    2450                 errno = ENOMEM;
    2451                 return -1;
    2452         }
    2453         fd = mkstemp(fname);
    2454         if (fd == -1) {
    2455                 TALLOC_FREE(fname);
    2456                 return -1;
    2457         }
    2458         if (unlink(fname) == -1) {
    2459                 int sys_errno = errno;
    2460                 close(fd);
    2461                 TALLOC_FREE(fname);
    2462                 errno = sys_errno;
    2463                 return -1;
    2464         }
    2465         TALLOC_FREE(fname);
    2466         return fd;
     2912/*
     2913 * Read an smb packet in the echo handler child, giving the parent
     2914 * smbd one second to react once the socket becomes readable.
     2915 */
     2916
     2917struct smbd_echo_read_state {
     2918        struct tevent_context *ev;
     2919        struct smbXsrv_connection *xconn;
     2920
     2921        char *buf;
     2922        size_t buflen;
     2923        uint32_t seqnum;
     2924};
     2925
     2926static void smbd_echo_read_readable(struct tevent_req *subreq);
     2927static void smbd_echo_read_waited(struct tevent_req *subreq);
     2928
     2929static struct tevent_req *smbd_echo_read_send(
     2930        TALLOC_CTX *mem_ctx, struct tevent_context *ev,
     2931        struct smbXsrv_connection *xconn)
     2932{
     2933        struct tevent_req *req, *subreq;
     2934        struct smbd_echo_read_state *state;
     2935
     2936        req = tevent_req_create(mem_ctx, &state,
     2937                                struct smbd_echo_read_state);
     2938        if (req == NULL) {
     2939                return NULL;
     2940        }
     2941        state->ev = ev;
     2942        state->xconn = xconn;
     2943
     2944        subreq = wait_for_read_send(state, ev, xconn->transport.sock, false);
     2945        if (tevent_req_nomem(subreq, req)) {
     2946                return tevent_req_post(req, ev);
     2947        }
     2948        tevent_req_set_callback(subreq, smbd_echo_read_readable, req);
     2949        return req;
     2950}
     2951
     2952static void smbd_echo_read_readable(struct tevent_req *subreq)
     2953{
     2954        struct tevent_req *req = tevent_req_callback_data(
     2955                subreq, struct tevent_req);
     2956        struct smbd_echo_read_state *state = tevent_req_data(
     2957                req, struct smbd_echo_read_state);
     2958        bool ok;
     2959        int err;
     2960
     2961        ok = wait_for_read_recv(subreq, &err);
     2962        TALLOC_FREE(subreq);
     2963        if (!ok) {
     2964                tevent_req_nterror(req, map_nt_error_from_unix(err));
     2965                return;
     2966        }
     2967
     2968        /*
     2969         * Give the parent smbd one second to step in
     2970         */
     2971
     2972        subreq = tevent_wakeup_send(
     2973                state, state->ev, timeval_current_ofs(1, 0));
     2974        if (tevent_req_nomem(subreq, req)) {
     2975                return;
     2976        }
     2977        tevent_req_set_callback(subreq, smbd_echo_read_waited, req);
     2978}
     2979
     2980static void smbd_echo_read_waited(struct tevent_req *subreq)
     2981{
     2982        struct tevent_req *req = tevent_req_callback_data(
     2983                subreq, struct tevent_req);
     2984        struct smbd_echo_read_state *state = tevent_req_data(
     2985                req, struct smbd_echo_read_state);
     2986        struct smbXsrv_connection *xconn = state->xconn;
     2987        bool ok;
     2988        NTSTATUS status;
     2989        size_t unread = 0;
     2990        bool encrypted;
     2991
     2992        ok = tevent_wakeup_recv(subreq);
     2993        TALLOC_FREE(subreq);
     2994        if (!ok) {
     2995                tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
     2996                return;
     2997        }
     2998
     2999        ok = smbd_lock_socket_internal(xconn);
     3000        if (!ok) {
     3001                tevent_req_nterror(req, map_nt_error_from_unix(errno));
     3002                DEBUG(0, ("%s: failed to lock socket\n", __location__));
     3003                return;
     3004        }
     3005
     3006        if (!fd_is_readable(xconn->transport.sock)) {
     3007                DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
     3008                          (int)getpid()));
     3009
     3010                ok = smbd_unlock_socket_internal(xconn);
     3011                if (!ok) {
     3012                        tevent_req_nterror(req, map_nt_error_from_unix(errno));
     3013                        DEBUG(1, ("%s: failed to unlock socket\n",
     3014                                __location__));
     3015                        return;
     3016                }
     3017
     3018                subreq = wait_for_read_send(state, state->ev,
     3019                                            xconn->transport.sock, false);
     3020                if (tevent_req_nomem(subreq, req)) {
     3021                        return;
     3022                }
     3023                tevent_req_set_callback(subreq, smbd_echo_read_readable, req);
     3024                return;
     3025        }
     3026
     3027        status = receive_smb_talloc(state, xconn,
     3028                                    xconn->transport.sock,
     3029                                    &state->buf,
     3030                                    0 /* timeout */,
     3031                                    &unread,
     3032                                    &encrypted,
     3033                                    &state->buflen,
     3034                                    &state->seqnum,
     3035                                    false /* trusted_channel*/);
     3036
     3037        if (tevent_req_nterror(req, status)) {
     3038                tevent_req_nterror(req, status);
     3039                DEBUG(1, ("echo_handler[%d]: receive_smb_raw_talloc failed: %s\n",
     3040                          (int)getpid(), nt_errstr(status)));
     3041                return;
     3042        }
     3043
     3044        ok = smbd_unlock_socket_internal(xconn);
     3045        if (!ok) {
     3046                tevent_req_nterror(req, map_nt_error_from_unix(errno));
     3047                DEBUG(1, ("%s: failed to unlock socket\n", __location__));
     3048                return;
     3049        }
     3050        tevent_req_done(req);
     3051}
     3052
     3053static NTSTATUS smbd_echo_read_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
     3054                                    char **pbuf, size_t *pbuflen, uint32_t *pseqnum)
     3055{
     3056        struct smbd_echo_read_state *state = tevent_req_data(
     3057                req, struct smbd_echo_read_state);
     3058        NTSTATUS status;
     3059
     3060        if (tevent_req_is_nterror(req, &status)) {
     3061                return status;
     3062        }
     3063        *pbuf = talloc_move(mem_ctx, &state->buf);
     3064        *pbuflen = state->buflen;
     3065        *pseqnum = state->seqnum;
     3066        return NT_STATUS_OK;
    24673067}
    24683068
     
    24713071        struct iovec *pending;
    24723072        struct smbd_server_connection *sconn;
     3073        struct smbXsrv_connection *xconn;
    24733074        int parent_pipe;
    24743075
    24753076        struct tevent_fd *parent_fde;
    24763077
    2477         struct tevent_fd *read_fde;
    24783078        struct tevent_req *write_req;
    24793079};
     
    25233123                exit(1);
    25243124        }
    2525         DEBUG(10,("echo_handler[%d]: forwarded pdu to main\n", (int)sys_getpid()));
     3125        DEBUG(10,("echo_handler[%d]: forwarded pdu to main\n", (int)getpid()));
    25263126        smbd_echo_activate_writer(state);
    25273127}
    25283128
    2529 static bool smbd_echo_reply(uint8_t *inbuf, size_t inbuf_len,
     3129static bool smbd_echo_reply(struct smbd_echo_state *state,
     3130                            uint8_t *inbuf, size_t inbuf_len,
    25303131                            uint32_t seqnum)
    25313132{
    25323133        struct smb_request req;
    25333134        uint16_t num_replies;
    2534         size_t out_len;
    25353135        char *outbuf;
    25363136        bool ok;
    25373137
    2538         if ((inbuf_len == 4) && (CVAL(inbuf, 0) == SMBkeepalive)) {
     3138        if ((inbuf_len == 4) && (CVAL(inbuf, 0) == NBSSkeepalive)) {
    25393139                DEBUG(10, ("Got netbios keepalive\n"));
    25403140                /*
     
    25533153        }
    25543154
    2555         if (!init_smb_request(&req, smbd_server_conn, inbuf, 0, false,
     3155        if (!init_smb_request(&req, state->sconn, state->xconn, inbuf, 0, false,
    25563156                              seqnum)) {
    25573157                return false;
     
    25763176        }
    25773177
    2578         if (!create_outbuf(talloc_tos(), &req, (char *)req.inbuf, &outbuf,
     3178        if (!create_outbuf(talloc_tos(), &req, req.inbuf, &outbuf,
    25793179                           1, req.buflen)) {
    25803180                DEBUG(10, ("create_outbuf failed\n"));
     
    25893189        }
    25903190
    2591         out_len = smb_len(req.outbuf) + 4;
    2592 
    2593         ok = srv_send_smb(req.sconn,
     3191        ok = srv_send_smb(req.xconn,
    25943192                          (char *)outbuf,
    25953193                          true, seqnum+1,
     
    26113209}
    26123210
    2613 static void smbd_echo_reader(struct tevent_context *ev,
    2614                              struct tevent_fd *fde, uint16_t flags,
    2615                              void *private_data)
    2616 {
    2617         struct smbd_echo_state *state = talloc_get_type_abort(
    2618                 private_data, struct smbd_echo_state);
    2619         struct smbd_server_connection *sconn = state->sconn;
    2620         size_t unread, num_pending;
    2621         NTSTATUS status;
    2622         struct iovec *tmp;
    2623         size_t iov_len;
    2624         uint32_t seqnum = 0;
    2625         bool reply;
    2626         bool ok;
    2627         bool encrypted = false;
    2628 
    2629         smb_msleep(1000);
    2630 
    2631         ok = smbd_lock_socket_internal(sconn);
    2632         if (!ok) {
    2633                 DEBUG(0, ("%s: failed to lock socket\n",
    2634                         __location__));
    2635                 exit(1);
    2636         }
    2637 
    2638         if (!fd_is_readable(sconn->sock)) {
    2639                 DEBUG(10,("echo_handler[%d] the parent smbd was faster\n",
    2640                           (int)sys_getpid()));
    2641                 ok = smbd_unlock_socket_internal(sconn);
    2642                 if (!ok) {
    2643                         DEBUG(1, ("%s: failed to unlock socket in\n",
    2644                                 __location__));
    2645                         exit(1);
    2646                 }
    2647                 return;
    2648         }
    2649 
    2650         num_pending = talloc_array_length(state->pending);
    2651         tmp = talloc_realloc(state, state->pending, struct iovec,
    2652                              num_pending+1);
    2653         if (tmp == NULL) {
    2654                 DEBUG(1, ("talloc_realloc failed\n"));
    2655                 exit(1);
    2656         }
    2657         state->pending = tmp;
    2658 
    2659         DEBUG(10,("echo_handler[%d]: reading pdu\n", (int)sys_getpid()));
    2660 
    2661         status = receive_smb_talloc(state->pending, sconn, sconn->sock,
    2662                                     (char **)(void *)&state->pending[num_pending].iov_base,
    2663                                     0 /* timeout */,
    2664                                     &unread,
    2665                                     &encrypted,
    2666                                     &iov_len,
    2667                                     &seqnum,
    2668                                     false /* trusted_channel*/);
    2669         if (!NT_STATUS_IS_OK(status)) {
    2670                 DEBUG(1, ("echo_handler[%d]: receive_smb_raw_talloc failed: %s\n",
    2671                           (int)sys_getpid(), nt_errstr(status)));
    2672                 exit(1);
    2673         }
    2674         state->pending[num_pending].iov_len = iov_len;
    2675 
    2676         ok = smbd_unlock_socket_internal(sconn);
    2677         if (!ok) {
    2678                 DEBUG(1, ("%s: failed to unlock socket in\n",
    2679                         __location__));
    2680                 exit(1);
    2681         }
    2682 
    2683         reply = smbd_echo_reply((uint8_t *)state->pending[num_pending].iov_base,
    2684                                 state->pending[num_pending].iov_len,
    2685                                 seqnum);
    2686         if (reply) {
    2687                 DEBUG(10,("echo_handler[%d]: replied to client\n", (int)sys_getpid()));
    2688                 /* no check, shrinking by some bytes does not fail */
    2689                 state->pending = talloc_realloc(state, state->pending,
    2690                                                 struct iovec,
    2691                                                 num_pending);
    2692                 return;
    2693         }
    2694 
    2695         if (state->pending[num_pending].iov_len >= smb_size) {
    2696                 /*
    2697                  * place the seqnum in the packet so that the main process
    2698                  * can reply with signing
    2699                  */
    2700                 SIVAL((uint8_t *)state->pending[num_pending].iov_base,
    2701                       smb_ss_field, seqnum);
    2702                 SIVAL((uint8_t *)state->pending[num_pending].iov_base,
    2703                       smb_ss_field+4, NT_STATUS_V(NT_STATUS_OK));
    2704         }
    2705 
    2706         DEBUG(10,("echo_handler[%d]: forward to main\n", (int)sys_getpid()));
    2707         smbd_echo_activate_writer(state);
    2708 }
    2709 
    2710 static void smbd_echo_loop(struct smbd_server_connection *sconn,
     3211static void smbd_echo_got_packet(struct tevent_req *req);
     3212
     3213static void smbd_echo_loop(struct smbXsrv_connection *xconn,
    27113214                           int parent_pipe)
    27123215{
    27133216        struct smbd_echo_state *state;
    2714 
    2715         state = talloc_zero(sconn, struct smbd_echo_state);
     3217        struct tevent_req *read_req;
     3218
     3219        state = talloc_zero(xconn, struct smbd_echo_state);
    27163220        if (state == NULL) {
    27173221                DEBUG(1, ("talloc failed\n"));
    27183222                return;
    27193223        }
    2720         state->sconn = sconn;
     3224        state->xconn = xconn;
    27213225        state->parent_pipe = parent_pipe;
    27223226        state->ev = s3_tevent_context_init(state);
     
    27343238                return;
    27353239        }
    2736         state->read_fde = tevent_add_fd(state->ev, state, sconn->sock,
    2737                                         TEVENT_FD_READ, smbd_echo_reader,
    2738                                         state);
    2739         if (state->read_fde == NULL) {
    2740                 DEBUG(1, ("tevent_add_fd failed\n"));
     3240
     3241        read_req = smbd_echo_read_send(state, state->ev, xconn);
     3242        if (read_req == NULL) {
     3243                DEBUG(1, ("smbd_echo_read_send failed\n"));
    27413244                TALLOC_FREE(state);
    27423245                return;
    27433246        }
     3247        tevent_req_set_callback(read_req, smbd_echo_got_packet, state);
    27443248
    27453249        while (true) {
     
    27533257}
    27543258
     3259static void smbd_echo_got_packet(struct tevent_req *req)
     3260{
     3261        struct smbd_echo_state *state = tevent_req_callback_data(
     3262                req, struct smbd_echo_state);
     3263        NTSTATUS status;
     3264        char *buf = NULL;
     3265        size_t buflen = 0;
     3266        uint32_t seqnum = 0;
     3267        bool reply;
     3268
     3269        status = smbd_echo_read_recv(req, state, &buf, &buflen, &seqnum);
     3270        TALLOC_FREE(req);
     3271        if (!NT_STATUS_IS_OK(status)) {
     3272                DEBUG(1, ("smbd_echo_read_recv returned %s\n",
     3273                          nt_errstr(status)));
     3274                exit(1);
     3275        }
     3276
     3277        reply = smbd_echo_reply(state, (uint8_t *)buf, buflen, seqnum);
     3278        if (!reply) {
     3279                size_t num_pending;
     3280                struct iovec *tmp;
     3281                struct iovec *iov;
     3282
     3283                num_pending = talloc_array_length(state->pending);
     3284                tmp = talloc_realloc(state, state->pending, struct iovec,
     3285                                     num_pending+1);
     3286                if (tmp == NULL) {
     3287                        DEBUG(1, ("talloc_realloc failed\n"));
     3288                        exit(1);
     3289                }
     3290                state->pending = tmp;
     3291
     3292                if (buflen >= smb_size) {
     3293                        /*
     3294                         * place the seqnum in the packet so that the main process
     3295                         * can reply with signing
     3296                         */
     3297                        SIVAL(buf, smb_ss_field, seqnum);
     3298                        SIVAL(buf, smb_ss_field+4, NT_STATUS_V(NT_STATUS_OK));
     3299                }
     3300
     3301                iov = &state->pending[num_pending];
     3302                iov->iov_base = talloc_move(state->pending, &buf);
     3303                iov->iov_len = buflen;
     3304
     3305                DEBUG(10,("echo_handler[%d]: forward to main\n",
     3306                          (int)getpid()));
     3307                smbd_echo_activate_writer(state);
     3308        }
     3309
     3310        req = smbd_echo_read_send(state, state->ev, state->xconn);
     3311        if (req == NULL) {
     3312                DEBUG(1, ("smbd_echo_read_send failed\n"));
     3313                exit(1);
     3314        }
     3315        tevent_req_set_callback(req, smbd_echo_got_packet, state);
     3316}
     3317
     3318
    27553319/*
    27563320 * Handle SMBecho requests in a forked child process
    27573321 */
    2758 bool fork_echo_handler(struct smbd_server_connection *sconn)
     3322bool fork_echo_handler(struct smbXsrv_connection *xconn)
    27593323{
    27603324        int listener_pipe[2];
    27613325        int res;
    27623326        pid_t child;
     3327        bool use_mutex = false;
    27633328
    27643329        res = pipe(listener_pipe);
     
    27673332                return false;
    27683333        }
    2769         sconn->smb1.echo_handler.socket_lock_fd = create_unlink_tmp(lp_lockdir());
    2770         if (sconn->smb1.echo_handler.socket_lock_fd == -1) {
    2771                 DEBUG(1, ("Could not create lock fd: %s\n", strerror(errno)));
    2772                 goto fail;
    2773         }
    2774 
    2775         child = sys_fork();
     3334
     3335#ifdef HAVE_ROBUST_MUTEXES
     3336        use_mutex = tdb_runtime_check_for_robust_mutexes();
     3337
     3338        if (use_mutex) {
     3339                pthread_mutexattr_t a;
     3340
     3341                xconn->smb1.echo_handler.socket_mutex =
     3342                        anonymous_shared_allocate(sizeof(pthread_mutex_t));
     3343                if (xconn->smb1.echo_handler.socket_mutex == NULL) {
     3344                        DEBUG(1, ("Could not create mutex shared memory: %s\n",
     3345                                  strerror(errno)));
     3346                        goto fail;
     3347                }
     3348
     3349                res = pthread_mutexattr_init(&a);
     3350                if (res != 0) {
     3351                        DEBUG(1, ("pthread_mutexattr_init failed: %s\n",
     3352                                  strerror(res)));
     3353                        goto fail;
     3354                }
     3355                res = pthread_mutexattr_settype(&a, PTHREAD_MUTEX_ERRORCHECK);
     3356                if (res != 0) {
     3357                        DEBUG(1, ("pthread_mutexattr_settype failed: %s\n",
     3358                                  strerror(res)));
     3359                        pthread_mutexattr_destroy(&a);
     3360                        goto fail;
     3361                }
     3362                res = pthread_mutexattr_setpshared(&a, PTHREAD_PROCESS_SHARED);
     3363                if (res != 0) {
     3364                        DEBUG(1, ("pthread_mutexattr_setpshared failed: %s\n",
     3365                                  strerror(res)));
     3366                        pthread_mutexattr_destroy(&a);
     3367                        goto fail;
     3368                }
     3369                res = pthread_mutexattr_setrobust(&a, PTHREAD_MUTEX_ROBUST);
     3370                if (res != 0) {
     3371                        DEBUG(1, ("pthread_mutexattr_setrobust failed: "
     3372                                  "%s\n", strerror(res)));
     3373                        pthread_mutexattr_destroy(&a);
     3374                        goto fail;
     3375                }
     3376                res = pthread_mutex_init(xconn->smb1.echo_handler.socket_mutex,
     3377                                         &a);
     3378                pthread_mutexattr_destroy(&a);
     3379                if (res != 0) {
     3380                        DEBUG(1, ("pthread_mutex_init failed: %s\n",
     3381                                  strerror(res)));
     3382                        goto fail;
     3383                }
     3384        }
     3385#endif
     3386
     3387        if (!use_mutex) {
     3388                xconn->smb1.echo_handler.socket_lock_fd =
     3389                        create_unlink_tmp(lp_lock_directory());
     3390                if (xconn->smb1.echo_handler.socket_lock_fd == -1) {
     3391                        DEBUG(1, ("Could not create lock fd: %s\n",
     3392                                  strerror(errno)));
     3393                        goto fail;
     3394                }
     3395        }
     3396
     3397        child = fork();
    27763398        if (child == 0) {
    27773399                NTSTATUS status;
     
    27803402                set_blocking(listener_pipe[1], false);
    27813403
    2782                 status = reinit_after_fork(sconn->msg_ctx,
    2783                                            smbd_event_context(),
    2784                                            procid_self(), false);
     3404                status = smbd_reinit_after_fork(xconn->msg_ctx, xconn->ev_ctx,
     3405                                                true, "smbd-echo");
    27853406                if (!NT_STATUS_IS_OK(status)) {
    27863407                        DEBUG(1, ("reinit_after_fork failed: %s\n",
     
    27883409                        exit(1);
    27893410                }
    2790                 smbd_echo_loop(sconn, listener_pipe[1]);
     3411                smbd_echo_loop(xconn, listener_pipe[1]);
    27913412                exit(0);
    27923413        }
    27933414        close(listener_pipe[1]);
    27943415        listener_pipe[1] = -1;
    2795         sconn->smb1.echo_handler.trusted_fd = listener_pipe[0];
    2796 
    2797         DEBUG(10,("fork_echo_handler: main[%d] echo_child[%d]\n", (int)sys_getpid(), child));
     3416        xconn->smb1.echo_handler.trusted_fd = listener_pipe[0];
     3417
     3418        DEBUG(10,("fork_echo_handler: main[%d] echo_child[%d]\n", (int)getpid(), (int)child));
    27983419
    27993420        /*
     
    28013422         * listener. This needs to change once signing comes in.
    28023423         */
    2803         sconn->smb1.echo_handler.trusted_fde = event_add_fd(smbd_event_context(),
    2804                                         sconn,
    2805                                         sconn->smb1.echo_handler.trusted_fd,
    2806                                         EVENT_FD_READ,
     3424        xconn->smb1.echo_handler.trusted_fde = tevent_add_fd(xconn->ev_ctx,
     3425                                        xconn,
     3426                                        xconn->smb1.echo_handler.trusted_fd,
     3427                                        TEVENT_FD_READ,
    28073428                                        smbd_server_echo_handler,
    2808                                         sconn);
    2809         if (sconn->smb1.echo_handler.trusted_fde == NULL) {
     3429                                        xconn);
     3430        if (xconn->smb1.echo_handler.trusted_fde == NULL) {
    28103431                DEBUG(1, ("event_add_fd failed\n"));
    28113432                goto fail;
     
    28213442                close(listener_pipe[1]);
    28223443        }
    2823         sconn->smb1.echo_handler.trusted_fd = -1;
    2824         if (sconn->smb1.echo_handler.socket_lock_fd != -1) {
    2825                 close(sconn->smb1.echo_handler.socket_lock_fd);
    2826         }
    2827         sconn->smb1.echo_handler.trusted_fd = -1;
    2828         sconn->smb1.echo_handler.socket_lock_fd = -1;
     3444        if (xconn->smb1.echo_handler.socket_lock_fd != -1) {
     3445                close(xconn->smb1.echo_handler.socket_lock_fd);
     3446        }
     3447#ifdef HAVE_ROBUST_MUTEXES
     3448        if (xconn->smb1.echo_handler.socket_mutex != NULL) {
     3449                pthread_mutex_destroy(xconn->smb1.echo_handler.socket_mutex);
     3450                anonymous_shared_free(xconn->smb1.echo_handler.socket_mutex);
     3451        }
     3452#endif
     3453        smbd_echo_init(xconn);
     3454
    28293455        return false;
    28303456}
    28313457
    2832 #if CLUSTER_SUPPORT
    2833 
    2834 static NTSTATUS smbd_register_ips(struct smbd_server_connection *sconn,
    2835                                   struct sockaddr_storage *srv,
    2836                                   struct sockaddr_storage *clnt)
    2837 {
    2838         struct ctdbd_connection *cconn;
    2839         char tmp_addr[INET6_ADDRSTRLEN];
    2840         char *addr;
    2841 
    2842         cconn = messaging_ctdbd_connection();
    2843         if (cconn == NULL) {
    2844                 return NT_STATUS_NO_MEMORY;
    2845         }
    2846 
    2847         client_socket_addr(sconn->sock, tmp_addr, sizeof(tmp_addr));
    2848         addr = talloc_strdup(cconn, tmp_addr);
    2849         if (addr == NULL) {
    2850                 return NT_STATUS_NO_MEMORY;
    2851         }
    2852         return ctdbd_register_ips(cconn, srv, clnt, release_ip, addr);
    2853 }
    2854 
    2855 #endif
    2856 
    2857 /****************************************************************************
    2858  Process commands from the client
    2859 ****************************************************************************/
    2860 
    2861 void smbd_process(struct smbd_server_connection *sconn)
     3458static bool uid_in_use(const struct user_struct *user, uid_t uid)
     3459{
     3460        while (user) {
     3461                if (user->session_info &&
     3462                    (user->session_info->unix_token->uid == uid)) {
     3463                        return true;
     3464                }
     3465                user = user->next;
     3466        }
     3467        return false;
     3468}
     3469
     3470static bool gid_in_use(const struct user_struct *user, gid_t gid)
     3471{
     3472        while (user) {
     3473                if (user->session_info != NULL) {
     3474                        int i;
     3475                        struct security_unix_token *utok;
     3476
     3477                        utok = user->session_info->unix_token;
     3478                        if (utok->gid == gid) {
     3479                                return true;
     3480                        }
     3481                        for(i=0; i<utok->ngroups; i++) {
     3482                                if (utok->groups[i] == gid) {
     3483                                        return true;
     3484                                }
     3485                        }
     3486                }
     3487                user = user->next;
     3488        }
     3489        return false;
     3490}
     3491
     3492static bool sid_in_use(const struct user_struct *user,
     3493                       const struct dom_sid *psid)
     3494{
     3495        while (user) {
     3496                struct security_token *tok;
     3497
     3498                if (user->session_info == NULL) {
     3499                        continue;
     3500                }
     3501                tok = user->session_info->security_token;
     3502                if (tok == NULL) {
     3503                        /*
     3504                         * Not sure session_info->security_token can
     3505                         * ever be NULL. This check might be not
     3506                         * necessary.
     3507                         */
     3508                        continue;
     3509                }
     3510                if (security_token_has_sid(tok, psid)) {
     3511                        return true;
     3512                }
     3513                user = user->next;
     3514        }
     3515        return false;
     3516}
     3517
     3518static bool id_in_use(const struct user_struct *user,
     3519                      const struct id_cache_ref *id)
     3520{
     3521        switch(id->type) {
     3522        case UID:
     3523                return uid_in_use(user, id->id.uid);
     3524        case GID:
     3525                return gid_in_use(user, id->id.gid);
     3526        case SID:
     3527                return sid_in_use(user, &id->id.sid);
     3528        default:
     3529                break;
     3530        }
     3531        return false;
     3532}
     3533
     3534static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
     3535                               void *private_data,
     3536                               uint32_t msg_type,
     3537                               struct server_id server_id,
     3538                               DATA_BLOB* data)
     3539{
     3540        const char *msg = (data && data->data)
     3541                ? (const char *)data->data : "<NULL>";
     3542        struct id_cache_ref id;
     3543        struct smbd_server_connection *sconn =
     3544                talloc_get_type_abort(private_data,
     3545                struct smbd_server_connection);
     3546
     3547        if (!id_cache_ref_parse(msg, &id)) {
     3548                DEBUG(0, ("Invalid ?ID: %s\n", msg));
     3549                return;
     3550        }
     3551
     3552        if (id_in_use(sconn->users, &id)) {
     3553                exit_server_cleanly(msg);
     3554        }
     3555        id_cache_delete_from_cache(&id);
     3556}
     3557
     3558NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
     3559                                        enum protocol_types protocol)
     3560{
     3561        NTSTATUS status;
     3562
     3563        conn->protocol = protocol;
     3564
     3565        if (conn->client->session_table != NULL) {
     3566                return NT_STATUS_OK;
     3567        }
     3568
     3569        if (protocol >= PROTOCOL_SMB2_02) {
     3570                status = smb2srv_session_table_init(conn);
     3571                if (!NT_STATUS_IS_OK(status)) {
     3572                        conn->protocol = PROTOCOL_NONE;
     3573                        return status;
     3574                }
     3575
     3576                status = smb2srv_open_table_init(conn);
     3577                if (!NT_STATUS_IS_OK(status)) {
     3578                        conn->protocol = PROTOCOL_NONE;
     3579                        return status;
     3580                }
     3581        } else {
     3582                status = smb1srv_session_table_init(conn);
     3583                if (!NT_STATUS_IS_OK(status)) {
     3584                        conn->protocol = PROTOCOL_NONE;
     3585                        return status;
     3586                }
     3587
     3588                status = smb1srv_tcon_table_init(conn);
     3589                if (!NT_STATUS_IS_OK(status)) {
     3590                        conn->protocol = PROTOCOL_NONE;
     3591                        return status;
     3592                }
     3593
     3594                status = smb1srv_open_table_init(conn);
     3595                if (!NT_STATUS_IS_OK(status)) {
     3596                        conn->protocol = PROTOCOL_NONE;
     3597                        return status;
     3598                }
     3599        }
     3600
     3601        set_Protocol(protocol);
     3602        return NT_STATUS_OK;
     3603}
     3604
     3605struct smbd_tevent_trace_state {
     3606        struct tevent_context *ev;
     3607        TALLOC_CTX *frame;
     3608        SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
     3609};
     3610
     3611static void smbd_tevent_trace_callback(enum tevent_trace_point point,
     3612                                       void *private_data)
     3613{
     3614        struct smbd_tevent_trace_state *state =
     3615                (struct smbd_tevent_trace_state *)private_data;
     3616
     3617        switch (point) {
     3618        case TEVENT_TRACE_BEFORE_WAIT:
     3619                if (!smbprofile_dump_pending()) {
     3620                        /*
     3621                         * If there's no dump pending
     3622                         * we don't want to schedule a new 1 sec timer.
     3623                         *
     3624                         * Instead we want to sleep as long as nothing happens.
     3625                         */
     3626                        smbprofile_dump_setup(NULL);
     3627                }
     3628                SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
     3629                break;
     3630        case TEVENT_TRACE_AFTER_WAIT:
     3631                SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
     3632                if (!smbprofile_dump_pending()) {
     3633                        /*
     3634                         * We need to flush our state after sleeping
     3635                         * (hopefully a long time).
     3636                         */
     3637                        smbprofile_dump();
     3638                        /*
     3639                         * future profiling events should trigger timers
     3640                         * on our main event context.
     3641                         */
     3642                        smbprofile_dump_setup(state->ev);
     3643                }
     3644                break;
     3645        case TEVENT_TRACE_BEFORE_LOOP_ONCE:
     3646                TALLOC_FREE(state->frame);
     3647                state->frame = talloc_stackframe_pool(8192);
     3648                break;
     3649        case TEVENT_TRACE_AFTER_LOOP_ONCE:
     3650                TALLOC_FREE(state->frame);
     3651                break;
     3652        }
     3653
     3654        errno = 0;
     3655}
     3656
     3657/**
     3658 * Create a debug string for the connection
     3659 *
     3660 * This is allocated to talloc_tos() or a string constant
     3661 * in certain corner cases. The returned string should
     3662 * hence not be free'd directly but only via the talloc stack.
     3663 */
     3664const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
     3665{
     3666        const char *ret;
     3667
     3668        /*
     3669         * TODO: this can be improved later
     3670         * maybe including the client guid or more
     3671         */
     3672        ret = tsocket_address_string(xconn->remote_address, talloc_tos());
     3673        if (ret == NULL) {
     3674                return "<tsocket_address_string() failed>";
     3675        }
     3676
     3677        return ret;
     3678}
     3679
     3680NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
     3681                             struct smbXsrv_connection **_xconn)
    28623682{
    28633683        TALLOC_CTX *frame = talloc_stackframe();
    2864         struct sockaddr_storage ss;
    2865         struct sockaddr *sa = NULL;
     3684        struct smbXsrv_connection *xconn;
     3685        struct sockaddr_storage ss_srv;
     3686        void *sp_srv = (void *)&ss_srv;
     3687        struct sockaddr *sa_srv = (struct sockaddr *)sp_srv;
     3688        struct sockaddr_storage ss_clnt;
     3689        void *sp_clnt = (void *)&ss_clnt;
     3690        struct sockaddr *sa_clnt = (struct sockaddr *)sp_clnt;
    28663691        socklen_t sa_socklen;
    28673692        struct tsocket_address *local_address = NULL;
    28683693        struct tsocket_address *remote_address = NULL;
    28693694        const char *remaddr = NULL;
     3695        char *p;
     3696        const char *rhost = NULL;
    28703697        int ret;
    2871 
    2872         if (lp_maxprotocol() == PROTOCOL_SMB2) {
     3698        int tmp;
     3699
     3700        *_xconn = NULL;
     3701
     3702        DO_PROFILE_INC(connect);
     3703
     3704        xconn = talloc_zero(client, struct smbXsrv_connection);
     3705        if (xconn == NULL) {
     3706                DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
     3707                TALLOC_FREE(frame);
     3708                return NT_STATUS_NO_MEMORY;
     3709        }
     3710        talloc_steal(frame, xconn);
     3711
     3712        xconn->ev_ctx = client->ev_ctx;
     3713        xconn->msg_ctx = client->msg_ctx;
     3714        xconn->transport.sock = sock_fd;
     3715        smbd_echo_init(xconn);
     3716        xconn->protocol = PROTOCOL_NONE;
     3717
     3718        /* Ensure child is set to blocking mode */
     3719        set_blocking(sock_fd,True);
     3720
     3721        set_socket_options(sock_fd, "SO_KEEPALIVE");
     3722        set_socket_options(sock_fd, lp_socket_options());
     3723
     3724        sa_socklen = sizeof(ss_clnt);
     3725        ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
     3726        if (ret != 0) {
     3727                int saved_errno = errno;
     3728                int level = (errno == ENOTCONN)?2:0;
     3729                DEBUG(level,("getpeername() failed - %s\n",
     3730                      strerror(saved_errno)));
     3731                TALLOC_FREE(frame);
     3732                return map_nt_error_from_unix_common(saved_errno);
     3733        }
     3734        ret = tsocket_address_bsd_from_sockaddr(xconn,
     3735                                                sa_clnt, sa_socklen,
     3736                                                &remote_address);
     3737        if (ret != 0) {
     3738                int saved_errno = errno;
     3739                DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
     3740                        __location__, strerror(saved_errno)));
     3741                TALLOC_FREE(frame);
     3742                return map_nt_error_from_unix_common(saved_errno);
     3743        }
     3744
     3745        sa_socklen = sizeof(ss_srv);
     3746        ret = getsockname(sock_fd, sa_srv, &sa_socklen);
     3747        if (ret != 0) {
     3748                int saved_errno = errno;
     3749                int level = (errno == ENOTCONN)?2:0;
     3750                DEBUG(level,("getsockname() failed - %s\n",
     3751                      strerror(saved_errno)));
     3752                TALLOC_FREE(frame);
     3753                return map_nt_error_from_unix_common(saved_errno);
     3754        }
     3755        ret = tsocket_address_bsd_from_sockaddr(xconn,
     3756                                                sa_srv, sa_socklen,
     3757                                                &local_address);
     3758        if (ret != 0) {
     3759                int saved_errno = errno;
     3760                DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
     3761                        __location__, strerror(saved_errno)));
     3762                TALLOC_FREE(frame);
     3763                return map_nt_error_from_unix_common(saved_errno);
     3764        }
     3765
     3766        if (tsocket_address_is_inet(remote_address, "ip")) {
     3767                remaddr = tsocket_address_inet_addr_string(remote_address,
     3768                                                           talloc_tos());
     3769                if (remaddr == NULL) {
     3770                        DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
     3771                                 __location__, strerror(errno)));
     3772                        TALLOC_FREE(frame);
     3773                        return NT_STATUS_NO_MEMORY;
     3774                }
     3775        } else {
     3776                remaddr = "0.0.0.0";
     3777        }
     3778
     3779        /*
     3780         * Before the first packet, check the global hosts allow/ hosts deny
     3781         * parameters before doing any parsing of packets passed to us by the
     3782         * client. This prevents attacks on our parsing code from hosts not in
     3783         * the hosts allow list.
     3784         */
     3785
     3786        ret = get_remote_hostname(remote_address,
     3787                                  &p, talloc_tos());
     3788        if (ret < 0) {
     3789                int saved_errno = errno;
     3790                DEBUG(0,("%s: get_remote_hostname failed - %s\n",
     3791                        __location__, strerror(saved_errno)));
     3792                TALLOC_FREE(frame);
     3793                return map_nt_error_from_unix_common(saved_errno);
     3794        }
     3795        rhost = p;
     3796        if (strequal(rhost, "UNKNOWN")) {
     3797                rhost = remaddr;
     3798        }
     3799
     3800        xconn->local_address = local_address;
     3801        xconn->remote_address = remote_address;
     3802        xconn->remote_hostname = talloc_strdup(xconn, rhost);
     3803        if (xconn->remote_hostname == NULL) {
     3804                return NT_STATUS_NO_MEMORY;
     3805        }
     3806
     3807        if (!srv_init_signing(xconn)) {
     3808                DEBUG(0, ("Failed to init smb_signing\n"));
     3809                TALLOC_FREE(frame);
     3810                return NT_STATUS_INTERNAL_ERROR;
     3811        }
     3812
     3813        if (!allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
     3814                          xconn->remote_hostname,
     3815                          remaddr)) {
     3816                DEBUG( 1, ("Connection denied from %s to %s\n",
     3817                           tsocket_address_string(remote_address, talloc_tos()),
     3818                           tsocket_address_string(local_address, talloc_tos())));
     3819
     3820                /*
     3821                 * We return a valid xconn
     3822                 * so that the caller can return an error message
     3823                 * to the client
     3824                 */
     3825                client->connections = xconn;
     3826                xconn->client = client;
     3827                talloc_steal(client, xconn);
     3828
     3829                *_xconn = xconn;
     3830                TALLOC_FREE(frame);
     3831                return NT_STATUS_NETWORK_ACCESS_DENIED;
     3832        }
     3833
     3834        DEBUG(10, ("Connection allowed from %s to %s\n",
     3835                   tsocket_address_string(remote_address, talloc_tos()),
     3836                   tsocket_address_string(local_address, talloc_tos())));
     3837
     3838        if (lp_clustering()) {
     3839                /*
     3840                 * We need to tell ctdb about our client's TCP
     3841                 * connection, so that for failover ctdbd can send
     3842                 * tickle acks, triggering a reconnection by the
     3843                 * client.
     3844                 */
     3845                NTSTATUS status;
     3846
     3847                status = smbd_register_ips(xconn, &ss_srv, &ss_clnt);
     3848                if (!NT_STATUS_IS_OK(status)) {
     3849                        DEBUG(0, ("ctdbd_register_ips failed: %s\n",
     3850                                  nt_errstr(status)));
     3851                }
     3852        }
     3853
     3854        tmp = lp_max_xmit();
     3855        tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
     3856        tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
     3857
     3858        xconn->smb1.negprot.max_recv = tmp;
     3859
     3860        xconn->smb1.sessions.done_sesssetup = false;
     3861        xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
     3862
     3863        xconn->transport.fde = tevent_add_fd(client->ev_ctx,
     3864                                             xconn,
     3865                                             sock_fd,
     3866                                             TEVENT_FD_READ,
     3867                                             smbd_server_connection_handler,
     3868                                             xconn);
     3869        if (!xconn->transport.fde) {
     3870                TALLOC_FREE(frame);
     3871                return NT_STATUS_NO_MEMORY;
     3872        }
     3873
     3874        /* for now we only have one connection */
     3875        DLIST_ADD_END(client->connections, xconn);
     3876        xconn->client = client;
     3877        talloc_steal(client, xconn);
     3878
     3879        *_xconn = xconn;
     3880        TALLOC_FREE(frame);
     3881        return NT_STATUS_OK;
     3882}
     3883
     3884/****************************************************************************
     3885 Process commands from the client
     3886****************************************************************************/
     3887
     3888void smbd_process(struct tevent_context *ev_ctx,
     3889                  struct messaging_context *msg_ctx,
     3890                  int sock_fd,
     3891                  bool interactive)
     3892{
     3893        struct smbd_tevent_trace_state trace_state = {
     3894                .ev = ev_ctx,
     3895                .frame = talloc_stackframe(),
     3896        };
     3897        struct smbXsrv_client *client = NULL;
     3898        struct smbd_server_connection *sconn = NULL;
     3899        struct smbXsrv_connection *xconn = NULL;
     3900        const char *locaddr = NULL;
     3901        const char *remaddr = NULL;
     3902        int ret;
     3903        NTSTATUS status;
     3904        struct timeval tv = timeval_current();
     3905        NTTIME now = timeval_to_nttime(&tv);
     3906
     3907        status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
     3908        if (!NT_STATUS_IS_OK(status)) {
     3909                DBG_ERR("smbXsrv_client_create(): %s\n", nt_errstr(status));
     3910                exit_server_cleanly("talloc_zero(struct smbXsrv_client).\n");
     3911        }
     3912
     3913        /*
     3914         * TODO: remove this...:-)
     3915         */
     3916        global_smbXsrv_client = client;
     3917
     3918        sconn = talloc_zero(client, struct smbd_server_connection);
     3919        if (sconn == NULL) {
     3920                exit_server("failed to create smbd_server_connection");
     3921        }
     3922
     3923        client->sconn = sconn;
     3924        sconn->client = client;
     3925
     3926        sconn->ev_ctx = ev_ctx;
     3927        sconn->msg_ctx = msg_ctx;
     3928
     3929        if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
    28733930                /*
    28743931                 * We're not making the decision here,
     
    28813938        }
    28823939
    2883         /* Ensure child is set to blocking mode */
    2884         set_blocking(sconn->sock,True);
    2885 
    2886         set_socket_options(sconn->sock, "SO_KEEPALIVE");
    2887         set_socket_options(sconn->sock, lp_socket_options());
    2888 
    2889         sa = (struct sockaddr *)(void *)&ss;
    2890         sa_socklen = sizeof(ss);
    2891         ret = getpeername(sconn->sock, sa, &sa_socklen);
    2892         if (ret != 0) {
    2893                 int level = (errno == ENOTCONN)?2:0;
    2894                 DEBUG(level,("getpeername() failed - %s\n", strerror(errno)));
    2895                 exit_server_cleanly("getpeername() failed.\n");
    2896         }
    2897         ret = tsocket_address_bsd_from_sockaddr(sconn,
    2898                                                 sa, sa_socklen,
    2899                                                 &remote_address);
    2900         if (ret != 0) {
    2901                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
    2902                         __location__, strerror(errno)));
    2903                 exit_server_cleanly("tsocket_address_bsd_from_sockaddr remote failed.\n");
    2904         }
    2905 
    2906         sa = (struct sockaddr *)(void *)&ss;
    2907         sa_socklen = sizeof(ss);
    2908         ret = getsockname(sconn->sock, sa, &sa_socklen);
    2909         if (ret != 0) {
    2910                 int level = (errno == ENOTCONN)?2:0;
    2911                 DEBUG(level,("getsockname() failed - %s\n", strerror(errno)));
    2912                 exit_server_cleanly("getsockname() failed.\n");
    2913         }
    2914         ret = tsocket_address_bsd_from_sockaddr(sconn,
    2915                                                 sa, sa_socklen,
    2916                                                 &local_address);
    2917         if (ret != 0) {
    2918                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
    2919                         __location__, strerror(errno)));
    2920                 exit_server_cleanly("tsocket_address_bsd_from_sockaddr remote failed.\n");
    2921         }
    2922 
    2923         sconn->local_address = local_address;
    2924         sconn->remote_address = remote_address;
    2925 
    2926         if (tsocket_address_is_inet(remote_address, "ip")) {
    2927                 remaddr = tsocket_address_inet_addr_string(
    2928                                 sconn->remote_address,
    2929                                 talloc_tos());
    2930                 if (remaddr == NULL) {
    2931 
    2932                 }
    2933         } else {
    2934                 remaddr = "0.0.0.0";
    2935         }
    2936 
    2937         /* this is needed so that we get decent entries
    2938            in smbstatus for port 445 connects */
    2939         set_remote_machine_name(remaddr, false);
    2940         reload_services(sconn->msg_ctx, sconn->sock, true);
    2941 
    2942         /*
    2943          * Before the first packet, check the global hosts allow/ hosts deny
    2944          * parameters before doing any parsing of packets passed to us by the
    2945          * client. This prevents attacks on our parsing code from hosts not in
    2946          * the hosts allow list.
    2947          */
    2948 
    2949         if (!allow_access(lp_hostsdeny(-1), lp_hostsallow(-1),
    2950                           sconn->client_id.name,
    2951                           sconn->client_id.addr)) {
     3940        if (!interactive) {
     3941                smbd_setup_sig_term_handler(sconn);
     3942                smbd_setup_sig_hup_handler(sconn);
     3943
     3944                if (!serverid_register(messaging_server_id(msg_ctx),
     3945                                       FLAG_MSG_GENERAL|FLAG_MSG_SMBD
     3946                                       |FLAG_MSG_DBWRAP
     3947                                       |FLAG_MSG_PRINT_GENERAL)) {
     3948                        exit_server_cleanly("Could not register myself in "
     3949                                            "serverid.tdb");
     3950                }
     3951        }
     3952
     3953        status = smbd_add_connection(client, sock_fd, &xconn);
     3954        if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
    29523955                /*
    29533956                 * send a negative session response "not listening on calling
     
    29553958                 */
    29563959                unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
    2957                 DEBUG( 1, ("Connection denied from %s to %s\n",
    2958                            tsocket_address_string(remote_address, talloc_tos()),
    2959                            tsocket_address_string(local_address, talloc_tos())));
    2960                 (void)srv_send_smb(sconn,(char *)buf, false,
     3960                (void)srv_send_smb(xconn,(char *)buf, false,
    29613961                                   0, false, NULL);
    29623962                exit_server_cleanly("connection denied");
    2963         }
    2964 
    2965         DEBUG(10, ("Connection allowed from %s to %s\n",
    2966                    tsocket_address_string(remote_address, talloc_tos()),
    2967                    tsocket_address_string(local_address, talloc_tos())));
    2968 
    2969         init_modules();
     3963        } else if (!NT_STATUS_IS_OK(status)) {
     3964                exit_server_cleanly(nt_errstr(status));
     3965        }
     3966
     3967        sconn->local_address =
     3968                tsocket_address_copy(xconn->local_address, sconn);
     3969        if (sconn->local_address == NULL) {
     3970                exit_server_cleanly("tsocket_address_copy() failed");
     3971        }
     3972        sconn->remote_address =
     3973                tsocket_address_copy(xconn->remote_address, sconn);
     3974        if (sconn->remote_address == NULL) {
     3975                exit_server_cleanly("tsocket_address_copy() failed");
     3976        }
     3977        sconn->remote_hostname =
     3978                talloc_strdup(sconn, xconn->remote_hostname);
     3979        if (sconn->remote_hostname == NULL) {
     3980                exit_server_cleanly("tsocket_strdup() failed");
     3981        }
     3982
     3983        if (tsocket_address_is_inet(sconn->local_address, "ip")) {
     3984                locaddr = tsocket_address_inet_addr_string(
     3985                                sconn->local_address,
     3986                                talloc_tos());
     3987                if (locaddr == NULL) {
     3988                        DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
     3989                                 __location__, strerror(errno)));
     3990                        exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
     3991                }
     3992        } else {
     3993                locaddr = "0.0.0.0";
     3994        }
     3995
     3996        if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
     3997                remaddr = tsocket_address_inet_addr_string(
     3998                                sconn->remote_address,
     3999                                talloc_tos());
     4000                if (remaddr == NULL) {
     4001                        DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
     4002                                 __location__, strerror(errno)));
     4003                        exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
     4004                }
     4005        } else {
     4006                remaddr = "0.0.0.0";
     4007        }
     4008
     4009        /* this is needed so that we get decent entries
     4010           in smbstatus for port 445 connects */
     4011        set_remote_machine_name(remaddr, false);
     4012        reload_services(sconn, conn_snum_used, true);
     4013        sub_set_socket_ids(remaddr,
     4014                           sconn->remote_hostname,
     4015                           locaddr);
     4016
     4017        if (lp_preload_modules()) {
     4018                smb_load_modules(lp_preload_modules());
     4019        }
    29704020
    29714021        smb_perfcount_init();
     
    29754025        }
    29764026
    2977         if (*lp_rootdir()) {
    2978                 if (chroot(lp_rootdir()) != 0) {
    2979                         DEBUG(0,("Failed to change root to %s\n", lp_rootdir()));
     4027        if (*lp_root_directory(talloc_tos())) {
     4028                if (chroot(lp_root_directory(talloc_tos())) != 0) {
     4029                        DEBUG(0,("Failed to change root to %s\n",
     4030                                 lp_root_directory(talloc_tos())));
    29804031                        exit_server("Failed to chroot()");
    29814032                }
    29824033                if (chdir("/") == -1) {
    2983                         DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir()));
     4034                        DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_root_directory(talloc_tos())));
    29844035                        exit_server("Failed to chroot()");
    29854036                }
    2986                 DEBUG(0,("Changed root to %s\n", lp_rootdir()));
    2987         }
    2988 
    2989         if (!srv_init_signing(sconn)) {
    2990                 exit_server("Failed to init smb_signing");
     4037                DEBUG(0,("Changed root to %s\n", lp_root_directory(talloc_tos())));
     4038        }
     4039
     4040        if (!file_init(sconn)) {
     4041                exit_server("file_init() failed");
    29914042        }
    29924043
    29934044        /* Setup oplocks */
    2994         if (!init_oplocks(sconn->msg_ctx))
     4045        if (!init_oplocks(sconn))
    29954046                exit_server("Failed to init oplocks");
    29964047
    29974048        /* register our message handlers */
    2998         messaging_register(sconn->msg_ctx, NULL,
     4049        messaging_register(sconn->msg_ctx, sconn,
    29994050                           MSG_SMB_FORCE_TDIS, msg_force_tdis);
    30004051        messaging_register(sconn->msg_ctx, sconn,
    3001                            MSG_SMB_RELEASE_IP, msg_release_ip);
    3002         messaging_register(sconn->msg_ctx, NULL,
    30034052                           MSG_SMB_CLOSE_FILE, msg_close_file);
     4053        messaging_register(sconn->msg_ctx, sconn,
     4054                           MSG_SMB_FILE_RENAME, msg_file_was_renamed);
     4055
     4056        id_cache_register_msgs(sconn->msg_ctx);
     4057        messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
     4058        messaging_register(sconn->msg_ctx, sconn,
     4059                           ID_CACHE_KILL, smbd_id_cache_kill);
     4060
     4061        messaging_deregister(sconn->msg_ctx,
     4062                             MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
     4063        messaging_register(sconn->msg_ctx, sconn,
     4064                           MSG_SMB_CONF_UPDATED, smbd_conf_updated);
     4065
     4066        messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
     4067                             NULL);
     4068        messaging_register(sconn->msg_ctx, sconn,
     4069                           MSG_SMB_KILL_CLIENT_IP,
     4070                           msg_kill_client_ip);
     4071
     4072        messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
    30044073
    30054074        /*
     
    30134082
    30144083        if ((lp_keepalive() != 0)
    3015             && !(event_add_idle(smbd_event_context(), NULL,
     4084            && !(event_add_idle(ev_ctx, NULL,
    30164085                                timeval_set(lp_keepalive(), 0),
    30174086                                "keepalive", keepalive_fn,
    3018                                 NULL))) {
     4087                                sconn))) {
    30194088                DEBUG(0, ("Could not add keepalive event\n"));
    30204089                exit(1);
    30214090        }
    30224091
    3023         if (!(event_add_idle(smbd_event_context(), NULL,
     4092        if (!(event_add_idle(ev_ctx, NULL,
    30244093                             timeval_set(IDLE_CLOSED_TIMEOUT, 0),
    30254094                             "deadtime", deadtime_fn, sconn))) {
     
    30284097        }
    30294098
    3030         if (!(event_add_idle(smbd_event_context(), NULL,
     4099        if (!(event_add_idle(ev_ctx, NULL,
    30314100                             timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
    30324101                             "housekeeping", housekeeping_fn, sconn))) {
     
    30354104        }
    30364105
    3037 #ifdef CLUSTER_SUPPORT
    3038 
    3039         if (lp_clustering()) {
    3040                 /*
    3041                  * We need to tell ctdb about our client's TCP
    3042                  * connection, so that for failover ctdbd can send
    3043                  * tickle acks, triggering a reconnection by the
    3044                  * client.
    3045                  */
    3046 
    3047                 struct sockaddr_storage srv, clnt;
    3048 
    3049                 if (client_get_tcp_info(sconn->sock, &srv, &clnt) == 0) {
    3050                         NTSTATUS status;
    3051                         status = smbd_register_ips(sconn, &srv, &clnt);
    3052                         if (!NT_STATUS_IS_OK(status)) {
    3053                                 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
    3054                                           nt_errstr(status)));
    3055                         }
    3056                 } else
    3057                 {
    3058                         DEBUG(0,("Unable to get tcp info for "
    3059                                  "CTDB_CONTROL_TCP_CLIENT: %s\n",
    3060                                  strerror(errno)));
    3061                 }
    3062         }
    3063 
    3064 #endif
    3065 
    3066         sconn->nbt.got_session = false;
    3067 
    3068         sconn->smb1.negprot.max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
    3069 
    3070         sconn->smb1.sessions.done_sesssetup = false;
    3071         sconn->smb1.sessions.max_send = BUFFER_SIZE;
    3072         sconn->smb1.sessions.last_session_tag = UID_FIELD_INVALID;
    3073         /* users from session setup */
    3074         sconn->smb1.sessions.session_userlist = NULL;
    3075         /* workgroup from session setup. */
    3076         sconn->smb1.sessions.session_workgroup = NULL;
    3077         /* this holds info on user ids that are already validated for this VC */
    3078         sconn->smb1.sessions.validated_users = NULL;
    3079         sconn->smb1.sessions.next_vuid = VUID_OFFSET;
    3080         sconn->smb1.sessions.num_validated_vuids = 0;
    3081 
    3082         conn_init(sconn);
     4106        smbprofile_dump_setup(ev_ctx);
     4107
    30834108        if (!init_dptrs(sconn)) {
    30844109                exit_server("init_dptrs() failed");
    30854110        }
    30864111
    3087         sconn->smb1.fde = event_add_fd(smbd_event_context(),
    3088                                                   sconn,
    3089                                                   sconn->sock,
    3090                                                   EVENT_FD_READ,
    3091                                                   smbd_server_connection_handler,
    3092                                                   sconn);
    3093         if (!sconn->smb1.fde) {
    3094                 exit_server("failed to create smbd_server_connection fde");
    3095         }
    3096 
    3097         TALLOC_FREE(frame);
    3098 
    3099         while (True) {
    3100                 NTSTATUS status;
    3101 
    3102                 frame = talloc_stackframe_pool(8192);
    3103 
    3104                 errno = 0;
    3105 
    3106                 status = smbd_server_connection_loop_once(sconn);
    3107                 if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY) &&
    3108                     !NT_STATUS_IS_OK(status)) {
    3109                         DEBUG(3, ("smbd_server_connection_loop_once failed: %s,"
    3110                                   " exiting\n", nt_errstr(status)));
    3111                         break;
    3112                 }
    3113 
    3114                 TALLOC_FREE(frame);
    3115         }
     4112        TALLOC_FREE(trace_state.frame);
     4113
     4114        tevent_set_trace_callback(ev_ctx, smbd_tevent_trace_callback,
     4115                                  &trace_state);
     4116
     4117        ret = tevent_loop_wait(ev_ctx);
     4118        if (ret != 0) {
     4119                DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
     4120                          " exiting\n", ret, strerror(errno)));
     4121        }
     4122
     4123        TALLOC_FREE(trace_state.frame);
    31164124
    31174125        exit_server_cleanly(NULL);
    31184126}
    31194127
    3120 bool req_is_in_chain(struct smb_request *req)
    3121 {
    3122         if (req->vwv != (uint16_t *)(req->inbuf+smb_vwv)) {
     4128bool req_is_in_chain(const struct smb_request *req)
     4129{
     4130        if (req->vwv != (const uint16_t *)(req->inbuf+smb_vwv)) {
    31234131                /*
    31244132                 * We're right now handling a subsequent request, so we must
Note: See TracChangeset for help on using the changeset viewer.