LCOV - code coverage report
Current view: top level - source3/smbd - smb2_process.c (source / functions) Hit Total Coverage
Test: coverage report for master 2b515b7d Lines: 532 891 59.7 %
Date: 2024-02-28 12:06:22 Functions: 37 54 68.5 %

          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           7 : 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           7 :         size_t len = 0;
      77             :         ssize_t ret;
      78           7 :         len = smb_len_large(buffer) + 4;
      79           7 :         ret = write_data(xconn->transport.sock, buffer, len);
      80           7 :         return (ret > 0);
      81             : }
      82             : #endif
      83             : 
      84             : /*******************************************************************
      85             :  Setup the word count and byte count for a smb1 message.
      86             : ********************************************************************/
      87             : 
      88     1317900 : size_t srv_smb1_set_message(char *buf,
      89             :                        size_t num_words,
      90             :                        size_t num_bytes,
      91             :                        bool zero)
      92             : {
      93     1317900 :         if (zero && (num_words || num_bytes)) {
      94      142044 :                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
      95             :         }
      96     1317900 :         SCVAL(buf,smb_wct,num_words);
      97     1317900 :         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
      98     1317900 :         smb_setlen(buf,(smb_size + num_words*2 + num_bytes - 4));
      99     1317900 :         return (smb_size + num_words*2 + num_bytes);
     100             : }
     101             : 
     102      684169 : NTSTATUS read_packet_remainder(int fd, char *buffer,
     103             :                                unsigned int timeout, ssize_t len)
     104             : {
     105        8560 :         NTSTATUS status;
     106             : 
     107      684169 :         if (len <= 0) {
     108           0 :                 return NT_STATUS_OK;
     109             :         }
     110             : 
     111      684169 :         status = read_fd_with_timeout(fd, buffer, len, len, timeout, NULL);
     112      684169 :         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      684169 :         return status;
     120             : }
     121             : 
     122             : #if !defined(WITH_SMB1SERVER)
     123           0 : 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           0 :         *p_unread = 0;
     134             : 
     135           0 :         status = read_smb_length_return_keepalive(sock, lenbuf, timeout,
     136             :                                                   &len);
     137           0 :         if (!NT_STATUS_IS_OK(status)) {
     138           0 :                 return status;
     139             :         }
     140             : 
     141             :         /*
     142             :          * The +4 here can't wrap, we've checked the length above already.
     143             :          */
     144             : 
     145           0 :         *buffer = talloc_array(mem_ctx, char, len+4);
     146             : 
     147           0 :         if (*buffer == NULL) {
     148           0 :                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
     149             :                           (int)len+4));
     150           0 :                 return NT_STATUS_NO_MEMORY;
     151             :         }
     152             : 
     153           0 :         memcpy(*buffer, lenbuf, sizeof(lenbuf));
     154             : 
     155           0 :         status = read_packet_remainder(sock, (*buffer)+4, timeout, len);
     156           0 :         if (!NT_STATUS_IS_OK(status)) {
     157           0 :                 return status;
     158             :         }
     159             : 
     160           0 :         *plen = len + 4;
     161           0 :         return NT_STATUS_OK;
     162             : }
     163             : 
     164           0 : 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           0 :         size_t len = 0;
     174             :         NTSTATUS status;
     175             : 
     176           0 :         *p_encrypted = false;
     177             : 
     178           0 :         status = smb2_receive_raw_talloc(mem_ctx, xconn, sock, buffer, timeout,
     179             :                                          p_unread, &len);
     180           0 :         if (!NT_STATUS_IS_OK(status)) {
     181           0 :                 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           0 :                 return status;
     187             :         }
     188             : 
     189           0 :         *p_len = len;
     190           0 :         return NT_STATUS_OK;
     191             : }
     192             : #endif
     193             : 
     194      659979 : 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      659979 :         return smb1_receive_talloc(mem_ctx, xconn, sock, buffer, timeout,
     205             :                                    p_unread, p_encrypted, p_len, seqnum,
     206             :                                    trusted_channel);
     207             : #else
     208           0 :         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        4384 : void remove_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     219             :                                       uint64_t mid)
     220             : {
     221        4384 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     222          17 :         struct pending_message_list *pml;
     223             : 
     224        4384 :         if (sconn->using_smb2) {
     225         328 :                 remove_deferred_open_message_smb2(xconn, mid);
     226         328 :                 return;
     227             :         }
     228             : 
     229        4056 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     230        4056 :                 if (mid == (uint64_t)SVAL(pml->buf.data,smb_mid)) {
     231        4056 :                         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        4056 :                         DLIST_REMOVE(sconn->deferred_open_queue, pml);
     236        4056 :                         TALLOC_FREE(pml);
     237        4056 :                         return;
     238             :                 }
     239             :         }
     240             : }
     241             : 
     242        4056 : 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        4056 :         struct pending_message_list *msg = talloc_get_type(private_data,
     248             :                                            struct pending_message_list);
     249        4056 :         struct smbd_server_connection *sconn = msg->sconn;
     250        4056 :         struct smbXsrv_connection *xconn = msg->xconn;
     251        4056 :         TALLOC_CTX *mem_ctx = talloc_tos();
     252        4056 :         uint64_t mid = (uint64_t)SVAL(msg->buf.data,smb_mid);
     253          17 :         uint8_t *inbuf;
     254             : 
     255        4056 :         inbuf = (uint8_t *)talloc_memdup(mem_ctx, msg->buf.data,
     256             :                                          msg->buf.length);
     257        4056 :         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        4056 :         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        4056 :         msg->processed = true;
     270             : 
     271        4056 :         process_smb(xconn,
     272             :                     inbuf,
     273             :                     msg->buf.length,
     274             :                     0,
     275             :                     msg->seqnum,
     276        4056 :                     msg->encrypted);
     277             : 
     278             :         /* If it's still there and was processed, remove it. */
     279        4073 :         msg = get_deferred_open_message_smb(sconn, mid);
     280        4056 :         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        4400 : bool schedule_deferred_open_message_smb(struct smbXsrv_connection *xconn,
     291             :                                         uint64_t mid)
     292             : {
     293        4400 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     294          17 :         struct pending_message_list *pml;
     295        4400 :         int i = 0;
     296             : 
     297        4400 :         if (sconn->using_smb2) {
     298         344 :                 return schedule_deferred_open_message_smb2(xconn, mid);
     299             :         }
     300             : 
     301        4056 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     302        4056 :                 uint64_t msg_mid = (uint64_t)SVAL(pml->buf.data,smb_mid);
     303             : 
     304        4056 :                 DEBUG(10,("schedule_deferred_open_message_smb: [%d] "
     305             :                         "msg_mid = %llu\n",
     306             :                         i++,
     307             :                         (unsigned long long)msg_mid ));
     308             : 
     309        4056 :                 if (mid == msg_mid) {
     310          17 :                         struct tevent_timer *te;
     311             : 
     312        4056 :                         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        4056 :                         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        4056 :                         te = tevent_add_timer(xconn->client->raw_ev_ctx,
     333             :                                               pml,
     334             :                                               timeval_zero(),
     335             :                                               smbd_deferred_open_timer,
     336             :                                               pml);
     337        4056 :                         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        4056 :                         TALLOC_FREE(pml->te);
     345        4056 :                         pml->te = te;
     346        4056 :                         DLIST_PROMOTE(sconn->deferred_open_queue, pml);
     347        4056 :                         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      145286 : bool open_was_deferred(struct smbXsrv_connection *xconn, uint64_t mid)
     363             : {
     364      145286 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     365        4932 :         struct pending_message_list *pml;
     366             : 
     367      145286 :         if (sconn->using_smb2) {
     368      108653 :                 return open_was_deferred_smb2(xconn, mid);
     369             :         }
     370             : 
     371       36709 :         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       31756 :         return False;
     377             : }
     378             : 
     379             : /****************************************************************************
     380             :  Return the message queued by this mid.
     381             : ****************************************************************************/
     382             : 
     383      161813 : 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      161893 :         for (pml = sconn->deferred_open_queue; pml; pml = pml->next) {
     389        8210 :                 if (((uint64_t)SVAL(pml->buf.data,smb_mid)) == mid) {
     390        8096 :                         return pml;
     391             :                 }
     392             :         }
     393      151700 :         return NULL;
     394             : }
     395             : 
     396             : /****************************************************************************
     397             :  Get the state data queued by this mid.
     398             : ****************************************************************************/
     399             : 
     400     1110113 : 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     1110113 :         if (smbreq->sconn->using_smb2) {
     407      952356 :                 return get_deferred_open_message_state_smb2(smbreq->smb2req,
     408             :                                         p_request_time,
     409             :                                         open_rec);
     410             :         }
     411             : 
     412      157757 :         pml = get_deferred_open_message_smb(smbreq->sconn, smbreq->mid);
     413      157757 :         if (!pml) {
     414      147719 :                 return false;
     415             :         }
     416        8072 :         if (p_request_time) {
     417        4052 :                 *p_request_time = pml->request_time;
     418             :         }
     419        8072 :         if (open_rec != NULL) {
     420        4020 :                 *open_rec = pml->open_rec;
     421             :         }
     422        8038 :         return true;
     423             : }
     424             : 
     425        4536 : 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        4536 :         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        4140 :                 return push_deferred_open_message_smb1(req, timeout,
     441             :                                                        id, open_rec);
     442             :         }
     443             : #endif
     444             : }
     445             : 
     446      654096 : static void construct_smb1_reply_common(uint8_t cmd, const uint8_t *inbuf,
     447             :                                    char *outbuf)
     448             : {
     449      654096 :         uint16_t in_flags2 = SVAL(inbuf,smb_flg2);
     450      654096 :         uint16_t out_flags2 = common_flags2;
     451             : 
     452      654096 :         out_flags2 |= in_flags2 & FLAGS2_UNICODE_STRINGS;
     453      654096 :         out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES;
     454      654096 :         out_flags2 |= in_flags2 & FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED;
     455             : 
     456      654096 :         srv_smb1_set_message(outbuf,0,0,false);
     457             : 
     458      654096 :         SCVAL(outbuf, smb_com, cmd);
     459      654096 :         SIVAL(outbuf,smb_rcls,0);
     460      654096 :         SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES));
     461      654096 :         SSVAL(outbuf,smb_flg2, out_flags2);
     462      654096 :         memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
     463      654096 :         memcpy(outbuf+smb_ss_field, inbuf+smb_ss_field, 8);
     464             : 
     465      654096 :         SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
     466      654096 :         SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
     467      654096 :         SSVAL(outbuf,smb_pidhigh,SVAL(inbuf,smb_pidhigh));
     468      654096 :         SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
     469      654096 :         SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
     470      654096 : }
     471             : 
     472      141930 : void construct_smb1_reply_common_req(struct smb_request *req, char *outbuf)
     473             : {
     474      141930 :         construct_smb1_reply_common(req->cmd, req->inbuf, outbuf);
     475      141930 : }
     476             : 
     477             : /*******************************************************************
     478             :  allocate and initialize a reply packet
     479             : ********************************************************************/
     480             : 
     481      512166 : 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      512166 :         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      512166 :         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      512166 :         *outbuf = talloc_array(mem_ctx, char,
     504             :                                NBT_HDR_SIZE + smb_len);
     505      512166 :         if (*outbuf == NULL) {
     506           0 :                 return false;
     507             :         }
     508             : 
     509      512166 :         construct_smb1_reply_common(req->cmd, inbuf, *outbuf);
     510      512166 :         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      512166 :         if (num_words != 0) {
     516      116424 :                 memset(*outbuf + (NBT_HDR_SIZE + HDR_VWV), 0, VWV(num_words));
     517             :         }
     518             : 
     519      504396 :         return true;
     520             : }
     521             : 
     522      512166 : void reply_smb1_outbuf(struct smb_request *req, uint8_t num_words, uint32_t num_bytes)
     523             : {
     524        7770 :         char *outbuf;
     525      512166 :         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      512166 :         req->outbuf = (uint8_t *)outbuf;
     530      512166 : }
     531             : 
     532      699027 : bool valid_smb1_header(const uint8_t *inbuf)
     533             : {
     534      699027 :         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      699027 :         return (IVAL(smb_base(inbuf), 0) == 0x424D53FF);
     542             : }
     543             : 
     544             : /****************************************************************************
     545             :  Process an smb from the client
     546             : ****************************************************************************/
     547             : 
     548          37 : 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          37 :         const uint8_t *inpdu = inbuf + NBT_HDR_SIZE;
     556          37 :         size_t pdulen = nread - NBT_HDR_SIZE;
     557          37 :         NTSTATUS status = smbd_smb2_process_negprot(xconn, 0, inpdu, pdulen);
     558          37 :         if (!NT_STATUS_IS_OK(status)) {
     559           0 :                 exit_server_cleanly("SMB2 negprot fail");
     560             :         }
     561          37 : }
     562             : 
     563      658299 : 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      658299 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     571      658299 :         int msg_type = CVAL(inbuf,0);
     572             : 
     573      658299 :         DO_PROFILE_INC(request);
     574             : 
     575      658299 :         DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
     576             :                     smb_len(inbuf) ) );
     577      658299 :         DEBUG(3, ("Transaction %d of length %d (%u toread)\n",
     578             :                   sconn->trans_num, (int)nread, (unsigned int)unread_bytes));
     579             : 
     580      658299 :         if (msg_type != NBSSmessage) {
     581             :                 /*
     582             :                  * NetBIOS session request, keepalive, etc.
     583             :                  */
     584         176 :                 reply_special(xconn, (char *)inbuf, nread);
     585         172 :                 goto done;
     586             :         }
     587             : 
     588             : #if defined(WITH_SMB1SERVER)
     589      658123 :         if (sconn->using_smb2) {
     590             :                 /* At this point we're not really using smb2,
     591             :                  * we make the decision here.. */
     592       11938 :                 if (smbd_is_smb2_header(inbuf, nread)) {
     593             : #endif
     594          37 :                         process_smb2(xconn,
     595             :                                      inbuf,
     596             :                                      nread,
     597             :                                      unread_bytes,
     598             :                                      seqnum,
     599             :                                      encrypted);
     600          37 :                         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      658086 :         process_smb1(xconn, inbuf, nread, unread_bytes, seqnum, encrypted);
     611             : #endif
     612             : 
     613      658161 : done:
     614      658161 :         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      669500 :         if ((sconn->num_requests % 50) == 0 &&
     624       11339 :             need_to_check_log_size()) {
     625          95 :                 change_to_root_user();
     626          95 :                 check_log_size();
     627             :         }
     628             : }
     629             : 
     630       35799 : NTSTATUS smbXsrv_connection_init_tables(struct smbXsrv_connection *conn,
     631             :                                         enum protocol_types protocol)
     632             : {
     633         886 :         NTSTATUS status;
     634             : 
     635       35799 :         conn->protocol = protocol;
     636             : 
     637       35799 :         if (conn->client->session_table != NULL) {
     638        1106 :                 return NT_STATUS_OK;
     639             :         }
     640             : 
     641       34693 :         if (protocol >= PROTOCOL_SMB2_02) {
     642       28913 :                 status = smb2srv_session_table_init(conn);
     643       28913 :                 if (!NT_STATUS_IS_OK(status)) {
     644           0 :                         conn->protocol = PROTOCOL_NONE;
     645           0 :                         return status;
     646             :                 }
     647             : 
     648       28913 :                 status = smb2srv_open_table_init(conn);
     649       28913 :                 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           0 :                 conn->protocol = PROTOCOL_NONE;
     674           0 :                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
     675             : #endif
     676             :         }
     677             : 
     678       34693 :         set_Protocol(protocol);
     679       34693 :         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          95 : const char *smbXsrv_connection_dbg(const struct smbXsrv_connection *xconn)
     690             : {
     691          95 :         const char *ret = NULL;
     692          95 :         char *raddr = NULL;
     693          95 :         char *laddr = NULL;
     694          95 :         struct GUID_txt_buf guid_buf = {};
     695             : 
     696             :         /*
     697             :          * TODO: this can be improved further later...
     698             :          */
     699             : 
     700          95 :         raddr = tsocket_address_string(xconn->remote_address, talloc_tos());
     701          95 :         if (raddr == NULL) {
     702           0 :                 return "<tsocket_address_string() failed>";
     703             :         }
     704          95 :         laddr = tsocket_address_string(xconn->local_address, talloc_tos());
     705          95 :         if (laddr == NULL) {
     706           0 :                 return "<tsocket_address_string() failed>";
     707             :         }
     708             : 
     709          95 :         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          95 :                         xconn->channel_id,
     714             :                         raddr,
     715             :                         laddr);
     716          95 :         TALLOC_FREE(raddr);
     717          95 :         TALLOC_FREE(laddr);
     718          95 :         if (ret == NULL) {
     719           0 :                 return "<talloc_asprintf() failed>";
     720             :         }
     721             : 
     722          95 :         return ret;
     723             : }
     724             : 
     725             : /*
     726             :  * Initialize a struct smb_request from an inbuf
     727             :  */
     728             : 
     729      678547 : 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      678547 :         size_t req_size = smb_len(inbuf) + 4;
     740             : 
     741             :         /* Ensure we have at least smb_size bytes. */
     742      678547 :         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      678547 :         *req = (struct smb_request) { .cmd = 0};
     749             : 
     750      678547 :         req->request_time = timeval_current();
     751      678547 :         now = timeval_to_nttime(&req->request_time);
     752             : 
     753      678547 :         req->cmd    = CVAL(inbuf, smb_com);
     754      678547 :         req->flags2 = SVAL(inbuf, smb_flg2);
     755      678547 :         req->smbpid = SVAL(inbuf, smb_pid);
     756      678547 :         req->mid    = (uint64_t)SVAL(inbuf, smb_mid);
     757      678547 :         req->seqnum = seqnum;
     758      678547 :         req->vuid   = SVAL(inbuf, smb_uid);
     759      678547 :         req->tid    = SVAL(inbuf, smb_tid);
     760      678547 :         req->wct    = CVAL(inbuf, smb_wct);
     761      678547 :         req->vwv    = (const uint16_t *)(inbuf+smb_vwv);
     762      678547 :         req->buflen = smb_buflen(inbuf);
     763      678547 :         req->buf    = (const uint8_t *)smb_buf_const(inbuf);
     764      678547 :         req->unread_bytes = unread_bytes;
     765      678547 :         req->encrypted = encrypted;
     766      678547 :         req->sconn = sconn;
     767      678547 :         req->xconn = xconn;
     768      678547 :         if (xconn != NULL) {
     769      678547 :                 status = smb1srv_tcon_lookup(xconn, req->tid, now, &tcon);
     770      678547 :                 if (NT_STATUS_IS_OK(status)) {
     771      627321 :                         req->conn = tcon->compat;
     772             :                 }
     773             :         }
     774      678547 :         req->posix_pathnames = lp_posix_pathnames();
     775             : 
     776             :         /* Ensure we have at least wct words and 2 bytes of bcc. */
     777      678547 :         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      678547 :         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      670278 :         return true;
     794             : }
     795             : 
     796             : /****************************************************************************
     797             :  Construct a reply to the incoming packet.
     798             : ****************************************************************************/
     799             : 
     800       20422 : static void construct_reply_smb1negprot(struct smbXsrv_connection *xconn,
     801             :                                         char *inbuf, int size,
     802             :                                         size_t unread_bytes)
     803             : {
     804       20422 :         struct smbd_server_connection *sconn = xconn->client->sconn;
     805         390 :         struct smb_request *req;
     806         390 :         NTSTATUS status;
     807             : 
     808       20422 :         if (!(req = talloc(talloc_tos(), struct smb_request))) {
     809           0 :                 smb_panic("could not allocate smb_request");
     810             :         }
     811             : 
     812       20422 :         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       20422 :         req->inbuf  = (uint8_t *)talloc_move(req, &inbuf);
     818             : 
     819       20422 :         status = smb2_multi_protocol_reply_negprot(req);
     820       19933 :         if (req->outbuf == NULL) {
     821             :                 /*
     822             :                 * req->outbuf == NULL means we bootstrapped into SMB2.
     823             :                 */
     824       19930 :                 return;
     825             :         }
     826           3 :         if (!NT_STATUS_IS_OK(status)) {
     827           3 :                 if (!smb1_srv_send(req->xconn,
     828           3 :                                    (char *)req->outbuf,
     829             :                                    true,
     830           3 :                                    req->seqnum + 1,
     831           6 :                                    IS_CONN_ENCRYPTED(req->conn) ||
     832           3 :                                            req->encrypted)) {
     833           0 :                         exit_server_cleanly("construct_reply_smb1negprot: "
     834             :                                             "smb1_srv_send failed.");
     835             :                 }
     836           3 :                 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       30050 : static void smbd_smb2_server_connection_read_handler(
     851             :                         struct smbXsrv_connection *xconn, int fd)
     852             : {
     853         701 :         char lenbuf[NBT_HDR_SIZE];
     854       30050 :         size_t len = 0;
     855       30050 :         uint8_t *buffer = NULL;
     856       30050 :         size_t bufferlen = 0;
     857         701 :         NTSTATUS status;
     858       30050 :         uint8_t msg_type = 0;
     859             : 
     860             :         /* Read the first 4 bytes - contains length of remainder. */
     861       30050 :         status = read_smb_length_return_keepalive(fd, lenbuf, 0, &len);
     862       30050 :         if (!NT_STATUS_IS_OK(status)) {
     863         124 :                 exit_server_cleanly("failed to receive request length");
     864             :                 return;
     865             :         }
     866             : 
     867             :         /* Integer wrap check. */
     868       29926 :         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       29926 :         bufferlen = len+NBT_HDR_SIZE;
     877             : 
     878       29926 :         buffer = talloc_array(talloc_tos(), uint8_t, bufferlen);
     879       29926 :         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       29926 :         memcpy(buffer, lenbuf, sizeof(lenbuf));
     888             : 
     889       29926 :         status = read_packet_remainder(fd, (char *)buffer+NBT_HDR_SIZE, 0, len);
     890       29926 :         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       29926 :         msg_type = PULL_LE_U8(buffer,0);
     897       29926 :         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         874 :                 reply_special(xconn, (char *)buffer, bufferlen);
     905         869 :                 xconn->client->sconn->num_requests++;
     906         869 :                 return;
     907             :         }
     908             : 
     909             :         /* Only a 'normal' message type allowed now. */
     910       29052 :         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       29052 :         if (bufferlen < smb_size) {
     918           0 :                 exit_server_cleanly("Invalid initial SMB1 or SMB2 packet");
     919             :                 return;
     920             :         }
     921       29052 :         if (valid_smb1_header(buffer)) {
     922             :                 /* Can *only* allow an SMB1 negprot here. */
     923       20447 :                 uint8_t cmd = PULL_LE_U8(buffer, smb_com);
     924       20447 :                 if (cmd != SMBnegprot) {
     925          25 :                         DBG_ERR("Incorrect SMB1 command 0x%hhx, "
     926             :                                 "should be SMBnegprot (0x72)\n",
     927             :                                 cmd);
     928          25 :                         exit_server_cleanly("Invalid initial SMB1 packet");
     929             :                 }
     930             :                 /* Minimal process_smb(). */
     931       20422 :                 show_msg((char *)buffer);
     932       20422 :                 construct_reply_smb1negprot(xconn, (char *)buffer,
     933             :                                             bufferlen, 0);
     934       19933 :                 xconn->client->sconn->trans_num++;
     935       19933 :                 xconn->client->sconn->num_requests++;
     936       19933 :                 return;
     937             : 
     938        8605 :         } 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        8605 :         status = smbd_smb2_process_negprot(xconn,
     951             :                                            0,
     952             :                                            (const uint8_t *)buffer+NBT_HDR_SIZE,
     953             :                                            len);
     954        8605 :         if (!NT_STATUS_IS_OK(status)) {
     955           0 :                 exit_server_cleanly("SMB2 negprot fail");
     956             :         }
     957        8294 :         return;
     958             : }
     959             : 
     960      690029 : 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      690029 :                 talloc_get_type_abort(private_data,
     967             :                 struct smbXsrv_connection);
     968             : 
     969      690029 :         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      690029 :         if (flags & TEVENT_FD_WRITE) {
     979           0 :                 smbd_server_connection_write_handler(xconn);
     980           0 :                 return;
     981             :         }
     982      690029 :         if (flags & TEVENT_FD_READ) {
     983             : #if defined(WITH_SMB1SERVER)
     984      686021 :                 if (lp_server_min_protocol() > PROTOCOL_NT1) {
     985             : #endif
     986       30050 :                         smbd_smb2_server_connection_read_handler(xconn,
     987             :                                                 xconn->transport.sock);
     988             : #if defined(WITH_SMB1SERVER)
     989             :                 } else {
     990      659979 :                         smbd_smb1_server_connection_read_handler(xconn,
     991             :                                                 xconn->transport.sock);
     992             :                 }
     993             : #endif
     994      683549 :                 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       36487 : static int smbXsrv_connection_destructor(struct smbXsrv_connection *xconn)
    1206             : {
    1207       36487 :         DBG_DEBUG("xconn[%s]\n", smbXsrv_connection_dbg(xconn));
    1208       36487 :         return 0;
    1209             : }
    1210             : 
    1211       36501 : NTSTATUS smbd_add_connection(struct smbXsrv_client *client, int sock_fd,
    1212             :                              NTTIME now, struct smbXsrv_connection **_xconn)
    1213             : {
    1214       36501 :         TALLOC_CTX *frame = talloc_stackframe();
    1215         894 :         struct smbXsrv_connection *xconn;
    1216         894 :         struct sockaddr_storage ss_srv;
    1217       36501 :         void *sp_srv = (void *)&ss_srv;
    1218       36501 :         struct sockaddr *sa_srv = (struct sockaddr *)sp_srv;
    1219         894 :         struct sockaddr_storage ss_clnt;
    1220       36501 :         void *sp_clnt = (void *)&ss_clnt;
    1221       36501 :         struct sockaddr *sa_clnt = (struct sockaddr *)sp_clnt;
    1222         894 :         socklen_t sa_socklen;
    1223       36501 :         struct tsocket_address *local_address = NULL;
    1224       36501 :         struct tsocket_address *remote_address = NULL;
    1225       36501 :         const char *remaddr = NULL;
    1226         894 :         char *p;
    1227       36501 :         const char *rhost = NULL;
    1228         894 :         int ret;
    1229         894 :         int tmp;
    1230             : 
    1231       36501 :         *_xconn = NULL;
    1232             : 
    1233       36501 :         DO_PROFILE_INC(connect);
    1234             : 
    1235       36501 :         xconn = talloc_zero(client, struct smbXsrv_connection);
    1236       36501 :         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       36501 :         talloc_set_destructor(xconn, smbXsrv_connection_destructor);
    1242       36501 :         talloc_steal(frame, xconn);
    1243       36501 :         xconn->client = client;
    1244       36501 :         xconn->connect_time = now;
    1245       36501 :         if (client->next_channel_id != 0) {
    1246       36501 :                 xconn->channel_id = client->next_channel_id++;
    1247             :         }
    1248             : 
    1249       36501 :         xconn->transport.sock = sock_fd;
    1250             : #if defined(WITH_SMB1SERVER)
    1251       32499 :         smbd_echo_init(xconn);
    1252             : #endif
    1253       36501 :         xconn->protocol = PROTOCOL_NONE;
    1254             : 
    1255             :         /* Ensure child is set to blocking mode */
    1256       36501 :         set_blocking(sock_fd,True);
    1257             : 
    1258       36501 :         set_socket_options(sock_fd, "SO_KEEPALIVE");
    1259       36501 :         set_socket_options(sock_fd, lp_socket_options());
    1260             : 
    1261       36501 :         sa_socklen = sizeof(ss_clnt);
    1262       36501 :         ret = getpeername(sock_fd, sa_clnt, &sa_socklen);
    1263       36501 :         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       36501 :         ret = tsocket_address_bsd_from_sockaddr(xconn,
    1272             :                                                 sa_clnt, sa_socklen,
    1273             :                                                 &remote_address);
    1274       36501 :         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       36501 :         sa_socklen = sizeof(ss_srv);
    1283       36501 :         ret = getsockname(sock_fd, sa_srv, &sa_socklen);
    1284       36501 :         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       36501 :         ret = tsocket_address_bsd_from_sockaddr(xconn,
    1293             :                                                 sa_srv, sa_socklen,
    1294             :                                                 &local_address);
    1295       36501 :         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       36501 :         if (tsocket_address_is_inet(remote_address, "ip")) {
    1304       36501 :                 remaddr = tsocket_address_inet_addr_string(remote_address,
    1305             :                                                            talloc_tos());
    1306       36501 :                 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       36501 :         ret = get_remote_hostname(remote_address,
    1324             :                                   &p, talloc_tos());
    1325       36501 :         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       36501 :         rhost = p;
    1333       36501 :         if (strequal(rhost, "UNKNOWN")) {
    1334           0 :                 rhost = remaddr;
    1335             :         }
    1336             : 
    1337       36501 :         xconn->local_address = local_address;
    1338       36501 :         xconn->remote_address = remote_address;
    1339       36501 :         xconn->remote_hostname = talloc_strdup(xconn, rhost);
    1340       36501 :         if (xconn->remote_hostname == NULL) {
    1341           0 :                 return NT_STATUS_NO_MEMORY;
    1342             :         }
    1343             : 
    1344       36501 :         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       36501 :         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       36501 :         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       36501 :         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       36501 :         tmp = lp_max_xmit();
    1391       36501 :         tmp = MAX(tmp, SMB_BUFFER_SIZE_MIN);
    1392       36501 :         tmp = MIN(tmp, SMB_BUFFER_SIZE_MAX);
    1393             : 
    1394             : #if defined(WITH_SMB1SERVER)
    1395       32499 :         xconn->smb1.negprot.max_recv = tmp;
    1396             : 
    1397       32499 :         xconn->smb1.sessions.done_sesssetup = false;
    1398       32499 :         xconn->smb1.sessions.max_send = SMB_BUFFER_SIZE_MAX;
    1399             : #endif
    1400             : 
    1401       36501 :         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       36501 :         if (!xconn->transport.fde) {
    1408           0 :                 TALLOC_FREE(frame);
    1409           0 :                 return NT_STATUS_NO_MEMORY;
    1410             :         }
    1411       36501 :         tevent_fd_set_auto_close(xconn->transport.fde);
    1412             : 
    1413             :         /* for now we only have one connection */
    1414       36501 :         DLIST_ADD_END(client->connections, xconn);
    1415       36501 :         talloc_steal(client, xconn);
    1416             : 
    1417       36501 :         *_xconn = xconn;
    1418       36501 :         TALLOC_FREE(frame);
    1419       36501 :         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         557 : static void check_reload(struct smbd_server_connection *sconn, time_t t)
    1529             : {
    1530             : 
    1531         557 :         if (last_smb_conf_reload_time == 0) {
    1532         107 :                 last_smb_conf_reload_time = t;
    1533             :         }
    1534             : 
    1535         557 :         if (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK) {
    1536         120 :                 reload_services(sconn, conn_snum_used, true);
    1537         120 :                 last_smb_conf_reload_time = t;
    1538             :         }
    1539         557 : }
    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         561 : static bool deadtime_fn(const struct timeval *now, void *private_data)
    1571             : {
    1572         561 :         struct smbd_server_connection *sconn =
    1573             :                 (struct smbd_server_connection *)private_data;
    1574             : 
    1575         561 :         if ((conn_num_open(sconn) == 0)
    1576         559 :             || (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         557 :         return True;
    1585             : }
    1586             : 
    1587             : /*
    1588             :  * Do the recurring log file and smb.conf reload checks.
    1589             :  */
    1590             : 
    1591         557 : static bool housekeeping_fn(const struct timeval *now, void *private_data)
    1592             : {
    1593         557 :         struct smbd_server_connection *sconn = talloc_get_type_abort(
    1594             :                 private_data, struct smbd_server_connection);
    1595             : 
    1596         557 :         DEBUG(5, ("housekeeping\n"));
    1597             : 
    1598         557 :         change_to_root_user();
    1599             : 
    1600             :         /* check if we need to reload services */
    1601         557 :         check_reload(sconn, time_mono(NULL));
    1602             : 
    1603             :         /*
    1604             :          * Force a log file check.
    1605             :          */
    1606         557 :         force_check_log_size();
    1607         557 :         check_log_size();
    1608         557 :         return true;
    1609             : }
    1610             : 
    1611          16 : 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          16 :         exit_server_cleanly("termination signal");
    1619             : }
    1620             : 
    1621       35395 : static void smbd_setup_sig_term_handler(struct smbd_server_connection *sconn)
    1622             : {
    1623         842 :         struct tevent_signal *se;
    1624             : 
    1625       35395 :         se = tevent_add_signal(sconn->ev_ctx,
    1626             :                                sconn,
    1627             :                                SIGTERM, 0,
    1628             :                                smbd_sig_term_handler,
    1629             :                                sconn);
    1630       35395 :         if (!se) {
    1631           0 :                 exit_server("failed to setup SIGTERM handler");
    1632             :         }
    1633       35395 : }
    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       35395 : static void smbd_setup_sig_hup_handler(struct smbd_server_connection *sconn)
    1652             : {
    1653         842 :         struct tevent_signal *se;
    1654             : 
    1655       35395 :         se = tevent_add_signal(sconn->ev_ctx,
    1656             :                                sconn,
    1657             :                                SIGHUP, 0,
    1658             :                                smbd_sig_hup_handler,
    1659             :                                sconn);
    1660       35395 :         if (!se) {
    1661           0 :                 exit_server("failed to setup SIGHUP handler");
    1662             :         }
    1663       35395 : }
    1664             : 
    1665         684 : 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         684 :                 talloc_get_type_abort(private_data,
    1673             :                 struct smbd_server_connection);
    1674             : 
    1675         684 :         DEBUG(10,("smbd_conf_updated: Got message saying smb.conf was "
    1676             :                   "updated. Reloading.\n"));
    1677         684 :         change_to_root_user();
    1678         684 :         reload_services(sconn, conn_snum_used, false);
    1679         684 : }
    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     5122966 : static inline void smbd_tevent_trace_callback_before_loop_once(
    1712             :         struct smbd_tevent_trace_state *state)
    1713             : {
    1714     5122966 :         talloc_free(state->frame);
    1715     5122966 :         state->frame = talloc_stackframe_pool(8192);
    1716     5122966 : }
    1717             : 
    1718     5087571 : static inline void smbd_tevent_trace_callback_after_loop_once(
    1719             :         struct smbd_tevent_trace_state *state)
    1720             : {
    1721     5087571 :         TALLOC_FREE(state->frame);
    1722     5030989 : }
    1723             : 
    1724    17270243 : static void smbd_tevent_trace_callback(enum tevent_trace_point point,
    1725             :                                        void *private_data)
    1726             : {
    1727    17270243 :         struct smbd_tevent_trace_state *state =
    1728             :                 (struct smbd_tevent_trace_state *)private_data;
    1729             : 
    1730    17270243 :         switch (point) {
    1731     3496984 :         case TEVENT_TRACE_BEFORE_WAIT:
    1732     3496984 :                 break;
    1733     3496984 :         case TEVENT_TRACE_AFTER_WAIT:
    1734     3496984 :                 break;
    1735     5122966 :         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
    1736     5122966 :                 smbd_tevent_trace_callback_before_loop_once(state);
    1737     5122966 :                 break;
    1738     5030989 :         case TEVENT_TRACE_AFTER_LOOP_ONCE:
    1739     5087571 :                 smbd_tevent_trace_callback_after_loop_once(state);
    1740     5030989 :                 break;
    1741             :         }
    1742             : 
    1743    17270243 :         errno = 0;
    1744    17270243 : }
    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       35395 : void smbd_process(struct tevent_context *ev_ctx,
    1796             :                   struct messaging_context *msg_ctx,
    1797             :                   int sock_fd,
    1798             :                   bool interactive)
    1799             : {
    1800       70790 :         struct smbd_tevent_trace_state trace_state = {
    1801             :                 .ev = ev_ctx,
    1802       35395 :                 .frame = talloc_stackframe(),
    1803             :         };
    1804         842 :         const struct loadparm_substitution *lp_sub =
    1805       35395 :                 loadparm_s3_global_substitution();
    1806       35395 :         struct smbXsrv_client *client = NULL;
    1807       35395 :         struct smbd_server_connection *sconn = NULL;
    1808       35395 :         struct smbXsrv_connection *xconn = NULL;
    1809       35395 :         const char *locaddr = NULL;
    1810       35395 :         const char *remaddr = NULL;
    1811         842 :         int ret;
    1812         842 :         NTSTATUS status;
    1813       35395 :         struct timeval tv = timeval_current();
    1814       35395 :         NTTIME now = timeval_to_nttime(&tv);
    1815       35395 :         char *chroot_dir = NULL;
    1816         842 :         int rc;
    1817             : 
    1818       35395 :         status = smbXsrv_client_create(ev_ctx, ev_ctx, msg_ctx, now, &client);
    1819       35395 :         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       35395 :         global_smbXsrv_client = client;
    1828             : 
    1829       35395 :         sconn = talloc_zero(client, struct smbd_server_connection);
    1830       35395 :         if (sconn == NULL) {
    1831           0 :                 exit_server("failed to create smbd_server_connection");
    1832             :         }
    1833             : 
    1834       35395 :         client->sconn = sconn;
    1835       35395 :         sconn->client = client;
    1836             : 
    1837       35395 :         sconn->ev_ctx = ev_ctx;
    1838       35395 :         sconn->msg_ctx = msg_ctx;
    1839             : 
    1840       35395 :         ret = pthreadpool_tevent_init(sconn, lp_aio_max_threads(),
    1841             :                                       &sconn->pool);
    1842       35395 :         if (ret != 0) {
    1843           0 :                 exit_server("pthreadpool_tevent_init() failed.");
    1844             :         }
    1845             : 
    1846             : #if defined(WITH_SMB1SERVER)
    1847       31393 :         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       35395 :                 sconn->using_smb2 = true;
    1857             : #if defined(WITH_SMB1SERVER)
    1858             :         }
    1859             : #endif
    1860             : 
    1861       35395 :         if (!interactive) {
    1862       35395 :                 smbd_setup_sig_term_handler(sconn);
    1863       35395 :                 smbd_setup_sig_hup_handler(sconn);
    1864             :         }
    1865             : 
    1866       35395 :         status = smbd_add_connection(client, sock_fd, now, &xconn);
    1867       35395 :         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       35395 :         } else if (!NT_STATUS_IS_OK(status)) {
    1876           0 :                 exit_server_cleanly(nt_errstr(status));
    1877             :         }
    1878             : 
    1879       36237 :         sconn->local_address =
    1880       35395 :                 tsocket_address_copy(xconn->local_address, sconn);
    1881       35395 :         if (sconn->local_address == NULL) {
    1882           0 :                 exit_server_cleanly("tsocket_address_copy() failed");
    1883             :         }
    1884       36237 :         sconn->remote_address =
    1885       35395 :                 tsocket_address_copy(xconn->remote_address, sconn);
    1886       35395 :         if (sconn->remote_address == NULL) {
    1887           0 :                 exit_server_cleanly("tsocket_address_copy() failed");
    1888             :         }
    1889       36237 :         sconn->remote_hostname =
    1890       35395 :                 talloc_strdup(sconn, xconn->remote_hostname);
    1891       35395 :         if (sconn->remote_hostname == NULL) {
    1892           0 :                 exit_server_cleanly("tsocket_strdup() failed");
    1893             :         }
    1894             : 
    1895       70790 :         client->global->local_address =
    1896       35395 :                 tsocket_address_string(sconn->local_address,
    1897       35395 :                                        client->global);
    1898       35395 :         if (client->global->local_address == NULL) {
    1899           0 :                 exit_server_cleanly("tsocket_address_string() failed");
    1900             :         }
    1901       70790 :         client->global->remote_address =
    1902       35395 :                 tsocket_address_string(sconn->remote_address,
    1903       34553 :                                        client->global);
    1904       35395 :         if (client->global->remote_address == NULL) {
    1905           0 :                 exit_server_cleanly("tsocket_address_string() failed");
    1906             :         }
    1907       70790 :         client->global->remote_name =
    1908       35395 :                 talloc_strdup(client->global, sconn->remote_hostname);
    1909       35395 :         if (client->global->remote_name == NULL) {
    1910           0 :                 exit_server_cleanly("tsocket_strdup() failed");
    1911             :         }
    1912             : 
    1913       35395 :         if (tsocket_address_is_inet(sconn->local_address, "ip")) {
    1914       35395 :                 locaddr = tsocket_address_inet_addr_string(
    1915             :                                 sconn->local_address,
    1916             :                                 talloc_tos());
    1917       35395 :                 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       35395 :         if (tsocket_address_is_inet(sconn->remote_address, "ip")) {
    1927       35395 :                 remaddr = tsocket_address_inet_addr_string(
    1928             :                                 sconn->remote_address,
    1929             :                                 talloc_tos());
    1930       35395 :                 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       35395 :         set_remote_machine_name(remaddr, false);
    1942       35395 :         reload_services(sconn, conn_snum_used, true);
    1943       35395 :         sub_set_socket_ids(remaddr,
    1944             :                            sconn->remote_hostname,
    1945             :                            locaddr);
    1946             : 
    1947       35395 :         if (lp_preload_modules()) {
    1948           0 :                 smb_load_all_modules_absoute_path(lp_preload_modules());
    1949             :         }
    1950             : 
    1951       35395 :         if (!init_account_policy()) {
    1952           0 :                 exit_server("Could not open account policy tdb.\n");
    1953             :         }
    1954             : 
    1955       35395 :         chroot_dir = lp_root_directory(talloc_tos(), lp_sub);
    1956       35395 :         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       35395 :         if (!file_init(sconn)) {
    1974           0 :                 exit_server("file_init() failed");
    1975             :         }
    1976             : 
    1977             :         /* Setup oplocks */
    1978       35395 :         if (!init_oplocks(sconn))
    1979           0 :                 exit_server("Failed to init oplocks");
    1980             : 
    1981             :         /* register our message handlers */
    1982       35395 :         messaging_register(sconn->msg_ctx, sconn,
    1983             :                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
    1984       35395 :         messaging_register(
    1985             :                 sconn->msg_ctx,
    1986             :                 sconn,
    1987             :                 MSG_SMB_FORCE_TDIS_DENIED,
    1988             :                 msg_force_tdis_denied);
    1989       35395 :         messaging_register(sconn->msg_ctx, sconn,
    1990             :                            MSG_SMB_CLOSE_FILE, msg_close_file);
    1991       35395 :         messaging_register(sconn->msg_ctx, sconn,
    1992             :                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
    1993             : 
    1994       35395 :         id_cache_register_msgs(sconn->msg_ctx);
    1995       35395 :         messaging_deregister(sconn->msg_ctx, ID_CACHE_KILL, NULL);
    1996       35395 :         messaging_register(sconn->msg_ctx, sconn,
    1997             :                            ID_CACHE_KILL, smbd_id_cache_kill);
    1998             : 
    1999       35395 :         messaging_deregister(sconn->msg_ctx,
    2000       35395 :                              MSG_SMB_CONF_UPDATED, sconn->ev_ctx);
    2001       35395 :         messaging_register(sconn->msg_ctx, sconn,
    2002             :                            MSG_SMB_CONF_UPDATED, smbd_conf_updated);
    2003             : 
    2004       35395 :         messaging_deregister(sconn->msg_ctx, MSG_SMB_KILL_CLIENT_IP,
    2005             :                              NULL);
    2006       35395 :         messaging_register(sconn->msg_ctx, sconn,
    2007             :                            MSG_SMB_KILL_CLIENT_IP,
    2008             :                            msg_kill_client_ip);
    2009             : 
    2010       35395 :         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       35395 :         messaging_deregister(sconn->msg_ctx,
    2017             :                              MSG_DEBUG, NULL);
    2018       35395 :         messaging_register(sconn->msg_ctx, NULL,
    2019             :                            MSG_DEBUG, debug_message);
    2020             : 
    2021             : #if defined(WITH_SMB1SERVER)
    2022       31393 :         if ((lp_keepalive() != 0)
    2023       31393 :             && !(event_add_idle(ev_ctx, NULL,
    2024       31393 :                                 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       35395 :         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       35395 :         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       35395 :         smbprofile_dump_setup(ev_ctx);
    2047             : 
    2048       35395 :         if (!init_dptrs(sconn)) {
    2049           0 :                 exit_server("init_dptrs() failed");
    2050             :         }
    2051             : 
    2052       35395 :         TALLOC_FREE(trace_state.frame);
    2053             : 
    2054       35395 :         if (smbprofile_active()) {
    2055           0 :                 tevent_set_trace_callback(ev_ctx,
    2056             :                                           smbd_tevent_trace_callback_profile,
    2057             :                                           &trace_state);
    2058             :         } else {
    2059       35395 :                 tevent_set_trace_callback(ev_ctx,
    2060             :                                           smbd_tevent_trace_callback,
    2061             :                                           &trace_state);
    2062             :         }
    2063             : 
    2064       35395 :         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