netbase.cpp raw
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include <bitcoin-build-config.h> // IWYU pragma: keep
7
8 #include <netbase.h>
9
10 #include <compat/compat.h>
11 #include <sync.h>
12 #include <tinyformat.h>
13 #include <util/log.h>
14 #include <util/sock.h>
15 #include <util/strencodings.h>
16 #include <util/string.h>
17 #include <util/time.h>
18
19 #include <atomic>
20 #include <chrono>
21 #include <cstdint>
22 #include <functional>
23 #include <limits>
24 #include <memory>
25
26 #ifdef HAVE_SOCKADDR_UN
27 #include <sys/un.h>
28 #endif
29
30 using util::ContainsNoNUL;
31
32 // Settings
33 static GlobalMutex g_proxyinfo_mutex;
34 static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
35 static Proxy nameProxy GUARDED_BY(g_proxyinfo_mutex);
36 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
37 bool fNameLookup = DEFAULT_NAME_LOOKUP;
38
39 // Need ample time for negotiation for very slow proxies such as Tor
40 std::chrono::milliseconds g_socks5_recv_timeout = 20s;
41 CThreadInterrupt g_socks5_interrupt;
42
43 ReachableNets g_reachable_nets;
44
45 std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
46 {
47 addrinfo ai_hint{};
48 // We want a TCP port, which is a streaming socket type
49 ai_hint.ai_socktype = SOCK_STREAM;
50 ai_hint.ai_protocol = IPPROTO_TCP;
51 // We don't care which address family (IPv4 or IPv6) is returned
52 ai_hint.ai_family = AF_UNSPEC;
53
54 // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
55 // return addresses whose family we have an address configured for.
56 //
57 // If we don't allow lookups, then use the AI_NUMERICHOST flag for
58 // getaddrinfo to only decode numerical network addresses and suppress
59 // hostname lookups.
60 ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
61
62 addrinfo* ai_res{nullptr};
63 const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
64 if (n_err != 0) {
65 if ((ai_hint.ai_flags & AI_ADDRCONFIG) == AI_ADDRCONFIG) {
66 // AI_ADDRCONFIG on some systems may exclude loopback-only addresses
67 // If first lookup failed we perform a second lookup without AI_ADDRCONFIG
68 ai_hint.ai_flags = (ai_hint.ai_flags & ~AI_ADDRCONFIG);
69 const int n_err_retry{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
70 if (n_err_retry != 0) {
71 return {};
72 }
73 } else {
74 return {};
75 }
76 }
77
78 // Traverse the linked list starting with ai_trav.
79 addrinfo* ai_trav{ai_res};
80 std::vector<CNetAddr> resolved_addresses;
81 while (ai_trav != nullptr) {
82 if (ai_trav->ai_family == AF_INET) {
83 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
84 resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
85 }
86 if (ai_trav->ai_family == AF_INET6) {
87 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
88 const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
89 resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
90 }
91 ai_trav = ai_trav->ai_next;
92 }
93 freeaddrinfo(ai_res);
94
95 return resolved_addresses;
96 }
97
98 DNSLookupFn g_dns_lookup{WrappedGetAddrInfo};
99
100 enum Network ParseNetwork(const std::string& net_in) {
101 std::string net = ToLower(net_in);
102 if (net == "ipv4") return NET_IPV4;
103 if (net == "ipv6") return NET_IPV6;
104 if (net == "onion") return NET_ONION;
105 if (net == "i2p") {
106 return NET_I2P;
107 }
108 if (net == "cjdns") {
109 return NET_CJDNS;
110 }
111 return NET_UNROUTABLE;
112 }
113
114 std::string GetNetworkName(enum Network net)
115 {
116 switch (net) {
117 case NET_UNROUTABLE: return "not_publicly_routable";
118 case NET_IPV4: return "ipv4";
119 case NET_IPV6: return "ipv6";
120 case NET_ONION: return "onion";
121 case NET_I2P: return "i2p";
122 case NET_CJDNS: return "cjdns";
123 case NET_INTERNAL: return "internal";
124 case NET_MAX: assert(false);
125 } // no default case, so the compiler can warn about missing cases
126
127 assert(false);
128 }
129
130 std::vector<std::string> GetNetworkNames(bool append_unroutable)
131 {
132 std::vector<std::string> names;
133 for (int n = 0; n < NET_MAX; ++n) {
134 const enum Network network{static_cast<Network>(n)};
135 if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
136 names.emplace_back(GetNetworkName(network));
137 }
138 if (append_unroutable) {
139 names.emplace_back(GetNetworkName(NET_UNROUTABLE));
140 }
141 return names;
142 }
143
144 static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
145 {
146 if (!ContainsNoNUL(name)) return {};
147 {
148 CNetAddr addr;
149 // From our perspective, onion addresses are not hostnames but rather
150 // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
151 // or IPv6 colon-separated hextet notation. Since we can't use
152 // getaddrinfo to decode them and it wouldn't make sense to resolve
153 // them, we return a network address representing it instead. See
154 // CNetAddr::SetSpecial(const std::string&) for more details.
155 if (addr.SetSpecial(name)) return {addr};
156 }
157
158 std::vector<CNetAddr> addresses;
159
160 for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
161 if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) {
162 break;
163 }
164 /* Never allow resolving to an internal address. Consider any such result invalid */
165 if (!resolved.IsInternal()) {
166 addresses.push_back(resolved);
167 }
168 }
169
170 return addresses;
171 }
172
173 std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
174 {
175 if (!ContainsNoNUL(name)) return {};
176 std::string strHost = name;
177 if (strHost.empty()) return {};
178 if (strHost.front() == '[' && strHost.back() == ']') {
179 strHost = strHost.substr(1, strHost.size() - 2);
180 }
181
182 return LookupIntern(strHost, nMaxSolutions, fAllowLookup, dns_lookup_function);
183 }
184
185 std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function)
186 {
187 const std::vector<CNetAddr> addresses{LookupHost(name, 1, fAllowLookup, dns_lookup_function)};
188 return addresses.empty() ? std::nullopt : std::make_optional(addresses.front());
189 }
190
191 std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
192 {
193 if (name.empty() || !ContainsNoNUL(name)) {
194 return {};
195 }
196 uint16_t port{portDefault};
197 std::string hostname;
198 SplitHostPort(name, port, hostname);
199
200 const std::vector<CNetAddr> addresses{LookupIntern(hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)};
201 if (addresses.empty()) return {};
202 std::vector<CService> services;
203 services.reserve(addresses.size());
204 for (const auto& addr : addresses)
205 services.emplace_back(addr, port);
206 return services;
207 }
208
209 std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
210 {
211 const std::vector<CService> services{Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)};
212
213 return services.empty() ? std::nullopt : std::make_optional(services.front());
214 }
215
216 CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
217 {
218 if (!ContainsNoNUL(name)) {
219 return {};
220 }
221 // "1.2:345" will fail to resolve the ip, but will still set the port.
222 // If the ip fails to resolve, re-init the result.
223 return Lookup(name, portDefault, /*fAllowLookup=*/false, dns_lookup_function).value_or(CService{});
224 }
225
226 bool IsUnixSocketPath(const std::string& name)
227 {
228 #ifdef HAVE_SOCKADDR_UN
229 if (!name.starts_with(ADDR_PREFIX_UNIX)) return false;
230
231 // Split off "unix:" prefix
232 std::string str{name.substr(ADDR_PREFIX_UNIX.length())};
233
234 // Path size limit is platform-dependent
235 // see https://manpages.ubuntu.com/manpages/xenial/en/man7/unix.7.html
236 if (str.size() + 1 > sizeof(((sockaddr_un*)nullptr)->sun_path)) return false;
237
238 return true;
239 #else
240 return false;
241 #endif
242 }
243
244 /** SOCKS version */
245 enum SOCKSVersion: uint8_t {
246 SOCKS4 = 0x04,
247 SOCKS5 = 0x05
248 };
249
250 /** Values defined for METHOD in RFC1928 */
251 enum SOCKS5Method: uint8_t {
252 NOAUTH = 0x00, //!< No authentication required
253 GSSAPI = 0x01, //!< GSSAPI
254 USER_PASS = 0x02, //!< Username/password
255 NO_ACCEPTABLE = 0xff, //!< No acceptable methods
256 };
257
258 /** Values defined for CMD in RFC1928 */
259 enum SOCKS5Command: uint8_t {
260 CONNECT = 0x01,
261 BIND = 0x02,
262 UDP_ASSOCIATE = 0x03
263 };
264
265 /** Values defined for REP in RFC1928 and https://spec.torproject.org/socks-extensions.html */
266 enum SOCKS5Reply: uint8_t {
267 SUCCEEDED = 0x00, //!< RFC1928: Succeeded
268 GENFAILURE = 0x01, //!< RFC1928: General failure
269 NOTALLOWED = 0x02, //!< RFC1928: Connection not allowed by ruleset
270 NETUNREACHABLE = 0x03, //!< RFC1928: Network unreachable
271 HOSTUNREACHABLE = 0x04, //!< RFC1928: Network unreachable
272 CONNREFUSED = 0x05, //!< RFC1928: Connection refused
273 TTLEXPIRED = 0x06, //!< RFC1928: TTL expired
274 CMDUNSUPPORTED = 0x07, //!< RFC1928: Command not supported
275 ATYPEUNSUPPORTED = 0x08, //!< RFC1928: Address type not supported
276 TOR_HS_DESC_NOT_FOUND = 0xf0, //!< Tor: Onion service descriptor can not be found
277 TOR_HS_DESC_INVALID = 0xf1, //!< Tor: Onion service descriptor is invalid
278 TOR_HS_INTRO_FAILED = 0xf2, //!< Tor: Onion service introduction failed
279 TOR_HS_REND_FAILED = 0xf3, //!< Tor: Onion service rendezvous failed
280 TOR_HS_MISSING_CLIENT_AUTH = 0xf4, //!< Tor: Onion service missing client authorization
281 TOR_HS_WRONG_CLIENT_AUTH = 0xf5, //!< Tor: Onion service wrong client authorization
282 TOR_HS_BAD_ADDRESS = 0xf6, //!< Tor: Onion service invalid address
283 TOR_HS_INTRO_TIMEOUT = 0xf7, //!< Tor: Onion service introduction timed out
284 };
285
286 /** Values defined for ATYPE in RFC1928 */
287 enum SOCKS5Atyp: uint8_t {
288 IPV4 = 0x01,
289 DOMAINNAME = 0x03,
290 IPV6 = 0x04,
291 };
292
293 /** Status codes that can be returned by InterruptibleRecv */
294 enum class IntrRecvError {
295 OK,
296 Timeout,
297 Disconnected,
298 NetworkError,
299 Interrupted
300 };
301
302 /**
303 * Try to read a specified number of bytes from a socket. Please read the "see
304 * also" section for more detail.
305 *
306 * @param data The buffer where the read bytes should be stored.
307 * @param len The number of bytes to read into the specified buffer.
308 * @param timeout The total timeout for this read.
309 * @param sock The socket (has to be in non-blocking mode) from which to read bytes.
310 *
311 * @returns An IntrRecvError indicating the resulting status of this read.
312 * IntrRecvError::OK only if all of the specified number of bytes were
313 * read.
314 *
315 * @see This function can be interrupted by calling g_socks5_interrupt().
316 * Sockets can be made non-blocking with Sock::SetNonBlocking().
317 */
318 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, std::chrono::milliseconds timeout, const Sock& sock)
319 {
320 auto curTime{Now<SteadyMilliseconds>()};
321 const auto endTime{curTime + timeout};
322 while (len > 0 && curTime < endTime) {
323 ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
324 if (ret > 0) {
325 len -= ret;
326 data += ret;
327 } else if (ret == 0) { // Unexpected disconnection
328 return IntrRecvError::Disconnected;
329 } else { // Other error or blocking
330 int nErr = WSAGetLastError();
331 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
332 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
333 // we're approaching the end of the specified total timeout
334 const auto remaining = std::chrono::milliseconds{endTime - curTime};
335 const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
336 if (!sock.Wait(timeout, Sock::RecvEvent)) {
337 return IntrRecvError::NetworkError;
338 }
339 } else {
340 return IntrRecvError::NetworkError;
341 }
342 }
343 if (g_socks5_interrupt) {
344 return IntrRecvError::Interrupted;
345 }
346 curTime = Now<SteadyMilliseconds>();
347 }
348 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
349 }
350
351 /** Convert SOCKS5 reply to an error message */
352 static std::string Socks5ErrorString(uint8_t err)
353 {
354 switch(err) {
355 case SOCKS5Reply::GENFAILURE:
356 return "general failure";
357 case SOCKS5Reply::NOTALLOWED:
358 return "connection not allowed";
359 case SOCKS5Reply::NETUNREACHABLE:
360 return "network unreachable";
361 case SOCKS5Reply::HOSTUNREACHABLE:
362 return "host unreachable";
363 case SOCKS5Reply::CONNREFUSED:
364 return "connection refused";
365 case SOCKS5Reply::TTLEXPIRED:
366 return "TTL expired";
367 case SOCKS5Reply::CMDUNSUPPORTED:
368 return "protocol error";
369 case SOCKS5Reply::ATYPEUNSUPPORTED:
370 return "address type not supported";
371 case SOCKS5Reply::TOR_HS_DESC_NOT_FOUND:
372 return "onion service descriptor can not be found";
373 case SOCKS5Reply::TOR_HS_DESC_INVALID:
374 return "onion service descriptor is invalid";
375 case SOCKS5Reply::TOR_HS_INTRO_FAILED:
376 return "onion service introduction failed";
377 case SOCKS5Reply::TOR_HS_REND_FAILED:
378 return "onion service rendezvous failed";
379 case SOCKS5Reply::TOR_HS_MISSING_CLIENT_AUTH:
380 return "onion service missing client authorization";
381 case SOCKS5Reply::TOR_HS_WRONG_CLIENT_AUTH:
382 return "onion service wrong client authorization";
383 case SOCKS5Reply::TOR_HS_BAD_ADDRESS:
384 return "onion service invalid address";
385 case SOCKS5Reply::TOR_HS_INTRO_TIMEOUT:
386 return "onion service introduction timed out";
387 default:
388 return strprintf("unknown (0x%02x)", err);
389 }
390 }
391
392 bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
393 {
394 try {
395 IntrRecvError recvr;
396 LogDebug(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
397 if (strDest.size() > 255) {
398 LogError("Hostname too long\n");
399 return false;
400 }
401 // Construct the version identifier/method selection message
402 std::vector<uint8_t> vSocks5Init;
403 vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
404 if (auth) {
405 vSocks5Init.push_back(0x02); // 2 method identifiers follow...
406 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
407 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
408 } else {
409 vSocks5Init.push_back(0x01); // 1 method identifier follows...
410 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
411 }
412 sock.SendComplete(vSocks5Init, g_socks5_recv_timeout, g_socks5_interrupt);
413 uint8_t pchRet1[2];
414 if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
415 LogInfo("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
416 return false;
417 }
418 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
419 LogError("Proxy failed to initialize\n");
420 return false;
421 }
422 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
423 // Perform username/password authentication (as described in RFC1929)
424 std::vector<uint8_t> vAuth;
425 vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
426 if (auth->username.size() > 255 || auth->password.size() > 255) {
427 LogError("Proxy username or password too long\n");
428 return false;
429 }
430 vAuth.push_back(auth->username.size());
431 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
432 vAuth.push_back(auth->password.size());
433 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
434 LogDebug(BCLog::PROXY, "SOCKS5 sending username/password authentication\n");
435 sock.SendComplete(vAuth, g_socks5_recv_timeout, g_socks5_interrupt);
436 uint8_t pchRetA[2];
437 if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
438 LogError("Error reading proxy authentication response\n");
439 return false;
440 }
441 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
442 LogError("Proxy authentication unsuccessful\n");
443 return false;
444 }
445 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
446 // Perform no authentication
447 } else {
448 LogError("Proxy requested wrong authentication method %02x\n", pchRet1[1]);
449 return false;
450 }
451 std::vector<uint8_t> vSocks5;
452 vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
453 vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
454 vSocks5.push_back(0x00); // RSV Reserved must be 0
455 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
456 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
457 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
458 vSocks5.push_back((port >> 8) & 0xFF);
459 vSocks5.push_back((port >> 0) & 0xFF);
460 sock.SendComplete(vSocks5, g_socks5_recv_timeout, g_socks5_interrupt);
461 uint8_t pchRet2[4];
462 if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
463 if (recvr == IntrRecvError::Timeout) {
464 /* If a timeout happens here, this effectively means we timed out while connecting
465 * to the remote node. This is very common for Tor, so do not print an
466 * error message. */
467 return false;
468 } else {
469 LogError("Error while reading proxy response\n");
470 return false;
471 }
472 }
473 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
474 LogError("Proxy failed to accept request\n");
475 return false;
476 }
477 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
478 // Failures to connect to a peer that are not proxy errors
479 LogDebug(BCLog::NET,
480 "Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
481 return false;
482 }
483 if (pchRet2[2] != 0x00) { // Reserved field must be 0
484 LogError("Error: malformed proxy response\n");
485 return false;
486 }
487 uint8_t pchRet3[256];
488 switch (pchRet2[3]) {
489 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
490 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
491 case SOCKS5Atyp::DOMAINNAME: {
492 recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
493 if (recvr != IntrRecvError::OK) {
494 LogError("Error reading from proxy\n");
495 return false;
496 }
497 int nRecv = pchRet3[0];
498 recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
499 break;
500 }
501 default: {
502 LogError("Error: malformed proxy response\n");
503 return false;
504 }
505 }
506 if (recvr != IntrRecvError::OK) {
507 LogError("Error reading from proxy\n");
508 return false;
509 }
510 if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
511 LogError("Error reading from proxy\n");
512 return false;
513 }
514 LogDebug(BCLog::NET, "SOCKS5 connected %s\n", strDest);
515 return true;
516 } catch (const std::runtime_error& e) {
517 LogError("Error during SOCKS5 proxy handshake: %s\n", e.what());
518 return false;
519 }
520 }
521
522 std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol)
523 {
524 // Not IPv4, IPv6 or UNIX
525 if (domain == AF_UNSPEC) return nullptr;
526
527 // Create a socket in the specified address family.
528 SOCKET hSocket = socket(domain, type, protocol);
529 if (hSocket == INVALID_SOCKET) {
530 return nullptr;
531 }
532
533 auto sock = std::make_unique<Sock>(hSocket);
534
535 if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNIX) {
536 return sock;
537 }
538
539 // Ensure that waiting for I/O on this socket won't result in undefined
540 // behavior.
541 if (!sock->IsSelectable()) {
542 LogInfo("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
543 return nullptr;
544 }
545
546 #ifdef SO_NOSIGPIPE
547 int set = 1;
548 // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
549 // should use the MSG_NOSIGNAL flag for every send.
550 if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof(int)) == SOCKET_ERROR) {
551 LogInfo("Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n",
552 NetworkErrorString(WSAGetLastError()));
553 }
554 #endif
555
556 // Set the non-blocking option on the socket.
557 if (!sock->SetNonBlocking()) {
558 LogInfo("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
559 return nullptr;
560 }
561
562 #ifdef HAVE_SOCKADDR_UN
563 if (domain == AF_UNIX) return sock;
564 #endif
565
566 if (protocol == IPPROTO_TCP) {
567 // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
568 const int on{1};
569 if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
570 LogDebug(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
571 }
572 }
573
574 return sock;
575 }
576
577 std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock = CreateSockOS;
578
579 template<typename... Args>
580 static void LogConnectFailure(bool manual_connection, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
581 {
582 std::string error_message = tfm::format(fmt, args...);
583 if (manual_connection) {
584 LogInfo("%s\n", error_message);
585 } else {
586 LogDebug(BCLog::NET, "%s\n", error_message);
587 }
588 }
589
590 static bool ConnectToSocket(const Sock& sock,
591 struct sockaddr* sockaddr,
592 socklen_t len,
593 const std::string& dest_str,
594 bool manual_connection,
595 std::chrono::milliseconds timeout)
596 {
597 // Connect to `sockaddr` using `sock`.
598 if (sock.Connect(sockaddr, len) == SOCKET_ERROR) {
599 int nErr = WSAGetLastError();
600 // WSAEINVAL is here because some legacy version of winsock uses it
601 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
602 {
603 // Connection didn't actually fail, but is being established
604 // asynchronously. Thus, use async I/O api (select/poll)
605 // synchronously to check for successful connection with a timeout.
606 const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent;
607 Sock::Event occurred;
608 if (!sock.Wait(timeout, requested, &occurred)) {
609 LogInfo("wait for connect to %s failed: %s\n",
610 dest_str,
611 NetworkErrorString(WSAGetLastError()));
612 return false;
613 } else if (occurred == 0) {
614 LogDebug(BCLog::NET, "connection attempt to %s timed out\n", dest_str);
615 return false;
616 }
617
618 // Even if the wait was successful, the connect might not
619 // have been successful. The reason for this failure is hidden away
620 // in the SO_ERROR for the socket in modern systems. We read it into
621 // sockerr here.
622 int sockerr;
623 socklen_t sockerr_len = sizeof(sockerr);
624 if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, &sockerr, &sockerr_len) ==
625 SOCKET_ERROR) {
626 LogInfo("getsockopt() for %s failed: %s\n", dest_str, NetworkErrorString(WSAGetLastError()));
627 return false;
628 }
629 if (sockerr != 0) {
630 LogConnectFailure(manual_connection,
631 "connect() to %s failed after wait: %s",
632 dest_str,
633 NetworkErrorString(sockerr));
634 return false;
635 }
636 }
637 #ifdef WIN32
638 else if (WSAGetLastError() != WSAEISCONN)
639 #else
640 else
641 #endif
642 {
643 LogConnectFailure(manual_connection, "connect() to %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError()));
644 return false;
645 }
646 }
647 return true;
648 }
649
650 std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection)
651 {
652 return ConnectDirectly(dest, manual_connection, std::chrono::milliseconds{nConnectTimeout});
653 }
654
655 std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
656 bool manual_connection,
657 std::chrono::milliseconds timeout)
658 {
659 auto sock = CreateSock(dest.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
660 if (!sock) {
661 LogError("Cannot create a socket for connecting to %s\n", dest.ToStringAddrPort());
662 return {};
663 }
664
665 // Create a sockaddr from the specified service.
666 struct sockaddr_storage sockaddr;
667 socklen_t len = sizeof(sockaddr);
668 if (!dest.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
669 LogInfo("Cannot get sockaddr for %s: unsupported network\n", dest.ToStringAddrPort());
670 return {};
671 }
672
673 if (!ConnectToSocket(*sock, (struct sockaddr*)&sockaddr, len, dest.ToStringAddrPort(), manual_connection, timeout)) {
674 return {};
675 }
676
677 return sock;
678 }
679
680 std::unique_ptr<Sock> Proxy::Connect() const
681 {
682 if (!IsValid()) return {};
683
684 if (!m_is_unix_socket) return ConnectDirectly(proxy, /*manual_connection=*/true);
685
686 #ifdef HAVE_SOCKADDR_UN
687 auto sock = CreateSock(AF_UNIX, SOCK_STREAM, 0);
688 if (!sock) {
689 LogError("Cannot create a socket for connecting to %s\n", m_unix_socket_path);
690 return {};
691 }
692
693 const std::string path{m_unix_socket_path.substr(ADDR_PREFIX_UNIX.length())};
694
695 struct sockaddr_un addrun;
696 memset(&addrun, 0, sizeof(addrun));
697 addrun.sun_family = AF_UNIX;
698 // leave the last char in addrun.sun_path[] to be always '\0'
699 memcpy(addrun.sun_path, path.c_str(), std::min(sizeof(addrun.sun_path) - 1, path.length()));
700 socklen_t len = sizeof(addrun);
701
702 if (!ConnectToSocket(*sock,
703 (struct sockaddr*)&addrun,
704 len,
705 path,
706 /*manual_connection=*/true,
707 std::chrono::milliseconds{nConnectTimeout})) {
708 return {};
709 }
710
711 return sock;
712 #else
713 return {};
714 #endif
715 }
716
717 bool SetProxy(enum Network net, const Proxy &addrProxy) {
718 assert(net >= 0 && net < NET_MAX);
719 if (!addrProxy.IsValid())
720 return false;
721 LOCK(g_proxyinfo_mutex);
722 proxyInfo[net] = addrProxy;
723 return true;
724 }
725
726 std::optional<Proxy> GetProxy(enum Network net)
727 {
728 assert(net >= 0 && net < NET_MAX);
729 LOCK(g_proxyinfo_mutex);
730 if (!proxyInfo[net].IsValid()) {
731 return std::nullopt;
732 }
733 return proxyInfo[net];
734 }
735
736 bool SetNameProxy(const Proxy &addrProxy) {
737 if (!addrProxy.IsValid())
738 return false;
739 LOCK(g_proxyinfo_mutex);
740 nameProxy = addrProxy;
741 return true;
742 }
743
744 std::optional<Proxy> GetNameProxy()
745 {
746 LOCK(g_proxyinfo_mutex);
747 if (!nameProxy.IsValid()) {
748 return std::nullopt;
749 }
750 return nameProxy;
751 }
752
753 bool HaveNameProxy() {
754 LOCK(g_proxyinfo_mutex);
755 return nameProxy.IsValid();
756 }
757
758 bool IsProxy(const CNetAddr &addr) {
759 LOCK(g_proxyinfo_mutex);
760 for (int i = 0; i < NET_MAX; i++) {
761 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
762 return true;
763 }
764 return false;
765 }
766
767 /**
768 * Generate unique credentials for Tor stream isolation. Tor will create
769 * separate circuits for SOCKS5 proxy connections with different credentials, which
770 * makes it harder to correlate the connections.
771 */
772 class TorStreamIsolationCredentialsGenerator
773 {
774 public:
775 TorStreamIsolationCredentialsGenerator():
776 m_prefix(GenerateUniquePrefix()) {
777 }
778
779 /** Return the next unique proxy credentials. */
780 ProxyCredentials Generate() {
781 ProxyCredentials auth;
782 auth.username = auth.password = strprintf("%s%i", m_prefix, m_counter);
783 ++m_counter;
784 return auth;
785 }
786
787 /** Size of session prefix in bytes. */
788 static constexpr size_t PREFIX_BYTE_LENGTH = 8;
789 private:
790 const std::string m_prefix;
791 std::atomic<uint64_t> m_counter;
792
793 /** Generate a random prefix for each of the credentials returned by this generator.
794 * This makes sure that different launches of the application (either successively or in parallel)
795 * will not share the same circuits, as would be the case with a bare counter.
796 */
797 static std::string GenerateUniquePrefix() {
798 std::array<uint8_t, PREFIX_BYTE_LENGTH> prefix_bytes;
799 GetRandBytes(prefix_bytes);
800 return HexStr(prefix_bytes) + "-";
801 }
802 };
803
804 std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
805 const std::string& dest,
806 uint16_t port,
807 bool& proxy_connection_failed)
808 {
809 // first connect to proxy server
810 auto sock = proxy.Connect();
811 if (!sock) {
812 proxy_connection_failed = true;
813 return {};
814 }
815
816 // do socks negotiation
817 if (proxy.m_tor_stream_isolation) {
818 static TorStreamIsolationCredentialsGenerator generator;
819 ProxyCredentials random_auth{generator.Generate()};
820 if (!Socks5(dest, port, &random_auth, *sock)) {
821 return {};
822 }
823 } else {
824 if (!Socks5(dest, port, nullptr, *sock)) {
825 return {};
826 }
827 }
828 return sock;
829 }
830
831 CSubNet LookupSubNet(const std::string& subnet_str)
832 {
833 CSubNet subnet;
834 assert(!subnet.IsValid());
835 if (!ContainsNoNUL(subnet_str)) {
836 return subnet;
837 }
838
839 const size_t slash_pos{subnet_str.find_last_of('/')};
840 const std::string str_addr{subnet_str.substr(0, slash_pos)};
841 std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)};
842
843 if (addr.has_value()) {
844 addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
845 if (slash_pos != subnet_str.npos) {
846 const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
847 if (const auto netmask{ToIntegral<uint8_t>(netmask_str)}) {
848 // Valid number; assume CIDR variable-length subnet masking.
849 subnet = CSubNet{addr.value(), *netmask};
850 } else {
851 // Invalid number; try full netmask syntax. Never allow lookup for netmask.
852 const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)};
853 if (full_netmask.has_value()) {
854 subnet = CSubNet{addr.value(), full_netmask.value()};
855 }
856 }
857 } else {
858 // Single IP subnet (<ipv4>/32 or <ipv6>/128).
859 subnet = CSubNet{addr.value()};
860 }
861 }
862
863 return subnet;
864 }
865
866 bool IsBadPort(uint16_t port)
867 {
868 /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */
869
870 switch (port) {
871 case 1: // tcpmux
872 case 7: // echo
873 case 9: // discard
874 case 11: // systat
875 case 13: // daytime
876 case 15: // netstat
877 case 17: // qotd
878 case 19: // chargen
879 case 20: // ftp data
880 case 21: // ftp access
881 case 22: // ssh
882 case 23: // telnet
883 case 25: // smtp
884 case 37: // time
885 case 42: // name
886 case 43: // nicname
887 case 53: // domain
888 case 69: // tftp
889 case 77: // priv-rjs
890 case 79: // finger
891 case 87: // ttylink
892 case 95: // supdup
893 case 101: // hostname
894 case 102: // iso-tsap
895 case 103: // gppitnp
896 case 104: // acr-nema
897 case 109: // pop2
898 case 110: // pop3
899 case 111: // sunrpc
900 case 113: // auth
901 case 115: // sftp
902 case 117: // uucp-path
903 case 119: // nntp
904 case 123: // NTP
905 case 135: // loc-srv /epmap
906 case 137: // netbios
907 case 139: // netbios
908 case 143: // imap2
909 case 161: // snmp
910 case 179: // BGP
911 case 389: // ldap
912 case 427: // SLP (Also used by Apple Filing Protocol)
913 case 465: // smtp+ssl
914 case 512: // print / exec
915 case 513: // login
916 case 514: // shell
917 case 515: // printer
918 case 526: // tempo
919 case 530: // courier
920 case 531: // chat
921 case 532: // netnews
922 case 540: // uucp
923 case 548: // AFP (Apple Filing Protocol)
924 case 554: // rtsp
925 case 556: // remotefs
926 case 563: // nntp+ssl
927 case 587: // smtp (rfc6409)
928 case 601: // syslog-conn (rfc3195)
929 case 636: // ldap+ssl
930 case 989: // ftps-data
931 case 990: // ftps
932 case 993: // ldap+ssl
933 case 995: // pop3+ssl
934 case 1719: // h323gatestat
935 case 1720: // h323hostcall
936 case 1723: // pptp
937 case 2049: // nfs
938 case 3306: // MySQL
939 case 3389: // RDP / Windows Remote Desktop
940 case 3659: // apple-sasl / PasswordServer
941 case 4045: // lockd
942 case 5060: // sip
943 case 5061: // sips
944 case 5432: // PostgreSQL
945 case 5900: // VNC
946 case 6000: // X11
947 case 6566: // sane-port
948 case 6665: // Alternate IRC
949 case 6666: // Alternate IRC
950 case 6667: // Standard IRC
951 case 6668: // Alternate IRC
952 case 6669: // Alternate IRC
953 case 6697: // IRC + TLS
954 case 10080: // Amanda
955 case 27017: // MongoDB
956 return true;
957 }
958 return false;
959 }
960
961 CService MaybeFlipIPv6toCJDNS(const CService& service)
962 {
963 CService ret{service};
964 if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) {
965 ret.m_net = NET_CJDNS;
966 }
967 return ret;
968 }
969
970 CService GetBindAddress(const Sock& sock)
971 {
972 CService addr_bind;
973 sockaddr_storage storage;
974 socklen_t len = sizeof(storage);
975
976 auto sa = reinterpret_cast<sockaddr*>(&storage);
977
978 if (sock.GetSockName(sa, &len) == 0) {
979 addr_bind.SetSockAddr(sa, len);
980 } else {
981 LogWarning("getsockname failed\n");
982 }
983 return addr_bind;
984 }
985