Coverage Report

Created: 2026-11-13 17:38

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