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