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