Bitcoin Core 30.99.0
P2P Digital Currency
sock.cpp
Go to the documentation of this file.
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 <common/system.h>
8#include <compat/compat.h>
9#include <span.h>
10#include <tinyformat.h>
11#include <util/log.h>
12#include <util/syserror.h>
13#include <util/threadinterrupt.h>
14#include <util/time.h>
15
16#include <memory>
17#include <stdexcept>
18#include <string>
19
20#ifdef USE_POLL
21#include <poll.h>
22#endif
23
24static inline bool IOErrorIsPermanent(int err)
25{
26 return err != WSAEAGAIN && err != WSAEINTR && err != WSAEWOULDBLOCK && err != WSAEINPROGRESS;
27}
28
29Sock::Sock(SOCKET s) : m_socket(s) {}
30
32{
33 m_socket = other.m_socket;
34 other.m_socket = INVALID_SOCKET;
35}
36
38
40{
41 Close();
42 m_socket = other.m_socket;
43 other.m_socket = INVALID_SOCKET;
44 return *this;
45}
46
47ssize_t Sock::Send(const void* data, size_t len, int flags) const
48{
49 return send(m_socket, static_cast<const char*>(data), len, flags);
50}
51
52ssize_t Sock::Recv(void* buf, size_t len, int flags) const
53{
54 return recv(m_socket, static_cast<char*>(buf), len, flags);
55}
56
57int Sock::Connect(const sockaddr* addr, socklen_t addr_len) const
58{
59 return connect(m_socket, addr, addr_len);
60}
61
62int Sock::Bind(const sockaddr* addr, socklen_t addr_len) const
63{
64 return bind(m_socket, addr, addr_len);
65}
66
67int Sock::Listen(int backlog) const
68{
69 return listen(m_socket, backlog);
70}
71
72std::unique_ptr<Sock> Sock::Accept(sockaddr* addr, socklen_t* addr_len) const
73{
74#ifdef WIN32
75 static constexpr auto ERR = INVALID_SOCKET;
76#else
77 static constexpr auto ERR = SOCKET_ERROR;
78#endif
79
80 std::unique_ptr<Sock> sock;
81
82 const auto socket = accept(m_socket, addr, addr_len);
83 if (socket != ERR) {
84 try {
85 sock = std::make_unique<Sock>(socket);
86 } catch (const std::exception&) {
87#ifdef WIN32
88 closesocket(socket);
89#else
90 close(socket);
91#endif
92 }
93 }
94
95 return sock;
96}
97
98int Sock::GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const
99{
100 return getsockopt(m_socket, level, opt_name, static_cast<char*>(opt_val), opt_len);
101}
102
103int Sock::SetSockOpt(int level, int opt_name, const void* opt_val, socklen_t opt_len) const
104{
105 return setsockopt(m_socket, level, opt_name, static_cast<const char*>(opt_val), opt_len);
106}
107
108int Sock::GetSockName(sockaddr* name, socklen_t* name_len) const
109{
110 return getsockname(m_socket, name, name_len);
111}
112
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 const int flags{fcntl(m_socket, F_GETFL, 0)};
122 if (flags == SOCKET_ERROR) {
123 return false;
124 }
125 if (fcntl(m_socket, F_SETFL, flags | O_NONBLOCK) == SOCKET_ERROR) {
126 return false;
127 }
128#endif
129 return true;
130}
131
133{
134#if defined(USE_POLL) || defined(WIN32)
135 return true;
136#else
137 return m_socket < FD_SETSIZE;
138#endif
139}
140
141bool Sock::Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred) const
142{
143 // We need a `shared_ptr` owning `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. Create it with a custom noop deleter.
146 std::shared_ptr<const Sock> shared{this, [](const Sock*) {}};
147
148 EventsPerSock events_per_sock{std::make_pair(shared, Events{requested})};
149
150 if (!WaitMany(timeout, events_per_sock)) {
151 return false;
152 }
153
154 if (occurred != nullptr) {
155 *occurred = events_per_sock.begin()->second.occurred;
156 }
157
158 return true;
159}
160
161bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const
162{
163#ifdef USE_POLL
164 std::vector<pollfd> pfds;
165 for (const auto& [sock, events] : events_per_sock) {
166 pfds.emplace_back();
167 auto& pfd = pfds.back();
168 pfd.fd = sock->m_socket;
169 if (events.requested & RECV) {
170 pfd.events |= POLLIN;
171 }
172 if (events.requested & SEND) {
173 pfd.events |= POLLOUT;
174 }
175 }
176
177 if (poll(pfds.data(), pfds.size(), count_milliseconds(timeout)) == SOCKET_ERROR) {
178 return false;
179 }
180
181 assert(pfds.size() == events_per_sock.size());
182 size_t i{0};
183 for (auto& [sock, events] : events_per_sock) {
184 assert(sock->m_socket == static_cast<SOCKET>(pfds[i].fd));
185 events.occurred = 0;
186 if (pfds[i].revents & POLLIN) {
187 events.occurred |= RECV;
188 }
189 if (pfds[i].revents & POLLOUT) {
190 events.occurred |= SEND;
191 }
192 if (pfds[i].revents & (POLLERR | POLLHUP)) {
193 events.occurred |= ERR;
194 }
195 ++i;
196 }
197
198 return true;
199#else
200 fd_set recv;
201 fd_set send;
202 fd_set err;
203 FD_ZERO(&recv);
204 FD_ZERO(&send);
205 FD_ZERO(&err);
206 SOCKET socket_max{0};
207
208 for (const auto& [sock, events] : events_per_sock) {
209 if (!sock->IsSelectable()) {
210 return false;
211 }
212 const auto& s = sock->m_socket;
213 if (events.requested & RECV) {
214 FD_SET(s, &recv);
215 }
216 if (events.requested & SEND) {
217 FD_SET(s, &send);
218 }
219 FD_SET(s, &err);
220 socket_max = std::max(socket_max, s);
221 }
222
223 timeval tv = MillisToTimeval(timeout);
224
225 if (select(socket_max + 1, &recv, &send, &err, &tv) == SOCKET_ERROR) {
226 return false;
227 }
228
229 for (auto& [sock, events] : events_per_sock) {
230 const auto& s = sock->m_socket;
231 events.occurred = 0;
232 if (FD_ISSET(s, &recv)) {
233 events.occurred |= RECV;
234 }
235 if (FD_ISSET(s, &send)) {
236 events.occurred |= SEND;
237 }
238 if (FD_ISSET(s, &err)) {
239 events.occurred |= ERR;
240 }
241 }
242
243 return true;
244#endif /* USE_POLL */
245}
246
247void Sock::SendComplete(std::span<const unsigned char> data,
248 std::chrono::milliseconds timeout,
249 CThreadInterrupt& interrupt) const
250{
251 const auto deadline = GetTime<std::chrono::milliseconds>() + timeout;
252 size_t sent{0};
253
254 for (;;) {
255 const ssize_t ret{Send(data.data() + sent, data.size() - sent, MSG_NOSIGNAL)};
256
257 if (ret > 0) {
258 sent += static_cast<size_t>(ret);
259 if (sent == data.size()) {
260 break;
261 }
262 } else {
263 const int err{WSAGetLastError()};
264 if (IOErrorIsPermanent(err)) {
265 throw std::runtime_error(strprintf("send(): %s", NetworkErrorString(err)));
266 }
267 }
268
269 const auto now = GetTime<std::chrono::milliseconds>();
270
271 if (now >= deadline) {
272 throw std::runtime_error(strprintf(
273 "Send timeout (sent only %u of %u bytes before that)", sent, data.size()));
274 }
275
276 if (interrupt) {
277 throw std::runtime_error(strprintf(
278 "Send interrupted (sent only %u of %u bytes before that)", sent, data.size()));
279 }
280
281 // Wait for a short while (or the socket to become ready for sending) before retrying
282 // if nothing was sent.
283 const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
284 (void)Wait(wait_time, SEND);
285 }
286}
287
288void Sock::SendComplete(std::span<const char> data,
289 std::chrono::milliseconds timeout,
290 CThreadInterrupt& interrupt) const
291{
292 SendComplete(MakeUCharSpan(data), timeout, interrupt);
293}
294
295std::string Sock::RecvUntilTerminator(uint8_t terminator,
296 std::chrono::milliseconds timeout,
297 CThreadInterrupt& interrupt,
298 size_t max_data) const
299{
300 const auto deadline = GetTime<std::chrono::milliseconds>() + timeout;
301 std::string data;
302 bool terminator_found{false};
303
304 // We must not consume any bytes past the terminator from the socket.
305 // One option is to read one byte at a time and check if we have read a terminator.
306 // However that is very slow. Instead, we peek at what is in the socket and only read
307 // as many bytes as possible without crossing the terminator.
308 // Reading 64 MiB of random data with 262526 terminator chars takes 37 seconds to read
309 // one byte at a time VS 0.71 seconds with the "peek" solution below. Reading one byte
310 // at a time is about 50 times slower.
311
312 for (;;) {
313 if (data.size() >= max_data) {
314 throw std::runtime_error(
315 strprintf("Received too many bytes without a terminator (%u)", data.size()));
316 }
317
318 char buf[512];
319
320 const ssize_t peek_ret{Recv(buf, std::min(sizeof(buf), max_data - data.size()), MSG_PEEK)};
321
322 switch (peek_ret) {
323 case -1: {
324 const int err{WSAGetLastError()};
325 if (IOErrorIsPermanent(err)) {
326 throw std::runtime_error(strprintf("recv(): %s", NetworkErrorString(err)));
327 }
328 break;
329 }
330 case 0:
331 throw std::runtime_error("Connection unexpectedly closed by peer");
332 default:
333 auto end = buf + peek_ret;
334 auto terminator_pos = std::find(buf, end, terminator);
335 terminator_found = terminator_pos != end;
336
337 const size_t try_len{terminator_found ? terminator_pos - buf + 1 :
338 static_cast<size_t>(peek_ret)};
339
340 const ssize_t read_ret{Recv(buf, try_len, 0)};
341
342 if (read_ret < 0 || static_cast<size_t>(read_ret) != try_len) {
343 throw std::runtime_error(
344 strprintf("recv() returned %u bytes on attempt to read %u bytes but previous "
345 "peek claimed %u bytes are available",
346 read_ret, try_len, peek_ret));
347 }
348
349 // Don't include the terminator in the output.
350 const size_t append_len{terminator_found ? try_len - 1 : try_len};
351
352 data.append(buf, buf + append_len);
353
354 if (terminator_found) {
355 return data;
356 }
357 }
358
359 const auto now = GetTime<std::chrono::milliseconds>();
360
361 if (now >= deadline) {
362 throw std::runtime_error(strprintf(
363 "Receive timeout (received %u bytes without terminator before that)", data.size()));
364 }
365
366 if (interrupt) {
367 throw std::runtime_error(strprintf(
368 "Receive interrupted (received %u bytes without terminator before that)",
369 data.size()));
370 }
371
372 // Wait for a short while (or the socket to become ready for reading) before retrying.
373 const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
374 (void)Wait(wait_time, RECV);
375 }
376}
377
378bool Sock::IsConnected(std::string& errmsg) const
379{
380 if (m_socket == INVALID_SOCKET) {
381 errmsg = "not connected";
382 return false;
383 }
384
385 char c;
386 switch (Recv(&c, sizeof(c), MSG_PEEK)) {
387 case -1: {
388 const int err = WSAGetLastError();
389 if (IOErrorIsPermanent(err)) {
390 errmsg = NetworkErrorString(err);
391 return false;
392 }
393 return true;
394 }
395 case 0:
396 errmsg = "closed";
397 return false;
398 default:
399 return true;
400 }
401}
402
404{
405 if (m_socket == INVALID_SOCKET) {
406 return;
407 }
408#ifdef WIN32
409 int ret = closesocket(m_socket);
410#else
411 int ret = close(m_socket);
412#endif
413 if (ret) {
414 LogWarning("Error closing socket %d: %s", m_socket, NetworkErrorString(WSAGetLastError()));
415 }
417}
418
420{
421 return m_socket == s;
422};
423
424std::string NetworkErrorString(int err)
425{
426#if defined(WIN32)
427 return Win32ErrorString(err);
428#else
429 // On BSD sockets implementations, NetworkErrorString is the same as SysErrorString.
430 return SysErrorString(err);
431#endif
432}
int ret
int flags
Definition: bitcoin-tx.cpp:529
A helper class for interruptible sleeps.
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:28
virtual std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const
accept(2) wrapper.
Definition: sock.cpp:72
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:47
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition: sock.h:149
SOCKET m_socket
Contained socket.
Definition: sock.h:276
Sock & operator=(const Sock &)=delete
Copy assignment operator, disabled because closing the same socket twice is undesirable.
virtual int Bind(const sockaddr *addr, socklen_t addr_len) const
bind(2) wrapper.
Definition: sock.cpp:62
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
Definition: sock.cpp:141
virtual ~Sock()
Destructor, close the socket or do nothing if empty.
Definition: sock.cpp:37
virtual void SendComplete(std::span< const unsigned char > data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
Definition: sock.cpp:247
uint8_t Event
Definition: sock.h:139
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
Definition: sock.cpp:108
void Close()
Close m_socket if it is not INVALID_SOCKET.
Definition: sock.cpp:403
virtual bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock &events_per_sock) const
Same as Wait(), but wait on many sockets within the same timeout.
Definition: sock.cpp:161
static constexpr Event ERR
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
Definition: sock.h:155
virtual bool IsConnected(std::string &errmsg) const
Check if still connected.
Definition: sock.cpp:378
virtual int SetSockOpt(int level, int opt_name, const void *opt_val, socklen_t opt_len) const
setsockopt(2) wrapper.
Definition: sock.cpp:103
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:144
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:98
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:57
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:52
Sock()=delete
virtual std::string RecvUntilTerminator(uint8_t terminator, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt, size_t max_data) const
Read from socket until a terminator character is encountered.
Definition: sock.cpp:295
virtual int Listen(int backlog) const
listen(2) wrapper.
Definition: sock.cpp:67
virtual bool SetNonBlocking() const
Set the non-blocking option on the socket.
Definition: sock.cpp:113
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
Definition: sock.h:209
virtual bool IsSelectable() const
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition: sock.cpp:132
bool operator==(SOCKET s) const
Check if the internal socket is equal to s.
Definition: sock.cpp:419
#define INVALID_SOCKET
Definition: compat.h:67
#define WSAEWOULDBLOCK
Definition: compat.h:61
#define SOCKET_ERROR
Definition: compat.h:68
#define WSAGetLastError()
Definition: compat.h:59
#define MSG_NOSIGNAL
Definition: compat.h:110
unsigned int SOCKET
Definition: compat.h:57
#define WSAEINPROGRESS
Definition: compat.h:65
#define WSAEINTR
Definition: compat.h:64
#define WSAEAGAIN
Definition: compat.h:62
#define LogWarning(...)
Definition: log.h:96
RPCHelpMan send()
Definition: spend.cpp:1217
const char * name
Definition: rest.cpp:48
static bool IOErrorIsPermanent(int err)
Definition: sock.cpp:24
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:424
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:22
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition: span.h:111
Auxiliary requested/occurred events to wait for in WaitMany().
Definition: sock.h:174
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:17
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:142
constexpr int64_t count_milliseconds(std::chrono::milliseconds t)
Definition: time.h:89
assert(!tx.IsCoinBase())