LCOV - code coverage report
Current view: top level - source3/smbd - smb2_process.c (source / functions) Hit Total Coverage
Test: coverage report for support-claim-type-attributes 6b5c566e Lines: 520 841 61.8 %
Date: 2023-11-21 12:31:41 Functions: 36 50 72.0 %

          Line data    Source code
       1             : /*
       2             :    Unix SMB/CIFS implementation.
       3             :    process incoming packets - main loop
       4             :    Copyright (C) Andrew Tridgell 1992-1998
       5             :    Copyright (C) Volker Lendecke 2005-2007
       6             : 
       7             :    This program is free software; you can redistribute it and/or modify
       8             :    it under the terms of the GNU General Public License as published by
       9             :    the Free Software Foundation; either version 3 of the License, or
      10             :    (at your option) any later version.
      11             : 
      12             :    This program is distributed in the hope that it will be useful,
      13             :    but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :    GNU General Public License for more details.
      16             : 
      17             :    You should have received a copy of the GNU General Public License
      18             :    along with this program.  If not, see <http://www.gnu.org/licenses/>.
      19             : */
      20             : 
      21             : #include "includes.h"
      22             : #include "../lib/tsocket/tsocket.h"
      23             : #include "system/filesys.h"
      24             : #include "smbd/smbd.h"
      25             : #include "smbd/globals.h"
      26             : #include "smbd/smbXsrv_open.h"
      27             : #include "librpc/gen_ndr/netlogon.h"
      28             : #include "../lib/async_req/async_sock.h"
      29             : #include "ctdbd_conn.h"
      30             : #include "../lib/util/select.h"
      31             : #include "printing/queue_process.h"
      32             : #include "system/select.h"
      33             : #include "passdb.h"
      34             : #include "auth.h"
      35             : #include "messages.h"
      36             : #include "lib/messages_ctdb.h"
      37             : #include "smbprofile.h"
      38             : #include "rpc_server/spoolss/srv_spoolss_nt.h"
      39             : #include "../lib/util/tevent_ntstatus.h"
      40             : #include "../libcli/security/dom_sid.h"
      41             : #include "../libcli/security/security_token.h"
      42             : #include "lib/id_cache.h"
      43             : #include "lib/util/sys_rw_data.h"
      44             : #include "system/threads.h"
      45             : #include "lib/pthreadpool/pthreadpool_tevent.h"
      46             : #include "util_event.h"
      47             : #include "libcli/smb/smbXcli_base.h"
      48             : #include "lib/util/time_basic.h"
      49             : #include "source3/lib/substitute.h"
      50             : 
      51             : /* Internal message queue for deferred opens. */
      52             : struct pending_message_list {
      53             :         struct pending_message_list *next, *prev;
      54             :         struct timeval request_time; /* When was this first issued? */
      55             :         struct smbd_server_connection *sconn;
      56             :         struct smbXsrv_connection *xconn;
      57             :         struct tevent_timer *te;
      58             :         uint32_t seqnum;
      59             :         bool encrypted;
      60             :         bool processed;
      61             :         DATA_BLOB buf;
      62             :         struct deferred_open_record *open_rec;
      63             : };
      64             : 
      65             : static struct pending_message_list *get_deferred_open_message_smb(
      66             :         struct smbd_server_connection *sconn, uint64_t mid);
      67             : 
      68             : #if !defined(WITH_SMB1SERVER)
      69             : bool smb1_srv_send(struct smbXsrv_connection *xconn,
      70             :                    char *buffer,
      71             :                    bool do_signing,
      72             :                    uint32_t seqnum,
      73             :                    bool do_encrypt)
      74             : {
      75             :         size_t len = 0;
      76             :         ssize_t ret;
      77             :         len = smb_len_large(buffer) + 4;
      78             :         ret = write_data(xconn->transport.sock, buffer, len);
      79             :         return (ret > 0);
      80             : }
      81             : #endif
      82             : 
      83             : /*******************************************************************
      84             :  Setup the word count and byte count for a smb1 message.
      85             : ********************************************************************/
      86             : 
      87     1311979 : size_t srv_smb1_set_message(char *buf,
      88             :                        size_t num_words,
      89             :                        size_t num_bytes,
      90             :                        bool zero)
      91             : {
      92     1311979 :         if (zero && (num_words || num_bytes)) {
      93      142161 :                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
      94             :         }
      95     1311979 :         SCVAL(buf,smb_wct,num_words);
      96     1311979 :         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
      97     1311979 :         smb_setlen(buf,(smb_size + num_words*2 + num_bytes - 4));
      98     1311979 :         return (smb_size + num_words*2 + num_bytes);
      99             : }
     100             : 
     101      677104 : NTSTATUS read_packet_remainder(int fd, char *buffer,
     102             :                                unsigned int timeout, ssize_t len)
     103             : {
     104        8560 :         NTSTATUS status;
     105             : 
     106      677104 :         if (len <= 0) {
     107           0 :                 return NT_STATUS_OK;
     108             :         }
     109             : 
     110      677104 :         status = read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
     111      677104 :         if (!NT_STATUS_IS_OK(status)) {
     112           0 :                 char addr[INET6_ADDRSTRLEN];
     113           0 :                 DEBUG(0, ("read_fd_with_timeout failed for client %s read "
     114             :                           "error = %s.\n",
     115             :                           get_peer_addr(fd, addr, sizeof(addr)),
     116             :                           nt_errstr(status)));
     117             :         }
     118      677104 :         return status;
     119             : }
     120             : 
     121             : #if !defined(WITH_SMB1SERVER)
     122             : static NTSTATUS smb2_receive_raw_talloc(TALLOC_CTX *mem_ctx,
     123             :                                         struct smbXsrv_connection *xconn,
     124             :                                         int sock,
     125             :                                         char **buffer, unsigned int timeout,
     126             :                                         size_t *p_unread, size_t *plen)
     127             : {
     128             :         char lenbuf[4];
     129             :         size_t len;
     130             :         NTSTATUS status;
     131             : 
     132             :         *p_unread = 0;
     133             : 
     134             :         status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
     135             :                                                   &len);
     136             :         if (!NT_STATUS_IS_OK(status)) {
     137             :                 return status;
     138             :         }
     139             : 
     140             :         /*
     141             :          * The +4 here can't wrap, we've checked the length above already.
     142             :          */
     143             : 
     144             :         *buffer = talloc_array(mem_ctx, char, len+4);
     145             : 
     146             :         if (*buffer == NULL) {
     147             :                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
     148             :                           (int)len+4));
     149             :                 return NT_STATUS_NO_MEMORY;
     150             :         }
     151             : 
     152             :         memcpy(*buffer, lenbuf, sizeof(lenbuf));
     153             : 
     154             :         status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
     155             :         if (!NT_STATUS_IS_OK(status)) {
     156             :                 return status;
     157             :         }
     158             : 
     159             :         *plen = len + 4;
     160             :         return NT_STATUS_OK;
     161             : }
     162             : 
     163             : static NTSTATUS smb2_receive_talloc(TALLOC_CTX *mem_ctx,
     164             :                                     struct smbXsrv_connection *xconn,
     165             :                                     int sock,
     166             :                                     char **buffer, unsigned int timeout,
     167             :                                     size_t *p_unread, bool *p_encrypted,
     168             :                                     size_t *p_len,
     169             :                                     uint32_t *seqnum,
     170             :                                     bool trusted_channel)
     171             : {
     172             :         size_t len = 0;
     173             :         NTSTATUS status;
     174             : 
     175             :         *p_encrypted = false;
     176             : 
     177             :         status = smb2_receive_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
     178             :                                          p_unread, &len);
     179             :         if (!NT_STATUS_IS_OK(status)) {
     180             :                 DEBUG(NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)?5:1,
     181             :                       ("smb2_receive_raw_talloc failed for client %s "
     182             :                        "read error = %s.\n",
     183             :                        smbXsrv_connection_dbg(xconn),
     184             :                        nt_errstr(status)) );
     185             :                 return status;
     186             :         }
     187             : 
     188             :         *p_len = len;
     189             :         return NT_STATUS_OK;
     190             : }
     191             : #endif
     192             : 
     193      656808 : NTSTATUS receive_smb_talloc(TALLOC_CTX *mem_ctx,
     194             :                             struct smbXsrv_connection *xconn,
     195             :                             int sock,
     196             :                             char **buffer, unsigned int timeout,
     197             :                             size_t *p_unread, bool *p_encrypted,
     198             :                             size_t *p_len,
     199             :                             uint32_t *seqnum,
     200             :                             bool trusted_channel)
     201             : {
     202             : #if defined(WITH_SMB1SERVER)
     203      656808 :         return smb1_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
     204             :                                    p_unread, p_encrypted, p_len, seqnum,
     205             :                                    trusted_channel);
     206             : #else
     207             :         return smb2_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
     208             :                                    p_unread, p_encrypted, p_len, seqnum,
     209             :                                    trusted_channel);
     210             : #endif
     211             : }
     212             : 
     213             : /****************************************************************************
     214             :  Function to delete a sharing violation open message by mid.
     215             : ****************************************************************************/
     216             : 
     217        4413 : void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     218             :                                       uint64_t mid)
     219             : {
     220        4413 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     221          17 :         struct pending_message_list *pml;
     222             : 
     223        4413 :         if (sconn->using_smb2) {
     224         328 :                 remove_deferred_open_message_smb2(xconn, mid);
     225         328 :                 return;
     226             :         }
     227             : 
     228        4085 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     229        4085 :                 if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
     230        4085 :                         DEBUG(10,("remove_deferred_open_message_smb: "
     231             :                                   "deleting mid %llu len %u\n",
     232             :                                   (unsigned long long)mid,
     233             :                                   (unsigned int)pml->buf.length ));
     234        4085 :                         DLIST_REMOVE(sconn->deferred_open_queue, pml);
     235        4085 :                         TALLOC_FREE(pml);
     236        4085 :                         return;
     237             :                 }
     238             :         }
     239             : }
     240             : 
     241        4085 : static void smbd_deferred_open_timer(struct tevent_context *ev,
     242             :                                      struct tevent_timer *te,
     243             :                                      struct timeval _tval,
     244             :                                      void *private_data)
     245             : {
     246        4085 :         struct pending_message_list *msg = talloc_get_type(private_data,
     247             :                                            struct pending_message_list);
     248        4085 :         struct smbd_server_connection *sconn = msg->sconn;
     249        4085 :         struct smbXsrv_connection *xconn = msg->xconn;
     250        4085 :         TALLOC_CTX *mem_ctx = talloc_tos();
     251        4085 :         uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
     252          17 :         uint8_t *inbuf;
     253             : 
     254        4085 :         inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
     255             :                                          msg->buf.length);
     256        4085 :         if (inbuf == NULL) {
     257           0 :                 exit_server("smbd_deferred_open_timer: talloc failed\n");
     258             :                 return;
     259             :         }
     260             : 
     261             :         /* We leave this message on the queue so the open code can
     262             :            know this is a retry. */
     263        4085 :         DEBUG(5,("smbd_deferred_open_timer: trigger mid %llu.\n",
     264             :                 (unsigned long long)mid ));
     265             : 
     266             :         /* Mark the message as processed so this is not
     267             :          * re-processed in error. */
     268        4085 :         msg->processed = true;
     269             : 
     270        4085 :         process_smb(xconn,
     271             :                     inbuf,
     272             :                     msg->buf.length,
     273             :                     0,
     274             :                     msg->seqnum,
     275        4085 :                     msg->encrypted);
     276             : 
     277             :         /* If it's still there and was processed, remove it. */
     278        4102 :         msg = get_deferred_open_message_smb(sconn, mid);
     279        4085 :         if (msg && msg->processed) {
     280          36 :                 remove_deferred_open_message_smb(xconn, mid);
     281             :         }
     282             : }
     283             : 
     284             : /****************************************************************************
     285             :  Move a sharing violation open retry message to the front of the list and
     286             :  schedule it for immediate processing.
     287             : ****************************************************************************/
     288             : 
     289        4429 : bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     290             :                                         uint64_t mid)
     291             : {
     292        4429 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     293          17 :         struct pending_message_list *pml;
     294        4429 :         int i = 0;
     295             : 
     296        4429 :         if (sconn->using_smb2) {
     297         344 :                 return schedule_deferred_open_message_smb2(xconn, mid);
     298             :         }
     299             : 
     300        4085 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     301        4085 :                 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
     302             : 
     303        4085 :                 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
     304             :                         "msg_mid = %llu\n",
     305             :                         i++,
     306             :                         (unsigned long long)msg_mid ));
     307             : 
     308        4085 :                 if (mid == msg_mid) {
     309          17 :                         struct tevent_timer *te;
     310             : 
     311        4085 :                         if (pml->processed) {
     312             :                                 /* A processed message should not be
     313             :                                  * rescheduled. */
     314           0 :                                 DEBUG(0,("schedule_deferred_open_message_smb: LOGIC ERROR "
     315             :                                         "message mid %llu was already processed\n",
     316             :                                         (unsigned long long)msg_mid ));
     317           0 :                                 continue;
     318             :                         }
     319             : 
     320        4085 :                         DEBUG(10,("schedule_deferred_open_message_smb: "
     321             :                                 "scheduling mid %llu\n",
     322             :                                 (unsigned long long)mid ));
     323             : 
     324             :                         /*
     325             :                          * smbd_deferred_open_timer() calls
     326             :                          * process_smb() to redispatch the request
     327             :                          * including the required impersonation.
     328             :                          *
     329             :                          * So we can just use the raw tevent_context.
     330             :                          */
     331        4085 :                         te = tevent_add_timer(xconn->client->raw_ev_ctx,
     332             :                                               pml,
     333             :                                               timeval_zero(),
     334             :                                               smbd_deferred_open_timer,
     335             :                                               pml);
     336        4085 :                         if (!te) {
     337           0 :                                 DEBUG(10,("schedule_deferred_open_message_smb: "
     338             :                                         "event_add_timed() failed, "
     339             :                                         "skipping mid %llu\n",
     340             :                                         (unsigned long long)msg_mid ));
     341             :                         }
     342             : 
     343        4085 :                         TALLOC_FREE(pml->te);
     344        4085 :                         pml->te = te;
     345        4085 :                         DLIST_PROMOTE(sconn->deferred_open_queue, pml);
     346        4085 :                         return true;
     347             :                 }
     348             :         }
     349             : 
     350           0 :         DEBUG(10,("schedule_deferred_open_message_smb: failed to "
     351             :                 "find message mid %llu\n",
     352             :                 (unsigned long long)mid ));
     353             : 
     354           0 :         return false;
     355             : }
     356             : 
     357             : /****************************************************************************
     358             :  Return true if this mid is on the deferred queue and was not yet processed.
     359             : ****************************************************************************/
     360             : 
     361      141855 : bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
     362             : {
     363      141855 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     364        4932 :         struct pending_message_list *pml;
     365             : 
     366      141855 :         if (sconn->using_smb2) {
     367      105169 :                 return open_was_deferred_smb2(xconn, mid);
     368             :         }
     369             : 
     370       36762 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     371         183 :                 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid && !pml->processed) {
     372         107 :                         return True;
     373             :                 }
     374             :         }
     375       31809 :         return False;
     376             : }
     377             : 
     378             : /****************************************************************************
     379             :  Return the message queued by this mid.
     380             : ****************************************************************************/
     381             : 
     382      161606 : static struct pending_message_list *get_deferred_open_message_smb(
     383             :         struct smbd_server_connection *sconn, uint64_t mid)
     384             : {
     385        2017 :         struct pending_message_list *pml;
     386             : 
     387      161686 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     388        8268 :                 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
     389        8154 :                         return pml;
     390             :                 }
     391             :         }
     392      151435 :         return NULL;
     393             : }
     394             : 
     395             : /****************************************************************************
     396             :  Get the state data queued by this mid.
     397             : ****************************************************************************/
     398             : 
     399     1040269 : bool get_deferred_open_message_state(struct smb_request *smbreq,
     400             :                                 struct timeval *p_request_time,
     401             :                                 struct deferred_open_record **open_rec)
     402             : {
     403        2662 :         struct pending_message_list *pml;
     404             : 
     405     1040269 :         if (smbreq->sconn->using_smb2) {
     406      882748 :                 return get_deferred_open_message_state_smb2(smbreq->smb2req,
     407             :                                         p_request_time,
     408             :                                         open_rec);
     409             :         }
     410             : 
     411      157521 :         pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
     412      157521 :         if (!pml) {
     413      147425 :                 return false;
     414             :         }
     415        8130 :         if (p_request_time) {
     416        4081 :                 *p_request_time = pml->request_time;
     417             :         }
     418        8130 :         if (open_rec != NULL) {
     419        4049 :                 *open_rec = pml->open_rec;
     420             :         }
     421        8096 :         return true;
     422             : }
     423             : 
     424        4565 : bool push_deferred_open_message_smb(struct smb_request *req,
     425             :                                     struct timeval timeout,
     426             :                                     struct file_id id,
     427             :                                     struct deferred_open_record *open_rec)
     428             : {
     429             : #if defined(WITH_SMB1SERVER)
     430        4565 :         if (req->smb2req) {
     431             : #endif
     432         396 :                 return push_deferred_open_message_smb2(req->smb2req,
     433             :                                                 req->request_time,
     434             :                                                 timeout,
     435             :                                                 id,
     436             :                                                 open_rec);
     437             : #if defined(WITH_SMB1SERVER)
     438             :         } else {
     439        4169 :                 return push_deferred_open_message_smb1(req, timeout,
     440             :                                                        id, open_rec);
     441             :         }
     442             : #endif
     443             : }
     444             : 
     445      651086 : static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
     446             :                                    char *outbuf)
     447             : {
     448      651086 :         uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
     449      651086 :         uint16_t out_flags2 = common_flags2;
     450             : 
     451      651086 :         out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
     452      651086 :         out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
     453      651086 :         out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
     454             : 
     455      651086 :         srv_smb1_set_message(outbuf,0,0,false);
     456             : 
     457      651086 :         SCVAL(outbuf, smb_com, cmd);
     458      651086 :         SIVAL(outbuf,smb_rcls,0);
     459      651086 :         SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES));
     460      651086 :         SSVAL(outbuf,smb_flg2, out_flags2);
     461      651086 :         memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
     462      651086 :         memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
     463             : 
     464      651086 :         SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
     465      651086 :         SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
     466      651086 :         SSVAL(outbuf,smb_pidhigh,SVAL(inbuf,smb_pidhigh));
     467      651086 :         SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
     468      651086 :         SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
     469      651086 : }
     470             : 
     471      142047 : void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
     472             : {
     473      142047 :         construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
     474      142047 : }
     475             : 
     476             : /*******************************************************************
     477             :  allocate and initialize a reply packet
     478             : ********************************************************************/
     479             : 
     480      509039 : bool create_smb1_outbuf(TALLOC_CTX *mem_ctx, struct smb_request *req,
     481             :                    const uint8_t *inbuf, char **outbuf,
     482             :                    uint8_t num_words, uint32_t num_bytes)
     483             : {
     484      509039 :         size_t smb_len = MIN_SMB_SIZE + VWV(num_words) + num_bytes;
     485             : 
     486             :         /*
     487             :          * Protect against integer wrap.
     488             :          * The SMB layer reply can be up to 0xFFFFFF bytes.
     489             :          */
     490      509039 :         if ((num_bytes > 0xffffff) || (smb_len > 0xffffff)) {
     491           0 :                 char *msg;
     492           0 :                 if (asprintf(&msg, "num_bytes too large: %u",
     493             :                              (unsigned)num_bytes) == -1) {
     494           0 :                         msg = discard_const_p(char, "num_bytes too large");
     495             :                 }
     496           0 :                 smb_panic(msg);
     497             :         }
     498             : 
     499             :         /*
     500             :          * Here we include the NBT header for now.
     501             :          */
     502      509039 :         *outbuf = talloc_array(mem_ctx, char,
     503             :                                NBT_HDR_SIZE + smb_len);
     504      509039 :         if (*outbuf == NULL) {
     505           0 :                 return false;
     506             :         }
     507             : 
     508      509039 :         construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
     509      509039 :         srv_smb1_set_message(*outbuf, num_words, num_bytes, false);
     510             :         /*
     511             :          * Zero out the word area, the caller has to take care of the bcc area
     512             :          * himself
     513             :          */
     514      509039 :         if (num_words != 0) {
     515      114116 :                 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
     516             :         }
     517             : 
     518      501269 :         return true;
     519             : }
     520             : 
     521      509039 : void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
     522             : {
     523        7770 :         char *outbuf;
     524      509039 :         if (!create_smb1_outbuf(req, req, req->inbuf, &outbuf, num_words,
     525             :                            num_bytes)) {
     526           0 :                 smb_panic("could not allocate output buffer\n");
     527             :         }
     528      509039 :         req->outbuf = (uint8_t *)outbuf;
     529      509039 : }
     530             : 
     531      691688 : bool valid_smb1_header(const uint8_t *inbuf)
     532             : {
     533      691688 :         if (is_encrypted_packet(inbuf)) {
     534           0 :                 return true;
     535             :         }
     536             :         /*
     537             :          * This used to be (strncmp(smb_base(inbuf),"\377SMB",4) == 0)
     538             :          * but it just looks weird to call strncmp for this one.
     539             :          */
     540      691688 :         return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
     541             : }
     542             : 
     543             : /****************************************************************************
     544             :  Process an smb from the client
     545             : ****************************************************************************/
     546             : 
     547          39 : static void process_smb2(struct smbXsrv_connection *xconn,
     548             :                          uint8_t *inbuf,
     549             :                          size_t nread,
     550             :                          size_t unread_bytes,
     551             :                          uint32_t seqnum,
     552             :                          bool encrypted)
     553             : {
     554          39 :         const uint8_t *inpdu = inbuf + NBT_HDR_SIZE;
     555          39 :         size_t pdulen = nread - NBT_HDR_SIZE;
     556          39 :         NTSTATUS status = smbd_smb2_process_negprot(xconn, 0, inpdu, pdulen);
     557          39 :         if (!NT_STATUS_IS_OK(status)) {
     558           0 :                 exit_server_cleanly("SMB2 negprot fail");
     559             :         }
     560          39 : }
     561             : 
     562      655332 : void process_smb(struct smbXsrv_connection *xconn,
     563             :                  uint8_t *inbuf,
     564             :                  size_t nread,
     565             :                  size_t unread_bytes,
     566             :                  uint32_t seqnum,
     567             :                  bool encrypted)
     568             : {
     569      655332 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     570      655332 :         int msg_type = CVAL(inbuf,0);
     571             : 
     572      655332 :         DO_PROFILE_INC(request);
     573             : 
     574      655332 :         DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
     575             :                     smb_len(inbuf) ) );
     576      655332 :         DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
     577             :                   sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
     578             : 
     579      655332 :         if (msg_type != NBSSmessage) {
     580             :                 /*
     581             :                  * NetBIOS session request, keepalive, etc.
     582             :                  */
     583         181 :                 reply_special(xconn, (char *)inbuf, nread);
     584         177 :                 goto done;
     585             :         }
     586             : 
     587             : #if defined(WITH_SMB1SERVER)
     588      655151 :         if (sconn->using_smb2) {
     589             :                 /* At this point we're not really using smb2,
     590             :                  * we make the decision here.. */
     591       11628 :                 if (smbd_is_smb2_header(inbuf, nread)) {
     592             : #endif
     593          39 :                         process_smb2(xconn,
     594             :                                      inbuf,
     595             :                                      nread,
     596             :                                      unread_bytes,
     597             :                                      seqnum,
     598             :                                      encrypted);
     599          39 :                         return;
     600             : #if defined(WITH_SMB1SERVER)
     601             :                 }
     602       11589 :                 if (nread >= smb_size && valid_smb1_header(inbuf)
     603       11589 :                                 && CVAL(inbuf, smb_com) != 0x72) {
     604             :                         /* This is a non-negprot SMB1 packet.
     605             :                            Disable SMB2 from now on. */
     606        5615 :                         sconn->using_smb2 = false;
     607             :                 }
     608             :         }
     609      655112 :         process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted);
     610             : #endif
     611             : 
     612      655189 : done:
     613      655189 :         sconn->num_requests++;
     614             : 
     615             :         /* The timeout_processing function isn't run nearly
     616             :            often enough to implement 'max log size' without
     617             :            overrunning the size of the file by many megabytes.
     618             :            This is especially true if we are running at debug
     619             :            level 10.  Checking every 50 SMBs is a nice
     620             :            tradeoff of performance vs log file size overrun. */
     621             : 
     622      666524 :         if ((sconn->num_requests % 50) == 0 &&
     623       11335 :             need_to_check_log_size()) {
     624          94 :                 change_to_root_user();
     625          94 :                 check_log_size();
     626             :         }
     627             : }
     628             : 
     629       31598 : NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
     630             :                                         enum protocol_types protocol)
     631             : {
     632         886 :         NTSTATUS status;
     633             : 
     634       31598 :         conn->protocol = protocol;
     635             : 
     636       31598 :         if (conn->client->session_table != NULL) {
     637        1106 :                 return NT_STATUS_OK;
     638             :         }
     639             : 
     640       30492 :         if (protocol >= PROTOCOL_SMB2_02) {
     641       24869 :                 status = smb2srv_session_table_init(conn);
     642       24869 :                 if (!NT_STATUS_IS_OK(status)) {
     643           0 :                         conn->protocol = PROTOCOL_NONE;
     644           0 :                         return status;
     645             :                 }
     646             : 
     647       24869 :                 status = smb2srv_open_table_init(conn);
     648       24869 :                 if (!NT_STATUS_IS_OK(status)) {
     649           0 :                         conn->protocol = PROTOCOL_NONE;
     650           0 :                         return status;
     651             :                 }
     652             :         } else {
     653             : #if defined(WITH_SMB1SERVER)
     654        5623 :                 status = smb1srv_session_table_init(conn);
     655        5623 :                 if (!NT_STATUS_IS_OK(status)) {
     656           0 :                         conn->protocol = PROTOCOL_NONE;
     657           0 :                         return status;
     658             :                 }
     659             : 
     660        5623 :                 status = smb1srv_tcon_table_init(conn);
     661        5623 :                 if (!NT_STATUS_IS_OK(status)) {
     662           0 :                         conn->protocol = PROTOCOL_NONE;
     663           0 :                         return status;
     664             :                 }
     665             : 
     666        5623 :                 status = smb1srv_open_table_init(conn);
     667        5623 :                 if (!NT_STATUS_IS_OK(status)) {
     668           0 :                         conn->protocol = PROTOCOL_NONE;
     669           0 :                         return status;
     670             :                 }
     671             : #else
     672             :                 conn->protocol = PROTOCOL_NONE;
     673             :                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
     674             : #endif
     675             :         }
     676             : 
     677       30492 :         set_Protocol(protocol);
     678       30492 :         return NT_STATUS_OK;
     679             : }
     680             : 
     681             : /**
     682             :  * Create a debug string for the connection
     683             :  *
     684             :  * This is allocated to talloc_tos() or a string constant
     685             :  * in certain corner cases. The returned string should
     686             :  * hence not be free'd directly but only via the talloc stack.
     687             :  */
     688          90 : const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
     689             : {
     690           0 :         const char *ret;
     691           0 :         char *addr;
     692             :         /*
     693             :          * TODO: this can be improved later
     694             :          * maybe including the client guid or more
     695             :          */
     696          90 :         addr = tsocket_address_string(xconn->remote_address, talloc_tos());
     697          90 :         if (addr == NULL) {
     698           0 :                 return "<tsocket_address_string() failed>";
     699             :         }
     700             : 
     701          90 :         ret = talloc_asprintf(talloc_tos(), "ptr=%p,id=%llu,addr=%s",
     702          90 :                               xconn, (unsigned long long)xconn->channel_id, addr);
     703          90 :         TALLOC_FREE(addr);
     704          90 :         if (ret == NULL) {
     705           0 :                 return "<talloc_asprintf() failed>";
     706             :         }
     707             : 
     708          90 :         return ret;
     709             : }
     710             : 
     711             : /*
     712             :  * Initialize a struct smb_request from an inbuf
     713             :  */
     714             : 
     715      671553 : bool init_smb1_request(struct smb_request *req,
     716             :                       struct smbd_server_connection *sconn,
     717             :                       struct smbXsrv_connection *xconn,
     718             :                       const uint8_t *inbuf,
     719             :                       size_t unread_bytes, bool encrypted,
     720             :                       uint32_t seqnum)
     721             : {
     722        8269 :         struct smbXsrv_tcon *tcon;
     723        8269 :         NTSTATUS status;
     724        8269 :         NTTIME now;
     725      671553 :         size_t req_size = smb_len(inbuf) + 4;
     726             : 
     727             :         /* Ensure we have at least smb_size bytes. */
     728      671553 :         if (req_size < smb_size) {
     729           0 :                 DEBUG(0,("init_smb1_request: invalid request size %u\n",
     730             :                         (unsigned int)req_size ));
     731           0 :                 return false;
     732             :         }
     733             : 
     734      671553 :         *req = (struct smb_request) { .cmd = 0};
     735             : 
     736      671553 :         req->request_time = timeval_current();
     737      671553 :         now = timeval_to_nttime(&req->request_time);
     738             : 
     739      671553 :         req->cmd    = CVAL(inbuf, smb_com);
     740      671553 :         req->flags2 = SVAL(inbuf, smb_flg2);
     741      671553 :         req->smbpid = SVAL(inbuf, smb_pid);
     742      671553 :         req->mid    = (uint64_t)SVAL(inbuf, smb_mid);
     743      671553 :         req->seqnum = seqnum;
     744      671553 :         req->vuid   = SVAL(inbuf, smb_uid);
     745      671553 :         req->tid    = SVAL(inbuf, smb_tid);
     746      671553 :         req->wct    = CVAL(inbuf, smb_wct);
     747      671553 :         req->vwv    = (const uint16_t *)(inbuf+smb_vwv);
     748      671553 :         req->buflen = smb_buflen(inbuf);
     749      671553 :         req->buf    = (const uint8_t *)smb_buf_const(inbuf);
     750      671553 :         req->unread_bytes = unread_bytes;
     751      671553 :         req->encrypted = encrypted;
     752      671553 :         req->sconn = sconn;
     753      671553 :         req->xconn = xconn;
     754      671553 :         if (xconn != NULL) {
     755      671553 :                 status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
     756      671553 :                 if (NT_STATUS_IS_OK(status)) {
     757      625453 :                         req->conn = tcon->compat;
     758             :                 }
     759             :         }
     760      671553 :         req->posix_pathnames = lp_posix_pathnames();
     761             : 
     762             :         /* Ensure we have at least wct words and 2 bytes of bcc. */
     763      671553 :         if (smb_size + req->wct*2 > req_size) {
     764           0 :                 DEBUG(0,("init_smb1_request: invalid wct number %u (size %u)\n",
     765             :                         (unsigned int)req->wct,
     766             :                         (unsigned int)req_size));
     767           0 :                 return false;
     768             :         }
     769             :         /* Ensure bcc is correct. */
     770      671553 :         if (((const uint8_t *)smb_buf_const(inbuf)) + req->buflen > inbuf + req_size) {
     771           0 :                 DEBUG(0,("init_smb1_request: invalid bcc number %u "
     772             :                         "(wct = %u, size %u)\n",
     773             :                         (unsigned int)req->buflen,
     774             :                         (unsigned int)req->wct,
     775             :                         (unsigned int)req_size));
     776           0 :                 return false;
     777             :         }
     778             : 
     779      663284 :         return true;
     780             : }
     781             : 
     782             : /****************************************************************************
     783             :  Construct a reply to the incoming packet.
     784             : ****************************************************************************/
     785             : 
     786       16402 : static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
     787             :                                         char *inbuf, int size,
     788             :                                         size_t unread_bytes)
     789             : {
     790       16402 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     791         390 :         struct smb_request *req;
     792         390 :         NTSTATUS status;
     793             : 
     794       16402 :         if (!(req = talloc(talloc_tos(), struct smb_request))) {
     795           0 :                 smb_panic("could not allocate smb_request");
     796             :         }
     797             : 
     798       16402 :         if (!init_smb1_request(req, sconn, xconn, (uint8_t *)inbuf, unread_bytes,
     799             :                               false, 0)) {
     800           0 :                 exit_server_cleanly("Invalid SMB request");
     801             :         }
     802             : 
     803       16402 :         req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
     804             : 
     805       16402 :         status = smb2_multi_protocol_reply_negprot(req);
     806       15916 :         if (req->outbuf == NULL) {
     807             :                 /*
     808             :                 * req->outbuf == NULL means we bootstrapped into SMB2.
     809             :                 */
     810       15914 :                 return;
     811             :         }
     812           2 :         if (!NT_STATUS_IS_OK(status)) {
     813           2 :                 if (!smb1_srv_send(req->xconn,
     814           2 :                                    (char *)req->outbuf,
     815             :                                    true,
     816           2 :                                    req->seqnum + 1,
     817           4 :                                    IS_CONN_ENCRYPTED(req->conn) ||
     818           2 :                                            req->encrypted)) {
     819           0 :                         exit_server_cleanly("construct_reply_smb1negprot: "
     820             :                                             "smb1_srv_send failed.");
     821             :                 }
     822           2 :                 TALLOC_FREE(req);
     823             :         } else {
     824             :                 /* This code path should only *ever* bootstrap into SMB2. */
     825           0 :                 exit_server_cleanly("Internal error SMB1negprot didn't reply "
     826             :                                     "with an SMB2 packet");
     827             :         }
     828             : }
     829             : 
     830           0 : static void smbd_server_connection_write_handler(
     831             :         struct smbXsrv_connection *xconn)
     832             : {
     833             :         /* TODO: make write nonblocking */
     834           0 : }
     835             : 
     836       25862 : static void smbd_smb2_server_connection_read_handler(
     837             :                         struct smbXsrv_connection *xconn, int fd)
     838             : {
     839         701 :         char lenbuf[NBT_HDR_SIZE];
     840       25862 :         size_t len = 0;
     841       25862 :         uint8_t *buffer = NULL;
     842       25862 :         size_t bufferlen = 0;
     843         701 :         NTSTATUS status;
     844       25862 :         uint8_t msg_type = 0;
     845             : 
     846             :         /* Read the first 4 bytes - contains length of remainder. */
     847       25862 :         status = read_smb_length_return_keepalive(fd, lenbuf, 0, &len);
     848       25862 :         if (!NT_STATUS_IS_OK(status)) {
     849           5 :                 exit_server_cleanly("failed to receive request length");
     850             :                 return;
     851             :         }
     852             : 
     853             :         /* Integer wrap check. */
     854       25857 :         if (len + NBT_HDR_SIZE < len) {
     855           0 :                 exit_server_cleanly("Invalid length on initial request");
     856             :                 return;
     857             :         }
     858             : 
     859             :         /*
     860             :          * The +4 here can't wrap, we've checked the length above already.
     861             :          */
     862       25857 :         bufferlen = len+NBT_HDR_SIZE;
     863             : 
     864       25857 :         buffer = talloc_array(talloc_tos(), uint8_t, bufferlen);
     865       25857 :         if (buffer == NULL) {
     866           0 :                 DBG_ERR("Could not allocate request inbuf of length %zu\n",
     867             :                         bufferlen);
     868           0 :                 exit_server_cleanly("talloc fail");
     869             :                 return;
     870             :         }
     871             : 
     872             :         /* Copy the NBT_HDR_SIZE length. */
     873       25857 :         memcpy(buffer, lenbuf, sizeof(lenbuf));
     874             : 
     875       25857 :         status = read_packet_remainder(fd, (char *)buffer+NBT_HDR_SIZE, 0, len);
     876       25857 :         if (!NT_STATUS_IS_OK(status)) {
     877           0 :                 exit_server_cleanly("Failed to read remainder of initial request");
     878             :                 return;
     879             :         }
     880             : 
     881             :         /* Check the message type. */
     882       25857 :         msg_type = PULL_LE_U8(buffer,0);
     883       25857 :         if (msg_type == NBSSrequest) {
     884             :                 /*
     885             :                  * clients can send this request before
     886             :                  * bootstrapping into SMB2. Cope with this
     887             :                  * message only, don't allow any other strange
     888             :                  * NBSS types.
     889             :                  */
     890         858 :                 reply_special(xconn, (char *)buffer, bufferlen);
     891         858 :                 xconn->client->sconn->num_requests++;
     892         858 :                 return;
     893             :         }
     894             : 
     895             :         /* Only a 'normal' message type allowed now. */
     896       24999 :         if (msg_type != NBSSmessage) {
     897           0 :                 DBG_ERR("Invalid message type %d\n", msg_type);
     898           0 :                 exit_server_cleanly("Invalid message type for initial request");
     899             :                 return;
     900             :         }
     901             : 
     902             :         /* Could this be an SMB1 negprot bootstrap into SMB2 ? */
     903       24999 :         if (bufferlen < smb_size) {
     904           0 :                 exit_server_cleanly("Invalid initial SMB1 or SMB2 packet");
     905             :                 return;
     906             :         }
     907       24999 :         if (valid_smb1_header(buffer)) {
     908             :                 /* Can *only* allow an SMB1 negprot here. */
     909       16426 :                 uint8_t cmd = PULL_LE_U8(buffer, smb_com);
     910       16426 :                 if (cmd != SMBnegprot) {
     911          24 :                         DBG_ERR("Incorrect SMB1 command 0x%hhx, "
     912             :                                 "should be SMBnegprot (0x72)\n",
     913             :                                 cmd);
     914          24 :                         exit_server_cleanly("Invalid initial SMB1 packet");
     915             :                 }
     916             :                 /* Minimal process_smb(). */
     917       16402 :                 show_msg((char *)buffer);
     918       16402 :                 construct_reply_smb1negprot(xconn, (char *)buffer,
     919             :                                             bufferlen, 0);
     920       15916 :                 xconn->client->sconn->trans_num++;
     921       15916 :                 xconn->client->sconn->num_requests++;
     922       15916 :                 return;
     923             : 
     924        8573 :         } else if (!smbd_is_smb2_header(buffer, bufferlen)) {
     925           0 :                 exit_server_cleanly("Invalid initial SMB2 packet");
     926             :                 return;
     927             :         }
     928             : 
     929             :         /* Here we know we're a valid SMB2 packet. */
     930             : 
     931             :         /*
     932             :          * Point at the start of the SMB2 PDU.
     933             :          * len is the length of the SMB2 PDU.
     934             :          */
     935             : 
     936        8573 :         status = smbd_smb2_process_negprot(xconn,
     937             :                                            0,
     938             :                                            (const uint8_t *)buffer+NBT_HDR_SIZE,
     939             :                                            len);
     940        8573 :         if (!NT_STATUS_IS_OK(status)) {
     941           0 :                 exit_server_cleanly("SMB2 negprot fail");
     942             :         }
     943        8262 :         return;
     944             : }
     945             : 
     946      682670 : static void smbd_server_connection_handler(struct tevent_context *ev,
     947             :                                            struct tevent_fd *fde,
     948             :                                            uint16_t flags,
     949             :                                            void *private_data)
     950             : {
     951        8693 :         struct smbXsrv_connection *xconn =
     952      682670 :                 talloc_get_type_abort(private_data,
     953             :                 struct smbXsrv_connection);
     954             : 
     955      682670 :         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
     956             :                 /*
     957             :                  * we're not supposed to do any io
     958             :                  */
     959           0 :                 TEVENT_FD_NOT_READABLE(xconn->transport.fde);
     960           0 :                 TEVENT_FD_NOT_WRITEABLE(xconn->transport.fde);
     961           0 :                 return;
     962             :         }
     963             : 
     964      682670 :         if (flags & TEVENT_FD_WRITE) {
     965           0 :                 smbd_server_connection_write_handler(xconn);
     966           0 :                 return;
     967             :         }
     968      682670 :         if (flags & TEVENT_FD_READ) {
     969             : #if defined(WITH_SMB1SERVER)
     970      682670 :                 if (lp_server_min_protocol() > PROTOCOL_NT1) {
     971             : #endif
     972       25862 :                         smbd_smb2_server_connection_read_handler(xconn,
     973             :                                                 xconn->transport.sock);
     974             : #if defined(WITH_SMB1SERVER)
     975             :                 } else {
     976      656808 :                         smbd_smb1_server_connection_read_handler(xconn,
     977             :                                                 xconn->transport.sock);
     978             :                 }
     979             : #endif
     980      676490 :                 return;
     981             :         }
     982             : }
     983             : 
     984             : struct smbd_release_ip_state {
     985             :         struct smbXsrv_connection *xconn;
     986             :         struct tevent_immediate *im;
     987             :         char addr[INET6_ADDRSTRLEN];
     988             : };
     989             : 
     990           0 : static void smbd_release_ip_immediate(struct tevent_context *ctx,
     991             :                                       struct tevent_immediate *im,
     992             :                                       void *private_data)
     993             : {
     994           0 :         struct smbd_release_ip_state *state =
     995           0 :                 talloc_get_type_abort(private_data,
     996             :                 struct smbd_release_ip_state);
     997           0 :         struct smbXsrv_connection *xconn = state->xconn;
     998             : 
     999           0 :         if (!NT_STATUS_EQUAL(xconn->transport.status, NT_STATUS_ADDRESS_CLOSED)) {
    1000             :                 /*
    1001             :                  * smbd_server_connection_terminate() already triggered ?
    1002             :                  */
    1003           0 :                 return;
    1004             :         }
    1005             : 
    1006           0 :         smbd_server_connection_terminate(xconn, "CTDB_SRVID_RELEASE_IP");
    1007             : }
    1008             : 
    1009             : /****************************************************************************
    1010             : received when we should release a specific IP
    1011             : ****************************************************************************/
    1012           0 : static int release_ip(struct tevent_context *ev,
    1013             :                       uint32_t src_vnn, uint32_t dst_vnn,
    1014             :                       uint64_t dst_srvid,
    1015             :                       const uint8_t *msg, size_t msglen,
    1016             :                       void *private_data)
    1017             : {
    1018           0 :         struct smbd_release_ip_state *state =
    1019           0 :                 talloc_get_type_abort(private_data,
    1020             :                 struct smbd_release_ip_state);
    1021           0 :         struct smbXsrv_connection *xconn = state->xconn;
    1022           0 :         const char *ip;
    1023           0 :         const char *addr = state->addr;
    1024           0 :         const char *p = addr;
    1025             : 
    1026           0 :         if (msglen == 0) {
    1027           0 :                 return 0;
    1028             :         }
    1029           0 :         if (msg[msglen-1] != '\0') {
    1030           0 :                 return 0;
    1031             :         }
    1032             : 
    1033           0 :         ip = (const char *)msg;
    1034             : 
    1035           0 :         if (!NT_STATUS_IS_OK(xconn->transport.status)) {
    1036             :                 /* avoid recursion */
    1037           0 :                 return 0;
    1038             :         }
    1039             : 
    1040           0 :         if (strncmp("::ffff:", addr, 7) == 0) {
    1041           0 :                 p = addr + 7;
    1042             :         }
    1043             : 
    1044           0 :         DEBUG(10, ("Got release IP message for %s, "
    1045             :                    "our address is %s\n", ip, p));
    1046             : 
    1047           0 :         if ((strcmp(p, ip) == 0) || ((p != addr) && strcmp(addr, ip) == 0)) {
    1048           0 :                 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
    1049             :                         ip));
    1050             :                 /*
    1051             :                  * With SMB2 we should do a clean disconnect,
    1052             :                  * the previous_session_id in the session setup
    1053             :                  * will cleanup the old session, tcons and opens.
    1054             :                  *
    1055             :                  * A clean disconnect is needed in order to support
    1056             :                  * durable handles.
    1057             :                  *
    1058             :                  * Note: typically this is never triggered
    1059             :                  *       as we got a TCP RST (triggered by ctdb event scripts)
    1060             :                  *       before we get CTDB_SRVID_RELEASE_IP.
    1061             :                  *
    1062             :                  * We used to call _exit(1) here, but as this was mostly never
    1063             :                  * triggered and has implication on our process model,
    1064             :                  * we can just use smbd_server_connection_terminate()
    1065             :                  * (also for SMB1).
    1066             :                  *
    1067             :                  * We don't call smbd_server_connection_terminate() directly
    1068             :                  * as we might be called from within ctdbd_migrate(),
    1069             :                  * we need to defer our action to the next event loop
    1070             :                  */
    1071           0 :                 tevent_schedule_immediate(state->im,
    1072             :                                           xconn->client->raw_ev_ctx,
    1073             :                                           smbd_release_ip_immediate,
    1074           0 :                                           state);
    1075             : 
    1076             :                 /*
    1077             :                  * Make sure we don't get any io on the connection.
    1078             :                  */
    1079           0 :                 xconn->transport.status = NT_STATUS_ADDRESS_CLOSED;
    1080           0 :                 return EADDRNOTAVAIL;
    1081             :         }
    1082             : 
    1083           0 :         return 0;
    1084             : }
    1085             : 
    1086           0 : static int match_cluster_movable_ip(uint32_t total_ip_count,
    1087             :                                     const struct sockaddr_storage *ip,
    1088             :                                     bool is_movable_ip,
    1089             :                                     void *private_data)
    1090             : {
    1091           0 :         const struct sockaddr_storage *srv = private_data;
    1092           0 :         struct samba_sockaddr pub_ip = {
    1093             :                 .u = {
    1094             :                         .ss = *ip,
    1095             :                 },
    1096             :         };
    1097           0 :         struct samba_sockaddr srv_ip = {
    1098             :                 .u = {
    1099             :                         .ss = *srv,
    1100             :                 },
    1101             :         };
    1102             : 
    1103           0 :         if (is_movable_ip && sockaddr_equal(&pub_ip.u.sa, &srv_ip.u.sa)) {
    1104           0 :                 return EADDRNOTAVAIL;
    1105             :         }
    1106             : 
    1107           0 :         return 0;
    1108             : }
    1109             : 
    1110           0 : static NTSTATUS smbd_register_ips(struct smbXsrv_connection *xconn,
    1111             :                                   struct sockaddr_storage *srv,
    1112             :                                   struct sockaddr_storage *clnt)
    1113             : {
    1114           0 :         struct smbd_release_ip_state *state;
    1115           0 :         struct ctdbd_connection *cconn;
    1116           0 :         int ret;
    1117             : 
    1118           0 :         cconn = messaging_ctdb_connection();
    1119           0 :         if (cconn == NULL) {
    1120           0 :                 return NT_STATUS_NO_MEMORY;
    1121             :         }
    1122             : 
    1123           0 :         state = talloc_zero(xconn, struct smbd_release_ip_state);
    1124           0 :         if (state == NULL) {
    1125           0 :                 return NT_STATUS_NO_MEMORY;
    1126             :         }
    1127           0 :         state->xconn = xconn;
    1128           0 :         state->im = tevent_create_immediate(state);
    1129           0 :         if (state->im == NULL) {
    1130           0 :                 return NT_STATUS_NO_MEMORY;
    1131             :         }
    1132           0 :         if (print_sockaddr(state->addr, sizeof(state->addr), srv) == NULL) {
    1133           0 :                 return NT_STATUS_NO_MEMORY;
    1134             :         }
    1135             : 
    1136           0 :         if (xconn->client->server_multi_channel_enabled) {
    1137           0 :                 ret = ctdbd_public_ip_foreach(cconn,
    1138             :                                               match_cluster_movable_ip,
    1139             :                                               srv);
    1140           0 :                 if (ret == EADDRNOTAVAIL) {
    1141           0 :                         xconn->has_cluster_movable_ip = true;
    1142           0 :                         DBG_DEBUG("cluster movable IP on %s\n",
    1143             :                                   smbXsrv_connection_dbg(xconn));
    1144           0 :                 } else if (ret != 0) {
    1145           0 :                         DBG_ERR("failed to iterate cluster IPs: %s\n",
    1146             :                                 strerror(ret));
    1147           0 :                         return NT_STATUS_INTERNAL_ERROR;
    1148             :                 }
    1149             :         }
    1150             : 
    1151           0 :         ret = ctdbd_register_ips(cconn, srv, clnt, release_ip, state);
    1152           0 :         if (ret != 0) {
    1153           0 :                 return map_nt_error_from_unix(ret);
    1154             :         }
    1155           0 :         return NT_STATUS_OK;
    1156             : }
    1157             : 
    1158       32143 : static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
    1159             : {
    1160       32143 :         DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
    1161       32143 :         return 0;
    1162             : }
    1163             : 
    1164       32157 : NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
    1165             :                              NTTIME now, struct smbXsrv_connection **_xconn)
    1166             : {
    1167       32157 :         TALLOC_CTX *frame = talloc_stackframe();
    1168         894 :         struct smbXsrv_connection *xconn;
    1169         894 :         struct sockaddr_storage ss_srv;
    1170       32157 :         void *sp_srv = (void *)&ss_srv;
    1171       32157 :         struct sockaddr *sa_srv = (struct sockaddr *)sp_srv;
    1172         894 :         struct sockaddr_storage ss_clnt;
    1173       32157 :         void *sp_clnt = (void *)&ss_clnt;
    1174       32157 :         struct sockaddr *sa_clnt = (struct sockaddr *)sp_clnt;
    1175         894 :         socklen_t sa_socklen;
    1176       32157 :         struct tsocket_address *local_address = NULL;
    1177       32157 :         struct tsocket_address *remote_address = NULL;
    1178       32157 :         const char *remaddr = NULL;
    1179         894 :         char *p;
    1180       32157 :         const char *rhost = NULL;
    1181         894 :         int ret;
    1182         894 :         int tmp;
    1183             : 
    1184       32157 :         *_xconn = NULL;
    1185             : 
    1186       32157 :         DO_PROFILE_INC(connect);
    1187             : 
    1188       32157 :         xconn = talloc_zero(client, struct smbXsrv_connection);
    1189       32157 :         if (xconn == NULL) {
    1190           0 :                 DEBUG(0,("talloc_zero(struct smbXsrv_connection)\n"));
    1191           0 :                 TALLOC_FREE(frame);
    1192           0 :                 return NT_STATUS_NO_MEMORY;
    1193             :         }
    1194       32157 :         talloc_set_destructor(xconn, smbXsrv_connection_destructor);
    1195       32157 :         talloc_steal(frame, xconn);
    1196       32157 :         xconn->client = client;
    1197       32157 :         xconn->connect_time = now;
    1198       32157 :         if (client->next_channel_id != 0) {
    1199       32157 :                 xconn->channel_id = client->next_channel_id++;
    1200             :         }
    1201             : 
    1202       32157 :         xconn->transport.sock = sock_fd;
    1203             : #if defined(WITH_SMB1SERVER)
    1204       32157 :         smbd_echo_init(xconn);
    1205             : #endif
    1206       32157 :         xconn->protocol = PROTOCOL_NONE;
    1207             : 
    1208             :         /* Ensure child is set to blocking mode */
    1209       32157 :         set_blocking(sock_fd,True);
    1210             : 
    1211       32157 :         set_socket_options(sock_fd, "SO_KEEPALIVE");
    1212       32157 :         set_socket_options(sock_fd, lp_socket_options());
    1213             : 
    1214       32157 :         sa_socklen = sizeof(ss_clnt);
    1215       32157 :         ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
    1216       32157 :         if (ret != 0) {
    1217           0 :                 int saved_errno = errno;
    1218           0 :                 int level = (errno == ENOTCONN)?2:0;
    1219           0 :                 DEBUG(level,("getpeername() failed - %s\n",
    1220             :                       strerror(saved_errno)));
    1221           0 :                 TALLOC_FREE(frame);
    1222           0 :                 return map_nt_error_from_unix_common(saved_errno);
    1223             :         }
    1224       32157 :         ret = tsocket_address_bsd_from_sockaddr(xconn,
    1225             :                                                 sa_clnt, sa_socklen,
    1226             :                                                 &remote_address);
    1227       32157 :         if (ret != 0) {
    1228           0 :                 int saved_errno = errno;
    1229           0 :                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
    1230             :                         __location__, strerror(saved_errno)));
    1231           0 :                 TALLOC_FREE(frame);
    1232           0 :                 return map_nt_error_from_unix_common(saved_errno);
    1233             :         }
    1234             : 
    1235       32157 :         sa_socklen = sizeof(ss_srv);
    1236       32157 :         ret = getsockname(sock_fd, sa_srv, &sa_socklen);
    1237       32157 :         if (ret != 0) {
    1238           0 :                 int saved_errno = errno;
    1239           0 :                 int level = (errno == ENOTCONN)?2:0;
    1240           0 :                 DEBUG(level,("getsockname() failed - %s\n",
    1241             :                       strerror(saved_errno)));
    1242           0 :                 TALLOC_FREE(frame);
    1243           0 :                 return map_nt_error_from_unix_common(saved_errno);
    1244             :         }
    1245       32157 :         ret = tsocket_address_bsd_from_sockaddr(xconn,
    1246             :                                                 sa_srv, sa_socklen,
    1247             :                                                 &local_address);
    1248       32157 :         if (ret != 0) {
    1249           0 :                 int saved_errno = errno;
    1250           0 :                 DEBUG(0,("%s: tsocket_address_bsd_from_sockaddr remote failed - %s\n",
    1251             :                         __location__, strerror(saved_errno)));
    1252           0 :                 TALLOC_FREE(frame);
    1253           0 :                 return map_nt_error_from_unix_common(saved_errno);
    1254             :         }
    1255             : 
    1256       32157 :         if (tsocket_address_is_inet(remote_address, "ip")) {
    1257       32157 :                 remaddr = tsocket_address_inet_addr_string(remote_address,
    1258             :                                                            talloc_tos());
    1259       32157 :                 if (remaddr == NULL) {
    1260           0 :                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
    1261             :                                  __location__, strerror(errno)));
    1262           0 :                         TALLOC_FREE(frame);
    1263           0 :                         return NT_STATUS_NO_MEMORY;
    1264             :                 }
    1265             :         } else {
    1266           0 :                 remaddr = "0.0.0.0";
    1267             :         }
    1268             : 
    1269             :         /*
    1270             :          * Before the first packet, check the global hosts allow/ hosts deny
    1271             :          * parameters before doing any parsing of packets passed to us by the
    1272             :          * client. This prevents attacks on our parsing code from hosts not in
    1273             :          * the hosts allow list.
    1274             :          */
    1275             : 
    1276       32157 :         ret = get_remote_hostname(remote_address,
    1277             :                                   &p, talloc_tos());
    1278       32157 :         if (ret < 0) {
    1279           0 :                 int saved_errno = errno;
    1280           0 :                 DEBUG(0,("%s: get_remote_hostname failed - %s\n",
    1281             :                         __location__, strerror(saved_errno)));
    1282           0 :                 TALLOC_FREE(frame);
    1283           0 :                 return map_nt_error_from_unix_common(saved_errno);
    1284             :         }
    1285       32157 :         rhost = p;
    1286       32157 :         if (strequal(rhost, "UNKNOWN")) {
    1287           0 :                 rhost = remaddr;
    1288             :         }
    1289             : 
    1290       32157 :         xconn->local_address = local_address;
    1291       32157 :         xconn->remote_address = remote_address;
    1292       32157 :         xconn->remote_hostname = talloc_strdup(xconn, rhost);
    1293       32157 :         if (xconn->remote_hostname == NULL) {
    1294           0 :                 return NT_STATUS_NO_MEMORY;
    1295             :         }
    1296             : 
    1297       32157 :         if (!srv_init_signing(xconn)) {
    1298           0 :                 DEBUG(0, ("Failed to init smb_signing\n"));
    1299           0 :                 TALLOC_FREE(frame);
    1300           0 :                 return NT_STATUS_INTERNAL_ERROR;
    1301             :         }
    1302             : 
    1303       32157 :         if (!allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1),
    1304             :                           xconn->remote_hostname,
    1305             :                           remaddr)) {
    1306           0 :                 DEBUG( 1, ("Connection denied from %s to %s\n",
    1307             :                            tsocket_address_string(remote_address, talloc_tos()),
    1308             :                            tsocket_address_string(local_address, talloc_tos())));
    1309             : 
    1310             :                 /*
    1311             :                  * We return a valid xconn
    1312             :                  * so that the caller can return an error message
    1313             :                  * to the client
    1314             :                  */
    1315           0 :                 DLIST_ADD_END(client->connections, xconn);
    1316           0 :                 talloc_steal(client, xconn);
    1317             : 
    1318           0 :                 *_xconn = xconn;
    1319           0 :                 TALLOC_FREE(frame);
    1320           0 :                 return NT_STATUS_NETWORK_ACCESS_DENIED;
    1321             :         }
    1322             : 
    1323       32157 :         DEBUG(10, ("Connection allowed from %s to %s\n",
    1324             :                    tsocket_address_string(remote_address, talloc_tos()),
    1325             :                    tsocket_address_string(local_address, talloc_tos())));
    1326             : 
    1327       32157 :         if (lp_clustering()) {
    1328             :                 /*
    1329             :                  * We need to tell ctdb about our client's TCP
    1330             :                  * connection, so that for failover ctdbd can send
    1331             :                  * tickle acks, triggering a reconnection by the
    1332             :                  * client.
    1333             :                  */
    1334           0 :                 NTSTATUS status;
    1335             : 
    1336           0 :                 status = smbd_register_ips(xconn, &ss_srv, &ss_clnt);
    1337           0 :                 if (!NT_STATUS_IS_OK(status)) {
    1338           0 :                         DEBUG(0, ("ctdbd_register_ips failed: %s\n",
    1339             :                                   nt_errstr(status)));
    1340             :                 }
    1341             :         }
    1342             : 
    1343       32157 :         tmp = lp_max_xmit();
    1344       32157 :         tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
    1345       32157 :         tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
    1346             : 
    1347             : #if defined(WITH_SMB1SERVER)
    1348       32157 :         xconn->smb1.negprot.max_recv = tmp;
    1349             : 
    1350       32157 :         xconn->smb1.sessions.done_sesssetup = false;
    1351       32157 :         xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
    1352             : #endif
    1353             : 
    1354       32157 :         xconn->transport.fde = tevent_add_fd(client->raw_ev_ctx,
    1355             :                                              xconn,
    1356             :                                              sock_fd,
    1357             :                                              TEVENT_FD_READ,
    1358             :                                              smbd_server_connection_handler,
    1359             :                                              xconn);
    1360       32157 :         if (!xconn->transport.fde) {
    1361           0 :                 TALLOC_FREE(frame);
    1362           0 :                 return NT_STATUS_NO_MEMORY;
    1363             :         }
    1364       32157 :         tevent_fd_set_auto_close(xconn->transport.fde);
    1365             : 
    1366             :         /* for now we only have one connection */
    1367       32157 :         DLIST_ADD_END(client->connections, xconn);
    1368       32157 :         talloc_steal(client, xconn);
    1369             : 
    1370       32157 :         *_xconn = xconn;
    1371       32157 :         TALLOC_FREE(frame);
    1372       32157 :         return NT_STATUS_OK;
    1373             : }
    1374             : 
    1375           0 : static bool uid_in_use(struct auth_session_info *session_info,
    1376             :                        uid_t uid)
    1377             : {
    1378           0 :         if (session_info->unix_token->uid == uid) {
    1379           0 :                 return true;
    1380             :         }
    1381           0 :         return false;
    1382             : }
    1383             : 
    1384           0 : static bool gid_in_use(struct auth_session_info *session_info,
    1385             :                        gid_t gid)
    1386             : {
    1387           0 :         uint32_t i;
    1388           0 :         struct security_unix_token *utok = NULL;
    1389             : 
    1390           0 :         utok = session_info->unix_token;
    1391           0 :         if (utok->gid == gid) {
    1392           0 :                 return true;
    1393             :         }
    1394             : 
    1395           0 :         for(i = 0; i < utok->ngroups; i++) {
    1396           0 :                 if (utok->groups[i] == gid) {
    1397           0 :                         return true;
    1398             :                 }
    1399             :         }
    1400           0 :         return false;
    1401             : }
    1402             : 
    1403           0 : static bool sid_in_use(struct auth_session_info *session_info,
    1404             :                        const struct dom_sid *psid)
    1405             : {
    1406           0 :         struct security_token *tok = NULL;
    1407             : 
    1408           0 :         tok = session_info->security_token;
    1409           0 :         if (tok == NULL) {
    1410             :                 /*
    1411             :                  * Not sure session_info->security_token can
    1412             :                  * ever be NULL. This check might be not
    1413             :                  * necessary.
    1414             :                  */
    1415           0 :                 return false;
    1416             :         }
    1417           0 :         if (security_token_has_sid(tok, psid)) {
    1418           0 :                 return true;
    1419             :         }
    1420           0 :         return false;
    1421             : }
    1422             : 
    1423             : struct id_in_use_state {
    1424             :         const struct id_cache_ref *id;
    1425             :         bool match;
    1426             : };
    1427             : 
    1428           0 : static int id_in_use_cb(struct smbXsrv_session *session,
    1429             :                         void *private_data)
    1430             : {
    1431           0 :         struct id_in_use_state *state = (struct id_in_use_state *)
    1432             :                 private_data;
    1433           0 :         struct auth_session_info *session_info =
    1434           0 :                 session->global->auth_session_info;
    1435             : 
    1436           0 :         switch(state->id->type) {
    1437           0 :         case UID:
    1438           0 :                 state->match = uid_in_use(session_info, state->id->id.uid);
    1439           0 :                 break;
    1440           0 :         case GID:
    1441           0 :                 state->match = gid_in_use(session_info, state->id->id.gid);
    1442           0 :                 break;
    1443           0 :         case SID:
    1444           0 :                 state->match = sid_in_use(session_info, &state->id->id.sid);
    1445           0 :                 break;
    1446           0 :         default:
    1447           0 :                 state->match = false;
    1448           0 :                 break;
    1449             :         }
    1450           0 :         if (state->match) {
    1451           0 :                 return -1;
    1452             :         }
    1453           0 :         return 0;
    1454             : }
    1455             : 
    1456           0 : static bool id_in_use(struct smbd_server_connection *sconn,
    1457             :                       const struct id_cache_ref *id)
    1458             : {
    1459           0 :         struct id_in_use_state state;
    1460           0 :         NTSTATUS status;
    1461             : 
    1462           0 :         state = (struct id_in_use_state) {
    1463             :                 .id = id,
    1464             :                 .match = false,
    1465             :         };
    1466             : 
    1467           0 :         status = smbXsrv_session_local_traverse(sconn->client,
    1468             :                                                 id_in_use_cb,
    1469             :                                                 &state);
    1470           0 :         if (!NT_STATUS_IS_OK(status)) {
    1471           0 :                 return false;
    1472             :         }
    1473             : 
    1474           0 :         return state.match;
    1475             : }
    1476             : 
    1477             : /****************************************************************************
    1478             :  Check if services need reloading.
    1479             : ****************************************************************************/
    1480             : 
    1481         487 : static void check_reload(struct smbd_server_connection *sconn, time_t t)
    1482             : {
    1483             : 
    1484         487 :         if (last_smb_conf_reload_time == 0) {
    1485         102 :                 last_smb_conf_reload_time = t;
    1486             :         }
    1487             : 
    1488         487 :         if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
    1489         101 :                 reload_services(sconn, conn_snum_used, true);
    1490         101 :                 last_smb_conf_reload_time = t;
    1491             :         }
    1492         487 : }
    1493             : 
    1494           0 : static void msg_kill_client_ip(struct messaging_context *msg_ctx,
    1495             :                                   void *private_data, uint32_t msg_type,
    1496             :                                   struct server_id server_id, DATA_BLOB *data)
    1497             : {
    1498           0 :         struct smbd_server_connection *sconn = talloc_get_type_abort(
    1499             :                 private_data, struct smbd_server_connection);
    1500           0 :         const char *ip = (char *) data->data;
    1501           0 :         char *client_ip;
    1502             : 
    1503           0 :         DBG_DEBUG("Got kill request for client IP %s\n", ip);
    1504             : 
    1505           0 :         client_ip = tsocket_address_inet_addr_string(sconn->remote_address,
    1506             :                                                      talloc_tos());
    1507           0 :         if (client_ip == NULL) {
    1508           0 :                 return;
    1509             :         }
    1510             : 
    1511           0 :         if (strequal(ip, client_ip)) {
    1512           0 :                 DBG_WARNING("Got kill client message for %s - "
    1513             :                             "exiting immediately\n", ip);
    1514           0 :                 exit_server_cleanly("Forced disconnect for client");
    1515             :         }
    1516             : 
    1517           0 :         TALLOC_FREE(client_ip);
    1518             : }
    1519             : 
    1520             : /*
    1521             :  * Do the recurring check if we're idle
    1522             :  */
    1523         491 : static bool deadtime_fn(const struct timeval *now, void *private_data)
    1524             : {
    1525         491 :         struct smbd_server_connection *sconn =
    1526             :                 (struct smbd_server_connection *)private_data;
    1527             : 
    1528         491 :         if ((conn_num_open(sconn) == 0)
    1529         489 :             || (conn_idle_all(sconn, now->tv_sec))) {
    1530           4 :                 DEBUG( 2, ( "Closing idle connection\n" ) );
    1531           4 :                 messaging_send(sconn->msg_ctx,
    1532           4 :                                messaging_server_id(sconn->msg_ctx),
    1533             :                                MSG_SHUTDOWN, &data_blob_null);
    1534           4 :                 return False;
    1535             :         }
    1536             : 
    1537         487 :         return True;
    1538             : }
    1539             : 
    1540             : /*
    1541             :  * Do the recurring log file and smb.conf reload checks.
    1542             :  */
    1543             : 
    1544         487 : static bool housekeeping_fn(const struct timeval *now, void *private_data)
    1545             : {
    1546         487 :         struct smbd_server_connection *sconn = talloc_get_type_abort(
    1547             :                 private_data, struct smbd_server_connection);
    1548             : 
    1549         487 :         DEBUG(5, ("housekeeping\n"));
    1550             : 
    1551         487 :         change_to_root_user();
    1552             : 
    1553             :         /* check if we need to reload services */
    1554         487 :         check_reload(sconn, time_mono(NULL));
    1555             : 
    1556             :         /*
    1557             :          * Force a log file check.
    1558             :          */
    1559         487 :         force_check_log_size();
    1560         487 :         check_log_size();
    1561         487 :         return true;
    1562             : }
    1563             : 
    1564          14 : static void smbd_sig_term_handler(struct tevent_context *ev,
    1565             :                                   struct tevent_signal *se,
    1566             :                                   int signum,
    1567             :                                   int count,
    1568             :                                   void *siginfo,
    1569             :                                   void *private_data)
    1570             : {
    1571          14 :         exit_server_cleanly("termination signal");
    1572             : }
    1573             : 
    1574       31051 : static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
    1575             : {
    1576         842 :         struct tevent_signal *se;
    1577             : 
    1578       31051 :         se = tevent_add_signal(sconn->ev_ctx,
    1579             :                                sconn,
    1580             :                                SIGTERM, 0,
    1581             :                                smbd_sig_term_handler,
    1582             :                                sconn);
    1583       31051 :         if (!se) {
    1584           0 :                 exit_server("failed to setup SIGTERM handler");
    1585             :         }
    1586       31051 : }
    1587             : 
    1588           0 : static void smbd_sig_hup_handler(struct tevent_context *ev,
    1589             :                                   struct tevent_signal *se,
    1590             :                                   int signum,
    1591             :                                   int count,
    1592             :                                   void *siginfo,
    1593             :                                   void *private_data)
    1594             : {
    1595           0 :         struct smbd_server_connection *sconn =
    1596           0 :                 talloc_get_type_abort(private_data,
    1597             :                 struct smbd_server_connection);
    1598             : 
    1599           0 :         change_to_root_user();
    1600           0 :         DEBUG(1,("Reloading services after SIGHUP\n"));
    1601           0 :         reload_services(sconn, conn_snum_used, false);
    1602           0 : }
    1603             : 
    1604       31051 : static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
    1605             : {
    1606         842 :         struct tevent_signal *se;
    1607             : 
    1608       31051 :         se = tevent_add_signal(sconn->ev_ctx,
    1609             :                                sconn,
    1610             :                                SIGHUP, 0,
    1611             :                                smbd_sig_hup_handler,
    1612             :                                sconn);
    1613       31051 :         if (!se) {
    1614           0 :                 exit_server("failed to setup SIGHUP handler");
    1615             :         }
    1616       31051 : }
    1617             : 
    1618         679 : static void smbd_conf_updated(struct messaging_context *msg,
    1619             :                               void *private_data,
    1620             :                               uint32_t msg_type,
    1621             :                               struct server_id server_id,
    1622             :                               DATA_BLOB *data)
    1623             : {
    1624           0 :         struct smbd_server_connection *sconn =
    1625         679 :                 talloc_get_type_abort(private_data,
    1626             :                 struct smbd_server_connection);
    1627             : 
    1628         679 :         DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
    1629             :                   "updated. Reloading.\n"));
    1630         679 :         change_to_root_user();
    1631         679 :         reload_services(sconn, conn_snum_used, false);
    1632         679 : }
    1633             : 
    1634           0 : static void smbd_id_cache_kill(struct messaging_context *msg_ctx,
    1635             :                                void *private_data,
    1636             :                                uint32_t msg_type,
    1637             :                                struct server_id server_id,
    1638             :                                DATA_BLOB* data)
    1639             : {
    1640           0 :         const char *msg = (data && data->data)
    1641           0 :                 ? (const char *)data->data : "<NULL>";
    1642           0 :         struct id_cache_ref id;
    1643           0 :         struct smbd_server_connection *sconn =
    1644           0 :                 talloc_get_type_abort(private_data,
    1645             :                 struct smbd_server_connection);
    1646             : 
    1647           0 :         if (!id_cache_ref_parse(msg, &id)) {
    1648           0 :                 DEBUG(0, ("Invalid ?ID: %s\n", msg));
    1649           0 :                 return;
    1650             :         }
    1651             : 
    1652           0 :         if (id_in_use(sconn, &id)) {
    1653           0 :                 exit_server_cleanly(msg);
    1654             :         }
    1655           0 :         id_cache_delete_from_cache(&id);
    1656             : }
    1657             : 
    1658             : struct smbd_tevent_trace_state {
    1659             :         struct tevent_context *ev;
    1660             :         TALLOC_CTX *frame;
    1661             :         SMBPROFILE_BASIC_ASYNC_STATE(profile_idle);
    1662             : };
    1663             : 
    1664     4845786 : static inline void smbd_tevent_trace_callback_before_loop_once(
    1665             :         struct smbd_tevent_trace_state *state)
    1666             : {
    1667     4845786 :         talloc_free(state->frame);
    1668     4845786 :         state->frame = talloc_stackframe_pool(8192);
    1669     4845786 : }
    1670             : 
    1671     4814735 : static inline void smbd_tevent_trace_callback_after_loop_once(
    1672             :         struct smbd_tevent_trace_state *state)
    1673             : {
    1674     4814735 :         TALLOC_FREE(state->frame);
    1675     4756720 : }
    1676             : 
    1677    16322301 : static void smbd_tevent_trace_callback(enum tevent_trace_point point,
    1678             :                                        void *private_data)
    1679             : {
    1680    16322301 :         struct smbd_tevent_trace_state *state =
    1681             :                 (struct smbd_tevent_trace_state *)private_data;
    1682             : 
    1683    16322301 :         switch (point) {
    1684     3297413 :         case TEVENT_TRACE_BEFORE_WAIT:
    1685     3297413 :                 break;
    1686     3297413 :         case TEVENT_TRACE_AFTER_WAIT:
    1687     3297413 :                 break;
    1688     4845786 :         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
    1689     4845786 :                 smbd_tevent_trace_callback_before_loop_once(state);
    1690     4845786 :                 break;
    1691     4756720 :         case TEVENT_TRACE_AFTER_LOOP_ONCE:
    1692     4814735 :                 smbd_tevent_trace_callback_after_loop_once(state);
    1693     4756720 :                 break;
    1694             :         }
    1695             : 
    1696    16322301 :         errno = 0;
    1697    16322301 : }
    1698             : 
    1699           0 : static void smbd_tevent_trace_callback_profile(enum tevent_trace_point point,
    1700             :                                                void *private_data)
    1701             : {
    1702           0 :         struct smbd_tevent_trace_state *state =
    1703             :                 (struct smbd_tevent_trace_state *)private_data;
    1704             : 
    1705           0 :         switch (point) {
    1706           0 :         case TEVENT_TRACE_BEFORE_WAIT:
    1707           0 :                 if (!smbprofile_dump_pending()) {
    1708             :                         /*
    1709             :                          * If there's no dump pending
    1710             :                          * we don't want to schedule a new 1 sec timer.
    1711             :                          *
    1712             :                          * Instead we want to sleep as long as nothing happens.
    1713             :                          */
    1714           0 :                         smbprofile_dump_setup(NULL);
    1715             :                 }
    1716           0 :                 SMBPROFILE_BASIC_ASYNC_START(idle, profile_p, state->profile_idle);
    1717           0 :                 break;
    1718           0 :         case TEVENT_TRACE_AFTER_WAIT:
    1719           0 :                 SMBPROFILE_BASIC_ASYNC_END(state->profile_idle);
    1720           0 :                 if (!smbprofile_dump_pending()) {
    1721             :                         /*
    1722             :                          * We need to flush our state after sleeping
    1723             :                          * (hopefully a long time).
    1724             :                          */
    1725           0 :                         smbprofile_dump();
    1726             :                         /*
    1727             :                          * future profiling events should trigger timers
    1728             :                          * on our main event context.
    1729             :                          */
    1730           0 :                         smbprofile_dump_setup(state->ev);
    1731             :                 }
    1732           0 :                 break;
    1733           0 :         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
    1734           0 :                 smbd_tevent_trace_callback_before_loop_once(state);
    1735           0 :                 break;
    1736           0 :         case TEVENT_TRACE_AFTER_LOOP_ONCE:
    1737           0 :                 smbd_tevent_trace_callback_after_loop_once(state);
    1738           0 :                 break;
    1739             :         }
    1740             : 
    1741           0 :         errno = 0;
    1742           0 : }
    1743             : 
    1744             : /****************************************************************************
    1745             :  Process commands from the client
    1746             : ****************************************************************************/
    1747             : 
    1748       31051 : void smbd_process(struct tevent_context *ev_ctx,
    1749             :                   struct messaging_context *msg_ctx,
    1750             :                   int sock_fd,
    1751             :                   bool interactive)
    1752             : {
    1753       62102 :         struct smbd_tevent_trace_state trace_state = {
    1754             :                 .ev = ev_ctx,
    1755       31051 :                 .frame = talloc_stackframe(),
    1756             :         };
    1757         842 :         const struct loadparm_substitution *lp_sub =
    1758       31051 :                 loadparm_s3_global_substitution();
    1759       31051 :         struct smbXsrv_client *client = NULL;
    1760       31051 :         struct smbd_server_connection *sconn = NULL;
    1761       31051 :         struct smbXsrv_connection *xconn = NULL;
    1762       31051 :         const char *locaddr = NULL;
    1763       31051 :         const char *remaddr = NULL;
    1764         842 :         int ret;
    1765         842 :         NTSTATUS status;
    1766       31051 :         struct timeval tv = timeval_current();
    1767       31051 :         NTTIME now = timeval_to_nttime(&tv);
    1768       31051 :         char *chroot_dir = NULL;
    1769         842 :         int rc;
    1770             : 
    1771       31051 :         status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
    1772       31051 :         if (!NT_STATUS_IS_OK(status)) {
    1773           0 :                 DBG_ERR("smbXsrv_client_create(): %s\n", nt_errstr(status));
    1774           0 :                 exit_server_cleanly("talloc_zero(struct smbXsrv_client).\n");
    1775             :         }
    1776             : 
    1777             :         /*
    1778             :          * TODO: remove this...:-)
    1779             :          */
    1780       31051 :         global_smbXsrv_client = client;
    1781             : 
    1782       31051 :         sconn = talloc_zero(client, struct smbd_server_connection);
    1783       31051 :         if (sconn == NULL) {
    1784           0 :                 exit_server("failed to create smbd_server_connection");
    1785             :         }
    1786             : 
    1787       31051 :         client->sconn = sconn;
    1788       31051 :         sconn->client = client;
    1789             : 
    1790       31051 :         sconn->ev_ctx = ev_ctx;
    1791       31051 :         sconn->msg_ctx = msg_ctx;
    1792             : 
    1793       31051 :         ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
    1794             :                                       &sconn->pool);
    1795       31051 :         if (ret != 0) {
    1796           0 :                 exit_server("pthreadpool_tevent_init() failed.");
    1797             :         }
    1798             : 
    1799             : #if defined(WITH_SMB1SERVER)
    1800       31051 :         if (lp_server_max_protocol() >= PROTOCOL_SMB2_02) {
    1801             : #endif
    1802             :                 /*
    1803             :                  * We're not making the decision here,
    1804             :                  * we're just allowing the client
    1805             :                  * to decide between SMB1 and SMB2
    1806             :                  * with the first negprot
    1807             :                  * packet.
    1808             :                  */
    1809       31051 :                 sconn->using_smb2 = true;
    1810             : #if defined(WITH_SMB1SERVER)
    1811             :         }
    1812             : #endif
    1813             : 
    1814       31051 :         if (!interactive) {
    1815       31051 :                 smbd_setup_sig_term_handler(sconn);
    1816       31051 :                 smbd_setup_sig_hup_handler(sconn);
    1817             :         }
    1818             : 
    1819       31051 :         status = smbd_add_connection(client, sock_fd, now, &xconn);
    1820       31051 :         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
    1821             :                 /*
    1822             :                  * send a negative session response "not listening on calling
    1823             :                  * name"
    1824             :                  */
    1825           0 :                 unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
    1826           0 :                 (void)smb1_srv_send(xconn, (char *)buf, false, 0, false);
    1827           0 :                 exit_server_cleanly("connection denied");
    1828       31051 :         } else if (!NT_STATUS_IS_OK(status)) {
    1829           0 :                 exit_server_cleanly(nt_errstr(status));
    1830             :         }
    1831             : 
    1832       31893 :         sconn->local_address =
    1833       31051 :                 tsocket_address_copy(xconn->local_address, sconn);
    1834       31051 :         if (sconn->local_address == NULL) {
    1835           0 :                 exit_server_cleanly("tsocket_address_copy() failed");
    1836             :         }
    1837       31893 :         sconn->remote_address =
    1838       31051 :                 tsocket_address_copy(xconn->remote_address, sconn);
    1839       31051 :         if (sconn->remote_address == NULL) {
    1840           0 :                 exit_server_cleanly("tsocket_address_copy() failed");
    1841             :         }
    1842       31893 :         sconn->remote_hostname =
    1843       31051 :                 talloc_strdup(sconn, xconn->remote_hostname);
    1844       31051 :         if (sconn->remote_hostname == NULL) {
    1845           0 :                 exit_server_cleanly("tsocket_strdup() failed");
    1846             :         }
    1847             : 
    1848       62102 :         client->global->local_address =
    1849       31051 :                 tsocket_address_string(sconn->local_address,
    1850       31051 :                                        client->global);
    1851       31051 :         if (client->global->local_address == NULL) {
    1852           0 :                 exit_server_cleanly("tsocket_address_string() failed");
    1853             :         }
    1854       62102 :         client->global->remote_address =
    1855       31051 :                 tsocket_address_string(sconn->remote_address,
    1856       30209 :                                        client->global);
    1857       31051 :         if (client->global->remote_address == NULL) {
    1858           0 :                 exit_server_cleanly("tsocket_address_string() failed");
    1859             :         }
    1860       62102 :         client->global->remote_name =
    1861       31051 :                 talloc_strdup(client->global, sconn->remote_hostname);
    1862       31051 :         if (client->global->remote_name == NULL) {
    1863           0 :                 exit_server_cleanly("tsocket_strdup() failed");
    1864             :         }
    1865             : 
    1866       31051 :         if (tsocket_address_is_inet(sconn->local_address, "ip")) {
    1867       31051 :                 locaddr = tsocket_address_inet_addr_string(
    1868             :                                 sconn->local_address,
    1869             :                                 talloc_tos());
    1870       31051 :                 if (locaddr == NULL) {
    1871           0 :                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
    1872             :                                  __location__, strerror(errno)));
    1873           0 :                         exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
    1874             :                 }
    1875             :         } else {
    1876           0 :                 locaddr = "0.0.0.0";
    1877             :         }
    1878             : 
    1879       31051 :         if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
    1880       31051 :                 remaddr = tsocket_address_inet_addr_string(
    1881             :                                 sconn->remote_address,
    1882             :                                 talloc_tos());
    1883       31051 :                 if (remaddr == NULL) {
    1884           0 :                         DEBUG(0,("%s: tsocket_address_inet_addr_string remote failed - %s\n",
    1885             :                                  __location__, strerror(errno)));
    1886           0 :                         exit_server_cleanly("tsocket_address_inet_addr_string remote failed.\n");
    1887             :                 }
    1888             :         } else {
    1889           0 :                 remaddr = "0.0.0.0";
    1890             :         }
    1891             : 
    1892             :         /* this is needed so that we get decent entries
    1893             :            in smbstatus for port 445 connects */
    1894       31051 :         set_remote_machine_name(remaddr, false);
    1895       31051 :         reload_services(sconn, conn_snum_used, true);
    1896       31051 :         sub_set_socket_ids(remaddr,
    1897             :                            sconn->remote_hostname,
    1898             :                            locaddr);
    1899             : 
    1900       31051 :         if (lp_preload_modules()) {
    1901           0 :                 smb_load_all_modules_absoute_path(lp_preload_modules());
    1902             :         }
    1903             : 
    1904       31051 :         if (!init_account_policy()) {
    1905           0 :                 exit_server("Could not open account policy tdb.\n");
    1906             :         }
    1907             : 
    1908       31051 :         chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
    1909       31051 :         if (chroot_dir[0] != '\0') {
    1910           0 :                 rc = chdir(chroot_dir);
    1911           0 :                 if (rc != 0) {
    1912           0 :                         DBG_ERR("Failed to chdir to %s\n", chroot_dir);
    1913           0 :                         exit_server("Failed to chdir()");
    1914             :                 }
    1915             : 
    1916           0 :                 rc = chroot(chroot_dir);
    1917           0 :                 if (rc != 0) {
    1918           0 :                         DBG_ERR("Failed to change root to %s\n", chroot_dir);
    1919           0 :                         exit_server("Failed to chroot()");
    1920             :                 }
    1921           0 :                 DBG_WARNING("Changed root to %s\n", chroot_dir);
    1922             : 
    1923           0 :                 TALLOC_FREE(chroot_dir);
    1924             :         }
    1925             : 
    1926       31051 :         if (!file_init(sconn)) {
    1927           0 :                 exit_server("file_init() failed");
    1928             :         }
    1929             : 
    1930             :         /* Setup oplocks */
    1931       31051 :         if (!init_oplocks(sconn))
    1932           0 :                 exit_server("Failed to init oplocks");
    1933             : 
    1934             :         /* register our message handlers */
    1935       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1936             :                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
    1937       31051 :         messaging_register(
    1938             :                 sconn->msg_ctx,
    1939             :                 sconn,
    1940             :                 MSG_SMB_FORCE_TDIS_DENIED,
    1941             :                 msg_force_tdis_denied);
    1942       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1943             :                            MSG_SMB_CLOSE_FILE, msg_close_file);
    1944       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1945             :                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
    1946             : 
    1947       31051 :         id_cache_register_msgs(sconn->msg_ctx);
    1948       31051 :         messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
    1949       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1950             :                            ID_CACHE_KILL, smbd_id_cache_kill);
    1951             : 
    1952       31051 :         messaging_deregister(sconn->msg_ctx,
    1953       31051 :                              MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
    1954       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1955             :                            MSG_SMB_CONF_UPDATED, smbd_conf_updated);
    1956             : 
    1957       31051 :         messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
    1958             :                              NULL);
    1959       31051 :         messaging_register(sconn->msg_ctx, sconn,
    1960             :                            MSG_SMB_KILL_CLIENT_IP,
    1961             :                            msg_kill_client_ip);
    1962             : 
    1963       31051 :         messaging_deregister(sconn->msg_ctx, MSG_SMB_TELL_NUM_CHILDREN, NULL);
    1964             : 
    1965             :         /*
    1966             :          * Use the default MSG_DEBUG handler to avoid rebroadcasting
    1967             :          * MSGs to all child processes
    1968             :          */
    1969       31051 :         messaging_deregister(sconn->msg_ctx,
    1970             :                              MSG_DEBUG, NULL);
    1971       31051 :         messaging_register(sconn->msg_ctx, NULL,
    1972             :                            MSG_DEBUG, debug_message);
    1973             : 
    1974             : #if defined(WITH_SMB1SERVER)
    1975       31051 :         if ((lp_keepalive() != 0)
    1976       31051 :             && !(event_add_idle(ev_ctx, NULL,
    1977       31051 :                                 timeval_set(lp_keepalive(), 0),
    1978             :                                 "keepalive", keepalive_fn,
    1979             :                                 sconn))) {
    1980           0 :                 DEBUG(0, ("Could not add keepalive event\n"));
    1981           0 :                 exit(1);
    1982             :         }
    1983             : #endif
    1984             : 
    1985       31051 :         if (!(event_add_idle(ev_ctx, NULL,
    1986             :                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
    1987             :                              "deadtime", deadtime_fn, sconn))) {
    1988           0 :                 DEBUG(0, ("Could not add deadtime event\n"));
    1989           0 :                 exit(1);
    1990             :         }
    1991             : 
    1992       31051 :         if (!(event_add_idle(ev_ctx, NULL,
    1993             :                              timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
    1994             :                              "housekeeping", housekeeping_fn, sconn))) {
    1995           0 :                 DEBUG(0, ("Could not add housekeeping event\n"));
    1996           0 :                 exit(1);
    1997             :         }
    1998             : 
    1999       31051 :         smbprofile_dump_setup(ev_ctx);
    2000             : 
    2001       31051 :         if (!init_dptrs(sconn)) {
    2002           0 :                 exit_server("init_dptrs() failed");
    2003             :         }
    2004             : 
    2005       31051 :         TALLOC_FREE(trace_state.frame);
    2006             : 
    2007       31051 :         if (smbprofile_active()) {
    2008           0 :                 tevent_set_trace_callback(ev_ctx,
    2009             :                                           smbd_tevent_trace_callback_profile,
    2010             :                                           &trace_state);
    2011             :         } else {
    2012       31051 :                 tevent_set_trace_callback(ev_ctx,
    2013             :                                           smbd_tevent_trace_callback,
    2014             :                                           &trace_state);
    2015             :         }
    2016             : 
    2017       31051 :         ret = tevent_loop_wait(ev_ctx);
    2018           0 :         if (ret != 0) {
    2019           0 :                 DEBUG(1, ("tevent_loop_wait failed: %d, %s,"
    2020             :                           " exiting\n", ret, strerror(errno)));
    2021             :         }
    2022             : 
    2023           0 :         TALLOC_FREE(trace_state.frame);
    2024             : 
    2025           0 :         exit_server_cleanly(NULL);
    2026             : }

Generated by: LCOV version 1.14