LCOV - code coverage report
Current view: top level - source3/smbd - smb2_process.c (source / functions) Hit Total Coverage
Test: coverage report for vadcx-master-patch-75612 fe003de8 Lines: 527 859 61.4 %
Date: 2024-02-29 22:57:05 Functions: 36 51 70.6 %

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

Generated by: LCOV version 1.14