Bitcoin ABC 0.32.11
P2P Digital Currency
netbase.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2016 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 <netbase.h>
7
8#include <compat/compat.h>
9#include <logging.h>
10#include <sync.h>
11#include <tinyformat.h>
12#include <util/sock.h>
13#include <util/strencodings.h>
14#include <util/string.h>
15#include <util/time.h>
16
17#include <atomic>
18#include <chrono>
19#include <cstdint>
20#include <functional>
21#include <memory>
22
23#ifndef WIN32
24#include <fcntl.h>
25#else
26#include <codecvt>
27#endif
28
29#ifdef USE_POLL
30#include <poll.h>
31#endif
32
33// Settings
36static proxyType nameProxy GUARDED_BY(g_proxyinfo_mutex);
39
40// Need ample time for negotiation for very slow proxies such as Tor
41std::chrono::milliseconds g_socks5_recv_timeout = 20s;
42static std::atomic<bool> interruptSocks5Recv(false);
43
44std::vector<CNetAddr> WrappedGetAddrInfo(const std::string &name,
45 bool allow_lookup) {
46 addrinfo ai_hint{};
47 // We want a TCP port, which is a streaming socket type
48 ai_hint.ai_socktype = SOCK_STREAM;
49 ai_hint.ai_protocol = IPPROTO_TCP;
50 // We don't care which address family (IPv4 or IPv6) is returned
51 ai_hint.ai_family = AF_UNSPEC;
52 // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
53 // return addresses whose family we have an address configured for.
54 //
55 // If we don't allow lookups, then use the AI_NUMERICHOST flag for
56 // getaddrinfo to only decode numerical network addresses and suppress
57 // hostname lookups.
58 ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
59
60 addrinfo *ai_res{nullptr};
61 const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
62 if (n_err != 0) {
63 return {};
64 }
65
66 // Traverse the linked list starting with ai_trav.
67 addrinfo *ai_trav{ai_res};
68 std::vector<CNetAddr> resolved_addresses;
69 while (ai_trav != nullptr) {
70 if (ai_trav->ai_family == AF_INET) {
71 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
72 resolved_addresses.emplace_back(
73 reinterpret_cast<sockaddr_in *>(ai_trav->ai_addr)->sin_addr);
74 }
75 if (ai_trav->ai_family == AF_INET6) {
76 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
77 const sockaddr_in6 *s6{
78 reinterpret_cast<sockaddr_in6 *>(ai_trav->ai_addr)};
79 resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
80 }
81 ai_trav = ai_trav->ai_next;
82 }
83 freeaddrinfo(ai_res);
84
85 return resolved_addresses;
86}
87
89
90enum Network ParseNetwork(const std::string &net_in) {
91 std::string net = ToLower(net_in);
92 if (net == "ipv4") {
93 return NET_IPV4;
94 }
95 if (net == "ipv6") {
96 return NET_IPV6;
97 }
98 if (net == "onion") {
99 return NET_ONION;
100 }
101 if (net == "tor") {
102 LogPrintf("Warning: net name 'tor' is deprecated and will be removed "
103 "in the future. You should use 'onion' instead.\n");
104 return NET_ONION;
105 }
106 if (net == "i2p") {
107 return NET_I2P;
108 }
109 return NET_UNROUTABLE;
110}
111
112std::string GetNetworkName(enum Network net) {
113 switch (net) {
114 case NET_UNROUTABLE:
115 return "not_publicly_routable";
116 case NET_IPV4:
117 return "ipv4";
118 case NET_IPV6:
119 return "ipv6";
120 case NET_ONION:
121 return "onion";
122 case NET_I2P:
123 return "i2p";
124 case NET_CJDNS:
125 return "cjdns";
126 case NET_INTERNAL:
127 return "internal";
128 case NET_MAX:
129 assert(false);
130 } // no default case, so the compiler can warn about missing cases
131
132 assert(false);
133}
134
135std::vector<std::string> GetNetworkNames(bool append_unroutable) {
136 std::vector<std::string> names;
137 for (int n = 0; n < NET_MAX; ++n) {
138 const enum Network network { static_cast<Network>(n) };
139 if (network == NET_UNROUTABLE || network == NET_CJDNS ||
140 network == NET_INTERNAL) {
141 continue;
142 }
143 names.emplace_back(GetNetworkName(network));
144 }
145 if (append_unroutable) {
146 names.emplace_back(GetNetworkName(NET_UNROUTABLE));
147 }
148 return names;
149}
150
151static std::vector<CNetAddr> LookupIntern(const std::string &name,
152 unsigned int nMaxSolutions,
153 bool fAllowLookup,
154 DNSLookupFn dns_lookup_function) {
155 if (!ContainsNoNUL(name)) {
156 return {};
157 }
158 {
159 CNetAddr addr;
160 // From our perspective, onion addresses are not hostnames but rather
161 // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
162 // or IPv6 colon-separated hextet notation. Since we can't use
163 // getaddrinfo to decode them and it wouldn't make sense to resolve
164 // them, we return a network address representing it instead. See
165 // CNetAddr::SetSpecial(const std::string&) for more details.
166 if (addr.SetSpecial(name)) {
167 return {addr};
168 }
169 }
170
171 std::vector<CNetAddr> addresses;
172
173 for (const CNetAddr &resolved : dns_lookup_function(name, fAllowLookup)) {
174 if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) {
175 break;
176 }
177
178 // Never allow resolving to an internal address. Consider any such
179 // result invalid.
180 if (!resolved.IsInternal()) {
181 addresses.push_back(resolved);
182 }
183 }
184
185 return addresses;
186}
187
188std::vector<CNetAddr> LookupHost(const std::string &name,
189 unsigned int nMaxSolutions, bool fAllowLookup,
190 DNSLookupFn dns_lookup_function) {
191 if (!ContainsNoNUL(name)) {
192 return {};
193 }
194 std::string strHost = name;
195 if (strHost.empty()) {
196 return {};
197 }
198 if (strHost.front() == '[' && strHost.back() == ']') {
199 strHost = strHost.substr(1, strHost.size() - 2);
200 }
201
202 return LookupIntern(strHost, nMaxSolutions, fAllowLookup,
203 dns_lookup_function);
204}
205
206std::optional<CNetAddr> LookupHost(const std::string &name, bool fAllowLookup,
207 DNSLookupFn dns_lookup_function) {
208 const std::vector<CNetAddr> addresses{
209 LookupHost(name, 1, fAllowLookup, dns_lookup_function)};
210 return addresses.empty() ? std::nullopt
211 : std::make_optional(addresses.front());
212}
213
214std::vector<CService> Lookup(const std::string &name, uint16_t portDefault,
215 bool fAllowLookup, unsigned int nMaxSolutions,
216 DNSLookupFn dns_lookup_function) {
217 if (name.empty() || !ContainsNoNUL(name)) {
218 return {};
219 }
220 uint16_t port{portDefault};
221 std::string hostname;
222 SplitHostPort(name, port, hostname);
223
224 const std::vector<CNetAddr> addresses{LookupIntern(
225 hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)};
226 if (addresses.empty()) {
227 return {};
228 }
229 std::vector<CService> services;
230 services.reserve(addresses.size());
231 for (const auto &addr : addresses) {
232 services.emplace_back(addr, port);
233 }
234 return services;
235}
236
237std::optional<CService> Lookup(const std::string &name, uint16_t portDefault,
238 bool fAllowLookup,
239 DNSLookupFn dns_lookup_function) {
240 const std::vector<CService> services{
241 Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)};
242
243 return services.empty() ? std::nullopt
244 : std::make_optional(services.front());
245}
246
247CService LookupNumeric(const std::string &name, uint16_t portDefault,
248 DNSLookupFn dns_lookup_function) {
249 if (!ContainsNoNUL(name)) {
250 return {};
251 }
252 // "1.2:345" will fail to resolve the ip, but will still set the port.
253 // If the ip fails to resolve, re-init the result.
254 return Lookup(name, portDefault, /*fAllowLookup=*/false,
255 dns_lookup_function)
256 .value_or(CService{});
257}
258
260enum SOCKSVersion : uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 };
261
263enum SOCKS5Method : uint8_t {
264 NOAUTH = 0x00,
265 GSSAPI = 0x01,
266 USER_PASS = 0x02,
268};
269
271enum SOCKS5Command : uint8_t {
272 CONNECT = 0x01,
273 BIND = 0x02,
274 UDP_ASSOCIATE = 0x03
276
278enum SOCKS5Reply : uint8_t {
279 SUCCEEDED = 0x00,
280 GENFAILURE = 0x01,
281 NOTALLOWED = 0x02,
284 CONNREFUSED = 0x05,
285 TTLEXPIRED = 0x06,
288};
289
291enum SOCKS5Atyp : uint8_t {
292 IPV4 = 0x01,
294 IPV6 = 0x04,
295};
296
298enum class IntrRecvError {
299 OK,
300 Timeout,
304};
305
324static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len,
325 std::chrono::milliseconds timeout,
326 const Sock &sock) {
327 auto curTime{Now<SteadyMilliseconds>()};
328 const auto endTime{curTime + timeout};
329 while (len > 0 && curTime < endTime) {
330 // Optimistically try the recv first
331 ssize_t ret = sock.Recv(data, len, 0);
332 if (ret > 0) {
333 len -= ret;
334 data += ret;
335 } else if (ret == 0) {
336 // Unexpected disconnection
338 } else {
339 // Other error or blocking
340 int nErr = WSAGetLastError();
341 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
342 nErr == WSAEINVAL) {
343 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
344 // we're approaching the end of the specified total timeout
345 const auto remaining =
346 std::chrono::milliseconds{endTime - curTime};
347 const auto timeout_ = std::min(
348 remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
349 if (!sock.Wait(timeout_, Sock::RECV)) {
351 }
352 } else {
354 }
355 }
358 }
359 curTime = Now<SteadyMilliseconds>();
360 }
361 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
362}
363
365static std::string Socks5ErrorString(uint8_t err) {
366 switch (err) {
368 return "general failure";
370 return "connection not allowed";
372 return "network unreachable";
374 return "host unreachable";
376 return "connection refused";
378 return "TTL expired";
380 return "protocol error";
382 return "address type not supported";
383 default:
384 return "unknown";
385 }
386}
387
406bool Socks5(const std::string &strDest, uint16_t port,
407 const ProxyCredentials *auth, const Sock &sock) {
408 IntrRecvError recvr;
409 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
410 if (strDest.size() > 255) {
411 LogError("Hostname too long\n");
412 return false;
413 }
414 // Construct the version identifier/method selection message
415 std::vector<uint8_t> vSocks5Init;
416 // We want the SOCK5 protocol
417 vSocks5Init.push_back(SOCKSVersion::SOCKS5);
418 if (auth) {
419 // 2 method identifiers follow...
420 vSocks5Init.push_back(0x02);
421 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
422 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
423 } else {
424 // 1 method identifier follows...
425 vSocks5Init.push_back(0x01);
426 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
427 }
428 ssize_t ret =
429 sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
430 if (ret != (ssize_t)vSocks5Init.size()) {
431 LogError("Error sending to proxy\n");
432 return false;
433 }
434 uint8_t pchRet1[2];
435 if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) !=
437 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() "
438 "timeout or other failure\n",
439 strDest, port);
440 return false;
441 }
442 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
443 LogError("Proxy failed to initialize\n");
444 return false;
445 }
446 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
447 // Perform username/password authentication (as described in RFC1929)
448 std::vector<uint8_t> vAuth;
449 // Current (and only) version of user/pass subnegotiation
450 vAuth.push_back(0x01);
451 if (auth->username.size() > 255 || auth->password.size() > 255) {
452 LogError("Proxy username or password too long\n");
453 return false;
454 }
455 vAuth.push_back(auth->username.size());
456 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
457 vAuth.push_back(auth->password.size());
458 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
459 ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
460 if (ret != (ssize_t)vAuth.size()) {
461 LogError("Error sending authentication to proxy\n");
462 return false;
463 }
464 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n",
465 auth->username, auth->password);
466 uint8_t pchRetA[2];
467 if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) !=
469 LogError("Error reading proxy authentication response\n");
470 return false;
471 }
472 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
473 LogError("Proxy authentication unsuccessful\n");
474 return false;
475 }
476 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
477 // Perform no authentication
478 } else {
479 LogError("Proxy requested wrong authentication method %02x\n",
480 pchRet1[1]);
481 return false;
482 }
483 std::vector<uint8_t> vSocks5;
484 // VER protocol version
485 vSocks5.push_back(SOCKSVersion::SOCKS5);
486 // CMD CONNECT
487 vSocks5.push_back(SOCKS5Command::CONNECT);
488 // RSV Reserved must be 0
489 vSocks5.push_back(0x00);
490 // ATYP DOMAINNAME
491 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME);
492 // Length<=255 is checked at beginning of function
493 vSocks5.push_back(strDest.size());
494 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
495 vSocks5.push_back((port >> 8) & 0xFF);
496 vSocks5.push_back((port >> 0) & 0xFF);
497 ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
498 if (ret != (ssize_t)vSocks5.size()) {
499 LogError("Error sending to proxy\n");
500 return false;
501 }
502 uint8_t pchRet2[4];
503 if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) !=
505 if (recvr == IntrRecvError::Timeout) {
511 return false;
512 } else {
513 LogError("Error while reading proxy response\n");
514 return false;
515 }
516 }
517 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
518 LogError("Proxy failed to accept request\n");
519 return false;
520 }
521 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
522 // Failures to connect to a peer that are not proxy errors
523 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port,
524 Socks5ErrorString(pchRet2[1]));
525 return false;
526 }
527 // Reserved field must be 0
528 if (pchRet2[2] != 0x00) {
529 LogError("Error: malformed proxy response\n");
530 return false;
531 }
532 uint8_t pchRet3[256];
533 switch (pchRet2[3]) {
534 case SOCKS5Atyp::IPV4:
535 recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock);
536 break;
537 case SOCKS5Atyp::IPV6:
538 recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock);
539 break;
541 recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
542 if (recvr != IntrRecvError::OK) {
543 LogError("Error reading from proxy\n");
544 return false;
545 }
546 int nRecv = pchRet3[0];
547 recvr =
548 InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
549 break;
550 }
551 default:
552 LogError("Error: malformed proxy response\n");
553 return false;
554 }
555 if (recvr != IntrRecvError::OK) {
556 LogError("Error reading from proxy\n");
557 return false;
558 }
559 if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) !=
561 LogError("Error reading from proxy\n");
562 return false;
563 }
564 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
565 return true;
566}
567
568std::unique_ptr<Sock> CreateSockTCP(const CService &address_family) {
569 // Create a sockaddr from the specified service.
570 struct sockaddr_storage sockaddr;
571 socklen_t len = sizeof(sockaddr);
572 if (!address_family.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
573 LogPrintf("Cannot create socket for %s: unsupported network\n",
574 address_family.ToStringAddrPort());
575 return nullptr;
576 }
577
578 // Create a TCP socket in the address family of the specified service.
579 SOCKET hSocket = socket(((struct sockaddr *)&sockaddr)->sa_family,
580 SOCK_STREAM, IPPROTO_TCP);
581 if (hSocket == INVALID_SOCKET) {
582 return nullptr;
583 }
584
585 // Ensure that waiting for I/O on this socket won't result in undefined
586 // behavior.
587 if (!IsSelectableSocket(hSocket)) {
588 CloseSocket(hSocket);
589 LogPrintf("Cannot create connection: non-selectable socket created (fd "
590 ">= FD_SETSIZE ?)\n");
591 return nullptr;
592 }
593
594#ifdef SO_NOSIGPIPE
595 int set = 1;
596 // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
597 // should use the MSG_NOSIGNAL flag for every send.
598 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (sockopt_arg_type)&set,
599 sizeof(int));
600#endif
601
602 // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
603 SetSocketNoDelay(hSocket);
604
605 // Set the non-blocking option on the socket.
606 if (!SetSocketNonBlocking(hSocket, true)) {
607 CloseSocket(hSocket);
608 LogPrintf("CreateSocket: Setting socket to non-blocking "
609 "failed, error %s\n",
611 return nullptr;
612 }
613 return std::make_unique<Sock>(hSocket);
614}
615
616std::function<std::unique_ptr<Sock>(const CService &)> CreateSock =
618
619template <typename... Args>
620static void LogConnectFailure(bool manual_connection, const char *fmt,
621 const Args &...args) {
622 std::string error_message = tfm::format(fmt, args...);
623 if (manual_connection) {
624 LogPrintf("%s\n", error_message);
625 } else {
626 LogPrint(BCLog::NET, "%s\n", error_message);
627 }
628}
629
630bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock,
631 int nTimeout, bool manual_connection) {
632 // Create a sockaddr from the specified service.
633 struct sockaddr_storage sockaddr;
634 socklen_t len = sizeof(sockaddr);
635 if (sock.Get() == INVALID_SOCKET) {
636 LogPrintf("Cannot connect to %s: invalid socket\n",
637 addrConnect.ToStringAddrPort());
638 return false;
639 }
640 if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
641 LogPrintf("Cannot connect to %s: unsupported network\n",
642 addrConnect.ToStringAddrPort());
643 return false;
644 }
645
646 // Connect to the addrConnect service on the hSocket socket.
647 if (sock.Connect(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
648 SOCKET_ERROR) {
649 int nErr = WSAGetLastError();
650 // WSAEINVAL is here because some legacy version of winsock uses it
651 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
652 nErr == WSAEINVAL) {
653 // Connection didn't actually fail, but is being established
654 // asynchronously. Thus, use async I/O api (select/poll)
655 // synchronously to check for successful connection with a timeout.
656 const Sock::Event requested = Sock::RECV | Sock::SEND;
657 Sock::Event occurred;
658 if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested,
659 &occurred)) {
660 LogPrintf("wait for connect to %s failed: %s\n",
661 addrConnect.ToStringAddrPort(),
663 return false;
664 } else if (occurred == 0) {
665 LogPrint(BCLog::NET, "connection attempt to %s timed out\n",
666 addrConnect.ToStringAddrPort());
667 return false;
668 }
669
670 // Even if the wait was successful, the connect might not
671 // have been successful. The reason for this failure is hidden away
672 // in the SO_ERROR for the socket in modern systems. We read it into
673 // sockerr here.
674 int sockerr;
675 socklen_t sockerr_len = sizeof(sockerr);
676 if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR,
677 (sockopt_arg_type)&sockerr,
678 &sockerr_len) == SOCKET_ERROR) {
679 LogPrintf("getsockopt() for %s failed: %s\n",
680 addrConnect.ToStringAddrPort(),
682 return false;
683 }
684 if (sockerr != 0) {
685 LogConnectFailure(manual_connection,
686 "connect() to %s failed after wait: %s",
687 addrConnect.ToStringAddrPort(),
688 NetworkErrorString(sockerr));
689 return false;
690 }
691 }
692#ifdef WIN32
693 else if (WSAGetLastError() != WSAEISCONN)
694#else
695 else
696#endif
697 {
698 LogConnectFailure(manual_connection, "connect() to %s failed: %s",
699 addrConnect.ToStringAddrPort(),
701 return false;
702 }
703 }
704 return true;
705}
706
707bool SetProxy(enum Network net, const proxyType &addrProxy) {
708 assert(net >= 0 && net < NET_MAX);
709 if (!addrProxy.IsValid()) {
710 return false;
711 }
713 proxyInfo[net] = addrProxy;
714 return true;
715}
716
717bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
718 assert(net >= 0 && net < NET_MAX);
720 if (!proxyInfo[net].IsValid()) {
721 return false;
722 }
723 proxyInfoOut = proxyInfo[net];
724 return true;
725}
726
727bool SetNameProxy(const proxyType &addrProxy) {
728 if (!addrProxy.IsValid()) {
729 return false;
730 }
732 nameProxy = addrProxy;
733 return true;
734}
735
736bool GetNameProxy(proxyType &nameProxyOut) {
738 if (!nameProxy.IsValid()) {
739 return false;
740 }
741 nameProxyOut = nameProxy;
742 return true;
743}
744
747 return nameProxy.IsValid();
748}
749
750bool IsProxy(const CNetAddr &addr) {
752 for (int i = 0; i < NET_MAX; i++) {
753 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) {
754 return true;
755 }
756 }
757 return false;
758}
759
760bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest,
761 uint16_t port, const Sock &sock, int nTimeout,
762 bool &outProxyConnectionFailed) {
763 // first connect to proxy server
764 if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
765 outProxyConnectionFailed = true;
766 return false;
767 }
768 // do socks negotiation
769 if (proxy.randomize_credentials) {
770 ProxyCredentials random_auth;
771 static std::atomic_int counter(0);
772 random_auth.username = random_auth.password =
773 strprintf("%i", counter++);
774 if (!Socks5(strDest, port, &random_auth, sock)) {
775 return false;
776 }
777 } else if (!Socks5(strDest, port, 0, sock)) {
778 return false;
779 }
780 return true;
781}
782
783bool LookupSubNet(const std::string &strSubnet, CSubNet &ret,
784 DNSLookupFn dns_lookup_function) {
785 if (!ContainsNoNUL(strSubnet)) {
786 return false;
787 }
788 size_t slash = strSubnet.find_last_of('/');
789 std::string strAddress = strSubnet.substr(0, slash);
790 const std::optional<CNetAddr> network{
791 LookupHost(strAddress, /*fAllowLookup=*/false)};
792
793 if (network.has_value()) {
794 if (slash != strSubnet.npos) {
795 std::string strNetmask = strSubnet.substr(slash + 1);
796 uint8_t n;
797 if (ParseUInt8(strNetmask, &n)) {
798 // If valid number, assume CIDR variable-length subnet masking
799 ret = CSubNet(network.value(), n);
800 return ret.IsValid();
801 } else {
802 // If not a valid number, try full netmask syntax
803 const std::optional<CNetAddr> netmask{LookupHost(
804 strNetmask, /*fAllowLookup=*/false, dns_lookup_function)};
805 // Never allow lookup for netmask
806 if (netmask.has_value()) {
807 ret = CSubNet(network.value(), netmask.value());
808 return ret.IsValid();
809 }
810 }
811 // Single IP subnet (<ipv4>/32 or <ipv6>/128)
812 } else {
813 ret = CSubNet(network.value());
814 return ret.IsValid();
815 }
816 }
817 return false;
818}
819
820bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking) {
821 if (fNonBlocking) {
822#ifdef WIN32
823 u_long nOne = 1;
824 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
825#else
826 int fFlags = fcntl(hSocket, F_GETFL, 0);
827 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
828#endif
829 return false;
830 }
831 } else {
832#ifdef WIN32
833 u_long nZero = 0;
834 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
835#else
836 int fFlags = fcntl(hSocket, F_GETFL, 0);
837 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
838#endif
839 return false;
840 }
841 }
842
843 return true;
844}
845
846bool SetSocketNoDelay(const SOCKET &hSocket) {
847 int set = 1;
848 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY,
849 (sockopt_arg_type)&set, sizeof(int));
850 return rc == 0;
851}
852
853void InterruptSocks5(bool interrupt) {
854 interruptSocks5Recv = interrupt;
855}
856
857bool IsBadPort(uint16_t port) {
858 // Don't forget to update doc/p2p-bad-ports.md if you change this list.
859
860 switch (port) {
861 case 1: // tcpmux
862 case 7: // echo
863 case 9: // discard
864 case 11: // systat
865 case 13: // daytime
866 case 15: // netstat
867 case 17: // qotd
868 case 19: // chargen
869 case 20: // ftp data
870 case 21: // ftp access
871 case 22: // ssh
872 case 23: // telnet
873 case 25: // smtp
874 case 37: // time
875 case 42: // name
876 case 43: // nicname
877 case 53: // domain
878 case 69: // tftp
879 case 77: // priv-rjs
880 case 79: // finger
881 case 87: // ttylink
882 case 95: // supdup
883 case 101: // hostname
884 case 102: // iso-tsap
885 case 103: // gppitnp
886 case 104: // acr-nema
887 case 109: // pop2
888 case 110: // pop3
889 case 111: // sunrpc
890 case 113: // auth
891 case 115: // sftp
892 case 117: // uucp-path
893 case 119: // nntp
894 case 123: // NTP
895 case 135: // loc-srv /epmap
896 case 137: // netbios
897 case 139: // netbios
898 case 143: // imap2
899 case 161: // snmp
900 case 179: // BGP
901 case 389: // ldap
902 case 427: // SLP (Also used by Apple Filing Protocol)
903 case 465: // smtp+ssl
904 case 512: // print / exec
905 case 513: // login
906 case 514: // shell
907 case 515: // printer
908 case 526: // tempo
909 case 530: // courier
910 case 531: // chat
911 case 532: // netnews
912 case 540: // uucp
913 case 548: // AFP (Apple Filing Protocol)
914 case 554: // rtsp
915 case 556: // remotefs
916 case 563: // nntp+ssl
917 case 587: // smtp (rfc6409)
918 case 601: // syslog-conn (rfc3195)
919 case 636: // ldap+ssl
920 case 989: // ftps-data
921 case 990: // ftps
922 case 993: // ldap+ssl
923 case 995: // pop3+ssl
924 case 1719: // h323gatestat
925 case 1720: // h323hostcall
926 case 1723: // pptp
927 case 2049: // nfs
928 case 3659: // apple-sasl / PasswordServer
929 case 4045: // lockd
930 case 5060: // sip
931 case 5061: // sips
932 case 6000: // X11
933 case 6566: // sane-port
934 case 6665: // Alternate IRC
935 case 6666: // Alternate IRC
936 case 6667: // Standard IRC
937 case 6668: // Alternate IRC
938 case 6669: // Alternate IRC
939 case 6697: // IRC + TLS
940 case 10080: // Amanda
941 return true;
942 }
943 return false;
944}
Network address.
Definition: netaddress.h:114
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:224
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:572
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
std::string ToStringAddrPort() const
bool IsValid() const
Different type to mark Mutex at global scope.
Definition: sync.h:144
RAII helper class that manages a socket.
Definition: sock.h:28
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:65
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition: sock.h:141
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:108
uint8_t Event
Definition: sock.h:129
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:135
virtual SOCKET Get() const
Get the value of the contained socket.
Definition: sock.cpp:51
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:102
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:73
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:69
bool IsValid() const
Definition: netbase.h:58
CService proxy
Definition: netbase.h:60
bool randomize_credentials
Definition: netbase.h:61
#define INVALID_SOCKET
Definition: compat.h:57
#define WSAEWOULDBLOCK
Definition: compat.h:51
#define WSAEINVAL
Definition: compat.h:50
#define SOCKET_ERROR
Definition: compat.h:58
#define WSAGetLastError()
Definition: compat.h:49
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:111
#define MSG_NOSIGNAL
Definition: compat.h:122
unsigned int SOCKET
Definition: compat.h:47
void * sockopt_arg_type
Definition: compat.h:96
#define WSAEINPROGRESS
Definition: compat.h:55
#define LogPrint(category,...)
Definition: logging.h:452
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
@ PROXY
Definition: logging.h:84
@ NET
Definition: logging.h:69
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1112
Network
A network type.
Definition: netaddress.h:37
@ NET_I2P
I2P.
Definition: netaddress.h:52
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:55
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:62
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:49
@ NET_IPV6
IPv6.
Definition: netaddress.h:46
@ NET_IPV4
IPv4.
Definition: netaddress.h:43
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:40
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:59
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:298
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:291
@ DOMAINNAME
Definition: netbase.cpp:293
@ IPV4
Definition: netbase.cpp:292
@ IPV6
Definition: netbase.cpp:294
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:271
@ UDP_ASSOCIATE
Definition: netbase.cpp:274
@ CONNECT
Definition: netbase.cpp:272
@ BIND
Definition: netbase.cpp:273
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:736
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:188
std::chrono::milliseconds g_socks5_recv_timeout
Definition: netbase.cpp:41
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:112
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &...args)
Definition: netbase.cpp:620
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, std::chrono::milliseconds timeout, const Sock &sock)
Try to read a specified number of bytes from a socket.
Definition: netbase.cpp:324
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:260
@ SOCKS4
Definition: netbase.cpp:260
@ SOCKS5
Definition: netbase.cpp:260
bool HaveNameProxy()
Definition: netbase.cpp:745
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:717
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:783
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:846
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, uint16_t port, const Sock &sock, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
Definition: netbase.cpp:760
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:90
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:263
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:265
@ NOAUTH
No authentication required.
Definition: netbase.cpp:264
@ USER_PASS
Username/password.
Definition: netbase.cpp:266
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:267
bool Socks5(const std::string &strDest, uint16_t port, const ProxyCredentials *auth, const Sock &sock)
Connect to a specified destination service through an already connected SOCKS5 proxy.
Definition: netbase.cpp:406
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:365
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:853
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:568
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:214
static std::vector< CNetAddr > LookupIntern(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:151
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:616
bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
Definition: netbase.cpp:630
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:278
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:285
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:286
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:282
@ GENFAILURE
General failure.
Definition: netbase.cpp:280
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:284
@ SUCCEEDED
Succeeded.
Definition: netbase.cpp:279
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:287
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:281
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:283
static GlobalMutex g_proxyinfo_mutex
Definition: netbase.cpp:34
bool fNameLookup
Definition: netbase.cpp:38
static std::atomic< bool > interruptSocks5Recv(false)
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
int nConnectTimeout
Definition: netbase.cpp:37
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:727
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:820
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:247
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:750
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
Definition: netbase.cpp:857
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
Definition: netbase.cpp:44
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:88
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:707
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:135
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:30
std::function< std::vector< CNetAddr >(const std::string &, bool)> DNSLookupFn
Definition: netbase.h:109
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:28
const char * name
Definition: rest.cpp:46
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:379
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:389
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:21
bool ContainsNoNUL(std::string_view str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:98
Credentials for proxy authentication.
Definition: netbase.h:65
std::string username
Definition: netbase.h:66
std::string password
Definition: netbase.h:67
#define LOCK(cs)
Definition: sync.h:306
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bool ParseUInt8(std::string_view str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
assert(!tx.IsCoinBase())