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