LCOV - code coverage report
Current view: top level - src/util - sock.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 39.9 % 168 67
Test Date: 2026-10-23 05:39:29 Functions: 28.0 % 25 7
Branches: 32.0 % 178 57

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2020-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <util/sock.h>
       6                 :             : 
       7                 :             : #include <compat/compat.h>
       8                 :             : #include <span.h>
       9                 :             : #include <tinyformat.h>
      10                 :             : #include <util/check.h>
      11                 :             : #include <util/log.h>
      12                 :             : #include <util/syserror.h>
      13                 :             : #include <util/threadinterrupt.h>
      14                 :             : #include <util/time.h>
      15                 :             : 
      16                 :             : #include <algorithm>
      17                 :             : #include <compare>
      18                 :             : #include <exception>
      19                 :             : #include <memory>
      20                 :             : #include <stdexcept>
      21                 :             : #include <string>
      22                 :             : #include <utility>
      23                 :             : #include <vector>
      24                 :             : 
      25                 :             : #ifdef USE_POLL
      26                 :             : #include <poll.h>
      27                 :             : #endif
      28                 :             : 
      29                 :      162260 : Sock::Sock(SOCKET s) : m_socket(s) {}
      30                 :             : 
      31                 :           0 : Sock::Sock(Sock&& other)
      32                 :             : {
      33                 :           0 :     m_socket = other.m_socket;
      34                 :           0 :     other.m_socket = INVALID_SOCKET;
      35                 :           0 : }
      36                 :             : 
      37                 :      162260 : Sock::~Sock() { Close(); }
      38                 :             : 
      39                 :           0 : Sock& Sock::operator=(Sock&& other)
      40                 :             : {
      41                 :           0 :     Close();
      42                 :           0 :     m_socket = other.m_socket;
      43                 :           0 :     other.m_socket = INVALID_SOCKET;
      44                 :           0 :     return *this;
      45                 :             : }
      46                 :             : 
      47                 :           0 : ssize_t Sock::Send(const void* data, size_t len, int flags) const
      48                 :             : {
      49                 :           0 :     return send(m_socket, static_cast<const char*>(data), len, flags);
      50                 :             : }
      51                 :             : 
      52                 :           0 : ssize_t Sock::Recv(void* buf, size_t len, int flags) const
      53                 :             : {
      54         [ #  # ]:           0 :     return recv(m_socket, static_cast<char*>(buf), len, flags);
      55                 :             : }
      56                 :             : 
      57                 :           0 : int Sock::Connect(const sockaddr* addr, socklen_t addr_len) const
      58                 :             : {
      59                 :           0 :     return connect(m_socket, addr, addr_len);
      60                 :             : }
      61                 :             : 
      62                 :           0 : int Sock::Bind(const sockaddr* addr, socklen_t addr_len) const
      63                 :             : {
      64                 :           0 :     return bind(m_socket, addr, addr_len);
      65                 :             : }
      66                 :             : 
      67                 :           0 : int Sock::Listen(int backlog) const
      68                 :             : {
      69                 :           0 :     return listen(m_socket, backlog);
      70                 :             : }
      71                 :             : 
      72                 :           0 : std::unique_ptr<Sock> Sock::Accept(sockaddr* addr, socklen_t* addr_len) const
      73                 :             : {
      74                 :             : #ifdef WIN32
      75                 :             :     static constexpr auto accept_error = INVALID_SOCKET;
      76                 :             : #else
      77                 :           0 :     static constexpr auto accept_error = SOCKET_ERROR;
      78                 :             : #endif
      79                 :             : 
      80                 :           0 :     std::unique_ptr<Sock> sock;
      81                 :             : 
      82         [ #  # ]:           0 :     const auto socket = accept(m_socket, addr, addr_len);
      83         [ #  # ]:           0 :     if (socket != accept_error) {
      84                 :           0 :         try {
      85         [ #  # ]:           0 :             sock = std::make_unique<Sock>(socket);
      86         [ -  - ]:           0 :         } catch (const std::exception&) {
      87                 :             : #ifdef WIN32
      88                 :             :             closesocket(socket);
      89                 :             : #else
      90         [ -  - ]:           0 :             close(socket);
      91                 :             : #endif
      92                 :           0 :         }
      93                 :             :     }
      94                 :             : 
      95                 :           0 :     return sock;
      96                 :           0 : }
      97                 :             : 
      98                 :           0 : int Sock::GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const
      99                 :             : {
     100                 :           0 :     return getsockopt(m_socket, level, opt_name, static_cast<char*>(opt_val), opt_len);
     101                 :             : }
     102                 :             : 
     103                 :           0 : int Sock::SetSockOpt(int level, int opt_name, const void* opt_val, socklen_t opt_len) const
     104                 :             : {
     105                 :           0 :     return setsockopt(m_socket, level, opt_name, static_cast<const char*>(opt_val), opt_len);
     106                 :             : }
     107                 :             : 
     108                 :           0 : int Sock::GetSockName(sockaddr* name, socklen_t* name_len) const
     109                 :             : {
     110                 :           0 :     return getsockname(m_socket, name, name_len);
     111                 :             : }
     112                 :             : 
     113                 :           0 : bool Sock::SetNonBlocking() const
     114                 :             : {
     115                 :             : #ifdef WIN32
     116                 :             :     u_long on{1};
     117                 :             :     if (ioctlsocket(m_socket, FIONBIO, &on) == SOCKET_ERROR) {
     118                 :             :         return false;
     119                 :             :     }
     120                 :             : #else
     121                 :           0 :     const int flags{fcntl(m_socket, F_GETFL, 0)};
     122         [ #  # ]:           0 :     if (flags == SOCKET_ERROR) {
     123                 :             :         return false;
     124                 :             :     }
     125         [ #  # ]:           0 :     if (fcntl(m_socket, F_SETFL, flags | O_NONBLOCK) == SOCKET_ERROR) {
     126                 :           0 :         return false;
     127                 :             :     }
     128                 :             : #endif
     129                 :             :     return true;
     130                 :             : }
     131                 :             : 
     132                 :           0 : bool Sock::IsSelectable() const
     133                 :             : {
     134                 :             : #if defined(USE_POLL) || defined(WIN32)
     135                 :           0 :     return true;
     136                 :             : #else
     137                 :             :     return m_socket < FD_SETSIZE;
     138                 :             : #endif
     139                 :             : }
     140                 :             : 
     141                 :           0 : bool Sock::Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred) const
     142                 :             : {
     143                 :             :     // We need a `shared_ptr` holding `this` for `WaitMany()`, but don't want
     144                 :             :     // `this` to be destroyed when the `shared_ptr` goes out of scope at the
     145                 :             :     // end of this function.
     146                 :             :     // Create it with an aliasing shared_ptr that points to `this` without
     147                 :             :     // owning it.
     148         [ #  # ]:           0 :     std::shared_ptr<const Sock> shared{std::shared_ptr<const Sock>{}, this};
     149                 :             : 
     150   [ #  #  #  #  :           0 :     EventsPerSock events_per_sock{std::make_pair(shared, Events{requested})};
          #  #  #  #  #  
                      # ]
     151                 :             : 
     152   [ #  #  #  # ]:           0 :     if (!WaitMany(timeout, events_per_sock)) {
     153                 :             :         return false;
     154                 :             :     }
     155                 :             : 
     156         [ #  # ]:           0 :     if (occurred != nullptr) {
     157                 :           0 :         *occurred = events_per_sock.begin()->second.occurred;
     158                 :             :     }
     159                 :             : 
     160                 :             :     return true;
     161         [ #  # ]:           0 : }
     162                 :             : 
     163                 :           0 : bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const
     164                 :             : {
     165                 :           0 :     timeout = std::min<std::chrono::milliseconds>(timeout, MAX_WAIT_TIMEOUT);
     166                 :             : 
     167                 :             : #ifdef USE_POLL
     168                 :           0 :     std::vector<pollfd> pfds;
     169   [ #  #  #  # ]:           0 :     for (const auto& [sock, events] : events_per_sock) {
     170         [ #  # ]:           0 :         pfds.emplace_back();
     171                 :           0 :         auto& pfd = pfds.back();
     172         [ #  # ]:           0 :         pfd.fd = sock->m_socket;
     173         [ #  # ]:           0 :         if (events.requested & RecvEvent) {
     174                 :           0 :             pfd.events |= POLLIN;
     175                 :             :         }
     176         [ #  # ]:           0 :         if (events.requested & SendEvent) {
     177                 :           0 :             pfd.events |= POLLOUT;
     178                 :             :         }
     179                 :             :     }
     180                 :             : 
     181   [ #  #  #  #  :           0 :     if (poll(pfds.data(), pfds.size(), count_milliseconds(timeout)) == SOCKET_ERROR) {
                   #  # ]
     182                 :             :         return false;
     183                 :             :     }
     184                 :             : 
     185   [ #  #  #  # ]:           0 :     assert(pfds.size() == events_per_sock.size());
     186                 :           0 :     size_t i{0};
     187   [ #  #  #  # ]:           0 :     for (auto& [sock, events] : events_per_sock) {
     188         [ #  # ]:           0 :         assert(sock->m_socket == static_cast<SOCKET>(pfds[i].fd));
     189                 :           0 :         events.occurred = 0;
     190         [ #  # ]:           0 :         if (pfds[i].revents & POLLIN) {
     191                 :           0 :             events.occurred |= RecvEvent;
     192                 :             :         }
     193         [ #  # ]:           0 :         if (pfds[i].revents & POLLOUT) {
     194                 :           0 :             events.occurred |= SendEvent;
     195                 :             :         }
     196         [ #  # ]:           0 :         if (pfds[i].revents & (POLLERR | POLLHUP)) {
     197                 :           0 :             events.occurred |= ErrorEvent;
     198                 :             :         }
     199                 :           0 :         ++i;
     200                 :             :     }
     201                 :             : 
     202                 :             :     return true;
     203                 :             : #else
     204                 :             :     fd_set recv;
     205                 :             :     fd_set send;
     206                 :             :     fd_set err;
     207                 :             :     FD_ZERO(&recv);
     208                 :             :     FD_ZERO(&send);
     209                 :             :     FD_ZERO(&err);
     210                 :             :     SOCKET socket_max{0};
     211                 :             : 
     212                 :             :     for (const auto& [sock, events] : events_per_sock) {
     213                 :             :         if (!sock->IsSelectable()) {
     214                 :             :             return false;
     215                 :             :         }
     216                 :             :         const auto& s = sock->m_socket;
     217                 :             :         if (events.requested & RecvEvent) {
     218                 :             :             FD_SET(s, &recv);
     219                 :             :         }
     220                 :             :         if (events.requested & SendEvent) {
     221                 :             :             FD_SET(s, &send);
     222                 :             :         }
     223                 :             :         FD_SET(s, &err);
     224                 :             :         socket_max = std::max(socket_max, s);
     225                 :             :     }
     226                 :             : 
     227                 :             :     timeval tv = MillisToTimeval(timeout);
     228                 :             : 
     229                 :             :     if (select(socket_max + 1, &recv, &send, &err, &tv) == SOCKET_ERROR) {
     230                 :             :         return false;
     231                 :             :     }
     232                 :             : 
     233                 :             :     for (auto& [sock, events] : events_per_sock) {
     234                 :             :         const auto& s = sock->m_socket;
     235                 :             :         events.occurred = 0;
     236                 :             :         if (FD_ISSET(s, &recv)) {
     237                 :             :             events.occurred |= RecvEvent;
     238                 :             :         }
     239                 :             :         if (FD_ISSET(s, &send)) {
     240                 :             :             events.occurred |= SendEvent;
     241                 :             :         }
     242                 :             :         if (FD_ISSET(s, &err)) {
     243                 :             :             events.occurred |= ErrorEvent;
     244                 :             :         }
     245                 :             :     }
     246                 :             : 
     247                 :             :     return true;
     248                 :             : #endif /* USE_POLL */
     249                 :           0 : }
     250                 :             : 
     251                 :        3369 : void Sock::SendComplete(std::span<const unsigned char> data,
     252                 :             :                         std::chrono::milliseconds timeout,
     253                 :             :                         CThreadInterrupt& interrupt) const
     254                 :             : {
     255                 :        3369 :     const auto deadline = GetTime<std::chrono::milliseconds>() + timeout;
     256                 :        3369 :     size_t sent{0};
     257                 :             : 
     258                 :       20719 :     for (;;) {
     259                 :       12044 :         const ssize_t ret{Send(data.data() + sent, data.size() - sent, MSG_NOSIGNAL)};
     260                 :             : 
     261         [ +  + ]:       12044 :         if (ret > 0) {
     262                 :        6145 :             sent += static_cast<size_t>(ret);
     263         [ +  + ]:        6145 :             if (sent == data.size()) {
     264                 :             :                 break;
     265                 :             :             }
     266                 :             :         } else {
     267                 :        5899 :             const int err{WSAGetLastError()};
     268         [ +  + ]:        5899 :             if (IOErrorIsPermanent(err)) {
     269   [ +  -  +  -  :        1656 :                 throw std::runtime_error(strprintf("send(): %s", NetworkErrorString(err)));
                   +  - ]
     270                 :             :             }
     271                 :             :         }
     272                 :             : 
     273                 :        8900 :         const auto now = GetTime<std::chrono::milliseconds>();
     274                 :             : 
     275         [ -  + ]:        8900 :         if (now >= deadline) {
     276         [ #  # ]:           0 :             throw std::runtime_error(strprintf(
     277   [ #  #  #  # ]:           0 :                 "Send timeout (sent only %u of %u bytes before that)", sent, data.size()));
     278                 :             :         }
     279                 :             : 
     280         [ +  + ]:        8900 :         if (interrupt) {
     281         [ +  - ]:         225 :             throw std::runtime_error(strprintf(
     282   [ +  -  +  - ]:         450 :                 "Send interrupted (sent only %u of %u bytes before that)", sent, data.size()));
     283                 :             :         }
     284                 :             : 
     285                 :             :         // Wait for a short while (or the socket to become ready for sending) before retrying
     286                 :             :         // if nothing was sent.
     287                 :        8675 :         const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
     288                 :        8675 :         (void)Wait(wait_time, SendEvent);
     289                 :        8675 :     }
     290                 :        2316 : }
     291                 :             : 
     292                 :        1979 : void Sock::SendComplete(std::span<const char> data,
     293                 :             :                         std::chrono::milliseconds timeout,
     294                 :             :                         CThreadInterrupt& interrupt) const
     295                 :             : {
     296                 :        1979 :     SendComplete(MakeUCharSpan(data), timeout, interrupt);
     297                 :        1737 : }
     298                 :             : 
     299                 :        1813 : std::string Sock::RecvUntilTerminator(uint8_t terminator,
     300                 :             :                                       std::chrono::milliseconds timeout,
     301                 :             :                                       CThreadInterrupt& interrupt,
     302                 :             :                                       size_t max_data) const
     303                 :             : {
     304                 :        1813 :     const auto deadline = GetTime<std::chrono::milliseconds>() + timeout;
     305                 :        1813 :     std::string data;
     306                 :        1813 :     bool terminator_found{false};
     307                 :             : 
     308                 :             :     // We must not consume any bytes past the terminator from the socket.
     309                 :             :     // One option is to read one byte at a time and check if we have read a terminator.
     310                 :             :     // However that is very slow. Instead, we peek at what is in the socket and only read
     311                 :             :     // as many bytes as possible without crossing the terminator.
     312                 :             :     // Reading 64 MiB of random data with 262526 terminator chars takes 37 seconds to read
     313                 :             :     // one byte at a time VS 0.71 seconds with the "peek" solution below. Reading one byte
     314                 :             :     // at a time is about 50 times slower.
     315                 :             : 
     316                 :       19208 :     for (;;) {
     317   [ -  +  +  + ]:       19208 :         if (data.size() >= max_data) {
     318                 :          14 :             throw std::runtime_error(
     319   [ -  +  +  -  :          28 :                 strprintf("Received too many bytes without a terminator (%u)", data.size()));
                   +  - ]
     320                 :             :         }
     321                 :             : 
     322                 :       19194 :         char buf[512];
     323                 :             : 
     324   [ +  +  +  - ]:       38190 :         const ssize_t peek_ret{Recv(buf, std::min(sizeof(buf), max_data - data.size()), MSG_PEEK)};
     325                 :             : 
     326      [ +  +  + ]:       19194 :         switch (peek_ret) {
     327                 :         881 :         case -1: {
     328                 :         881 :             const int err{WSAGetLastError()};
     329         [ +  + ]:         881 :             if (IOErrorIsPermanent(err)) {
     330   [ +  -  +  -  :         202 :                 throw std::runtime_error(strprintf("recv(): %s", NetworkErrorString(err)));
                   +  - ]
     331                 :             :             }
     332                 :             :             break;
     333                 :             :         }
     334                 :         105 :         case 0:
     335         [ +  - ]:         105 :             throw std::runtime_error("Connection unexpectedly closed by peer");
     336                 :       18208 :         default:
     337                 :       18208 :             auto end = buf + peek_ret;
     338                 :       18208 :             auto terminator_pos = std::find(buf, end, terminator);
     339                 :       18208 :             terminator_found = terminator_pos != end;
     340                 :             : 
     341         [ +  + ]:       18208 :             const size_t try_len{terminator_found ? terminator_pos - buf + 1 :
     342                 :             :                                                     static_cast<size_t>(peek_ret)};
     343                 :             : 
     344         [ +  - ]:       18208 :             const ssize_t read_ret{Recv(buf, try_len, 0)};
     345                 :             : 
     346   [ +  +  +  + ]:       18208 :             if (read_ret < 0 || static_cast<size_t>(read_ret) != try_len) {
     347                 :         199 :                 throw std::runtime_error(
     348         [ +  - ]:         199 :                     strprintf("recv() returned %u bytes on attempt to read %u bytes but previous "
     349                 :             :                               "peek claimed %u bytes are available",
     350         [ +  - ]:         597 :                               read_ret, try_len, peek_ret));
     351                 :             :             }
     352                 :             : 
     353                 :             :             // Don't include the terminator in the output.
     354         [ +  + ]:       18009 :             const size_t append_len{terminator_found ? try_len - 1 : try_len};
     355                 :             : 
     356         [ +  - ]:       18009 :             data.append(buf, buf + append_len);
     357                 :             : 
     358         [ +  + ]:       18009 :             if (terminator_found) {
     359                 :        1368 :                 return data;
     360                 :             :             }
     361                 :             :         }
     362                 :             : 
     363                 :       17421 :         const auto now = GetTime<std::chrono::milliseconds>();
     364                 :             : 
     365         [ -  + ]:       17421 :         if (now >= deadline) {
     366                 :           0 :             throw std::runtime_error(strprintf(
     367   [ #  #  #  #  :           0 :                 "Receive timeout (received %u bytes without terminator before that)", data.size()));
                   #  # ]
     368                 :             :         }
     369                 :             : 
     370   [ +  -  +  + ]:       17421 :         if (interrupt) {
     371                 :           0 :             throw std::runtime_error(strprintf(
     372                 :             :                 "Receive interrupted (received %u bytes without terminator before that)",
     373   [ -  +  +  -  :          52 :                 data.size()));
                   +  - ]
     374                 :             :         }
     375                 :             : 
     376                 :             :         // Wait for a short while (or the socket to become ready for reading) before retrying.
     377         [ +  - ]:       17395 :         const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
     378         [ +  - ]:       17395 :         (void)Wait(wait_time, RecvEvent);
     379                 :             :     }
     380                 :         445 : }
     381                 :             : 
     382                 :           0 : bool Sock::IsConnected(std::string& errmsg) const
     383                 :             : {
     384         [ #  # ]:           0 :     if (m_socket == INVALID_SOCKET) {
     385                 :           0 :         errmsg = "not connected";
     386                 :           0 :         return false;
     387                 :             :     }
     388                 :             : 
     389                 :           0 :     char c;
     390      [ #  #  # ]:           0 :     switch (Recv(&c, sizeof(c), MSG_PEEK)) {
     391                 :           0 :     case -1: {
     392                 :           0 :         const int err = WSAGetLastError();
     393         [ #  # ]:           0 :         if (IOErrorIsPermanent(err)) {
     394                 :           0 :             errmsg = NetworkErrorString(err);
     395                 :           0 :             return false;
     396                 :             :         }
     397                 :             :         return true;
     398                 :             :     }
     399                 :           0 :     case 0:
     400                 :           0 :         errmsg = "closed";
     401                 :           0 :         return false;
     402                 :             :     default:
     403                 :             :         return true;
     404                 :             :     }
     405                 :             : }
     406                 :             : 
     407                 :      162260 : void Sock::Close()
     408                 :             : {
     409         [ -  + ]:      162260 :     if (m_socket == INVALID_SOCKET) {
     410                 :             :         return;
     411                 :             :     }
     412                 :             : #ifdef WIN32
     413                 :             :     int ret = closesocket(m_socket);
     414                 :             : #else
     415                 :           0 :     int ret = close(m_socket);
     416                 :             : #endif
     417         [ #  # ]:           0 :     if (ret) {
     418         [ #  # ]:           0 :         LogWarning("Error closing socket %d: %s", m_socket, NetworkErrorString(WSAGetLastError()));
     419                 :             :     }
     420                 :           0 :     m_socket = INVALID_SOCKET;
     421                 :             : }
     422                 :             : 
     423                 :           0 : bool Sock::operator==(SOCKET s) const
     424                 :             : {
     425                 :           0 :     return m_socket == s;
     426                 :             : };
     427                 :             : 
     428                 :       48035 : std::string NetworkErrorString(int err)
     429                 :             : {
     430                 :             : #if defined(WIN32)
     431                 :             :     return Win32ErrorString(err);
     432                 :             : #else
     433                 :             :     // On BSD sockets implementations, NetworkErrorString is the same as SysErrorString.
     434                 :       48035 :     return SysErrorString(err);
     435                 :             : #endif
     436                 :             : }
        

Generated by: LCOV version 2.5.0-full