Bitcoin ABC 0.32.4
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.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 bool LookupIntern(const std::string &name, std::vector<CNetAddr> &vIP,
152 unsigned int nMaxSolutions, bool fAllowLookup,
153 DNSLookupFn dns_lookup_function) {
154 vIP.clear();
155
156 if (!ContainsNoNUL(name)) {
157 return false;
158 }
159
160 {
161 CNetAddr addr;
162 // From our perspective, onion addresses are not hostnames but rather
163 // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
164 // or IPv6 colon-separated hextet notation. Since we can't use
165 // getaddrinfo to decode them and it wouldn't make sense to resolve
166 // them, we return a network address representing it instead. See
167 // CNetAddr::SetSpecial(const std::string&) for more details.
168 if (addr.SetSpecial(name)) {
169 vIP.push_back(addr);
170 return true;
171 }
172 }
173
174 for (const CNetAddr &resolved : dns_lookup_function(name, fAllowLookup)) {
175 if (nMaxSolutions > 0 && vIP.size() >= nMaxSolutions) {
176 break;
177 }
178
179 // Never allow resolving to an internal address. Consider any such
180 // result invalid.
181 if (!resolved.IsInternal()) {
182 vIP.push_back(resolved);
183 }
184 }
185
186 return (vIP.size() > 0);
187}
188
189bool LookupHost(const std::string &name, std::vector<CNetAddr> &vIP,
190 unsigned int nMaxSolutions, bool fAllowLookup,
191 DNSLookupFn dns_lookup_function) {
192 if (!ContainsNoNUL(name)) {
193 return false;
194 }
195 std::string strHost = name;
196 if (strHost.empty()) {
197 return false;
198 }
199 if (strHost.front() == '[' && strHost.back() == ']') {
200 strHost = strHost.substr(1, strHost.size() - 2);
201 }
202
203 return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup,
204 dns_lookup_function);
205}
206
207bool LookupHost(const std::string &name, CNetAddr &addr, bool fAllowLookup,
208 DNSLookupFn dns_lookup_function) {
209 if (!ContainsNoNUL(name)) {
210 return false;
211 }
212 std::vector<CNetAddr> vIP;
213 LookupHost(name, vIP, 1, fAllowLookup, dns_lookup_function);
214 if (vIP.empty()) {
215 return false;
216 }
217 addr = vIP.front();
218 return true;
219}
220
221bool Lookup(const std::string &name, std::vector<CService> &vAddr,
222 uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions,
223 DNSLookupFn dns_lookup_function) {
224 if (name.empty() || !ContainsNoNUL(name)) {
225 return false;
226 }
227 uint16_t port{portDefault};
228 std::string hostname;
229 SplitHostPort(name, port, hostname);
230
231 std::vector<CNetAddr> vIP;
232 bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup,
233 dns_lookup_function);
234 if (!fRet) {
235 return false;
236 }
237 vAddr.resize(vIP.size());
238 for (unsigned int i = 0; i < vIP.size(); i++) {
239 vAddr[i] = CService(vIP[i], port);
240 }
241 return true;
242}
243
244bool Lookup(const std::string &name, CService &addr, uint16_t portDefault,
245 bool fAllowLookup, DNSLookupFn dns_lookup_function) {
246 if (!ContainsNoNUL(name)) {
247 return false;
248 }
249 std::vector<CService> vService;
250 bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1,
251 dns_lookup_function);
252 if (!fRet) {
253 return false;
254 }
255 addr = vService[0];
256 return true;
257}
258
259CService LookupNumeric(const std::string &name, uint16_t portDefault,
260 DNSLookupFn dns_lookup_function) {
261 if (!ContainsNoNUL(name)) {
262 return {};
263 }
264 CService addr;
265 // "1.2:345" will fail to resolve the ip, but will still set the port.
266 // If the ip fails to resolve, re-init the result.
267 if (!Lookup(name, addr, portDefault, false, dns_lookup_function)) {
268 addr = CService();
269 }
270 return addr;
271}
272
274enum SOCKSVersion : uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 };
275
277enum SOCKS5Method : uint8_t {
278 NOAUTH = 0x00,
279 GSSAPI = 0x01,
280 USER_PASS = 0x02,
282};
283
285enum SOCKS5Command : uint8_t {
286 CONNECT = 0x01,
287 BIND = 0x02,
288 UDP_ASSOCIATE = 0x03
290
292enum SOCKS5Reply : uint8_t {
293 SUCCEEDED = 0x00,
294 GENFAILURE = 0x01,
295 NOTALLOWED = 0x02,
298 CONNREFUSED = 0x05,
299 TTLEXPIRED = 0x06,
302};
303
305enum SOCKS5Atyp : uint8_t {
306 IPV4 = 0x01,
308 IPV6 = 0x04,
309};
310
312enum class IntrRecvError {
313 OK,
314 Timeout,
318};
319
338static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len,
339 std::chrono::milliseconds timeout,
340 const Sock &sock) {
341 auto curTime{Now<SteadyMilliseconds>()};
342 const auto endTime{curTime + timeout};
343 while (len > 0 && curTime < endTime) {
344 // Optimistically try the recv first
345 ssize_t ret = sock.Recv(data, len, 0);
346 if (ret > 0) {
347 len -= ret;
348 data += ret;
349 } else if (ret == 0) {
350 // Unexpected disconnection
352 } else {
353 // Other error or blocking
354 int nErr = WSAGetLastError();
355 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
356 nErr == WSAEINVAL) {
357 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
358 // we're approaching the end of the specified total timeout
359 const auto remaining =
360 std::chrono::milliseconds{endTime - curTime};
361 const auto timeout_ = std::min(
362 remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
363 if (!sock.Wait(timeout_, Sock::RECV)) {
365 }
366 } else {
368 }
369 }
372 }
373 curTime = Now<SteadyMilliseconds>();
374 }
375 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
376}
377
379static std::string Socks5ErrorString(uint8_t err) {
380 switch (err) {
382 return "general failure";
384 return "connection not allowed";
386 return "network unreachable";
388 return "host unreachable";
390 return "connection refused";
392 return "TTL expired";
394 return "protocol error";
396 return "address type not supported";
397 default:
398 return "unknown";
399 }
400}
401
420bool Socks5(const std::string &strDest, uint16_t port,
421 const ProxyCredentials *auth, const Sock &sock) {
422 IntrRecvError recvr;
423 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
424 if (strDest.size() > 255) {
425 LogError("Hostname too long\n");
426 return false;
427 }
428 // Construct the version identifier/method selection message
429 std::vector<uint8_t> vSocks5Init;
430 // We want the SOCK5 protocol
431 vSocks5Init.push_back(SOCKSVersion::SOCKS5);
432 if (auth) {
433 // 2 method identifiers follow...
434 vSocks5Init.push_back(0x02);
435 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
436 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
437 } else {
438 // 1 method identifier follows...
439 vSocks5Init.push_back(0x01);
440 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
441 }
442 ssize_t ret =
443 sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
444 if (ret != (ssize_t)vSocks5Init.size()) {
445 LogError("Error sending to proxy\n");
446 return false;
447 }
448 uint8_t pchRet1[2];
449 if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) !=
451 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() "
452 "timeout or other failure\n",
453 strDest, port);
454 return false;
455 }
456 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
457 LogError("Proxy failed to initialize\n");
458 return false;
459 }
460 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
461 // Perform username/password authentication (as described in RFC1929)
462 std::vector<uint8_t> vAuth;
463 // Current (and only) version of user/pass subnegotiation
464 vAuth.push_back(0x01);
465 if (auth->username.size() > 255 || auth->password.size() > 255) {
466 LogError("Proxy username or password too long\n");
467 return false;
468 }
469 vAuth.push_back(auth->username.size());
470 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
471 vAuth.push_back(auth->password.size());
472 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
473 ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
474 if (ret != (ssize_t)vAuth.size()) {
475 LogError("Error sending authentication to proxy\n");
476 return false;
477 }
478 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n",
479 auth->username, auth->password);
480 uint8_t pchRetA[2];
481 if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) !=
483 LogError("Error reading proxy authentication response\n");
484 return false;
485 }
486 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
487 LogError("Proxy authentication unsuccessful\n");
488 return false;
489 }
490 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
491 // Perform no authentication
492 } else {
493 LogError("Proxy requested wrong authentication method %02x\n",
494 pchRet1[1]);
495 return false;
496 }
497 std::vector<uint8_t> vSocks5;
498 // VER protocol version
499 vSocks5.push_back(SOCKSVersion::SOCKS5);
500 // CMD CONNECT
501 vSocks5.push_back(SOCKS5Command::CONNECT);
502 // RSV Reserved must be 0
503 vSocks5.push_back(0x00);
504 // ATYP DOMAINNAME
505 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME);
506 // Length<=255 is checked at beginning of function
507 vSocks5.push_back(strDest.size());
508 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
509 vSocks5.push_back((port >> 8) & 0xFF);
510 vSocks5.push_back((port >> 0) & 0xFF);
511 ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
512 if (ret != (ssize_t)vSocks5.size()) {
513 LogError("Error sending to proxy\n");
514 return false;
515 }
516 uint8_t pchRet2[4];
517 if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) !=
519 if (recvr == IntrRecvError::Timeout) {
525 return false;
526 } else {
527 LogError("Error while reading proxy response\n");
528 return false;
529 }
530 }
531 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
532 LogError("Proxy failed to accept request\n");
533 return false;
534 }
535 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
536 // Failures to connect to a peer that are not proxy errors
537 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port,
538 Socks5ErrorString(pchRet2[1]));
539 return false;
540 }
541 // Reserved field must be 0
542 if (pchRet2[2] != 0x00) {
543 LogError("Error: malformed proxy response\n");
544 return false;
545 }
546 uint8_t pchRet3[256];
547 switch (pchRet2[3]) {
548 case SOCKS5Atyp::IPV4:
549 recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock);
550 break;
551 case SOCKS5Atyp::IPV6:
552 recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock);
553 break;
555 recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
556 if (recvr != IntrRecvError::OK) {
557 LogError("Error reading from proxy\n");
558 return false;
559 }
560 int nRecv = pchRet3[0];
561 recvr =
562 InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
563 break;
564 }
565 default:
566 LogError("Error: malformed proxy response\n");
567 return false;
568 }
569 if (recvr != IntrRecvError::OK) {
570 LogError("Error reading from proxy\n");
571 return false;
572 }
573 if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) !=
575 LogError("Error reading from proxy\n");
576 return false;
577 }
578 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
579 return true;
580}
581
582std::unique_ptr<Sock> CreateSockTCP(const CService &address_family) {
583 // Create a sockaddr from the specified service.
584 struct sockaddr_storage sockaddr;
585 socklen_t len = sizeof(sockaddr);
586 if (!address_family.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
587 LogPrintf("Cannot create socket for %s: unsupported network\n",
588 address_family.ToString());
589 return nullptr;
590 }
591
592 // Create a TCP socket in the address family of the specified service.
593 SOCKET hSocket = socket(((struct sockaddr *)&sockaddr)->sa_family,
594 SOCK_STREAM, IPPROTO_TCP);
595 if (hSocket == INVALID_SOCKET) {
596 return nullptr;
597 }
598
599 // Ensure that waiting for I/O on this socket won't result in undefined
600 // behavior.
601 if (!IsSelectableSocket(hSocket)) {
602 CloseSocket(hSocket);
603 LogPrintf("Cannot create connection: non-selectable socket created (fd "
604 ">= FD_SETSIZE ?)\n");
605 return nullptr;
606 }
607
608#ifdef SO_NOSIGPIPE
609 int set = 1;
610 // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
611 // should use the MSG_NOSIGNAL flag for every send.
612 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (sockopt_arg_type)&set,
613 sizeof(int));
614#endif
615
616 // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
617 SetSocketNoDelay(hSocket);
618
619 // Set the non-blocking option on the socket.
620 if (!SetSocketNonBlocking(hSocket, true)) {
621 CloseSocket(hSocket);
622 LogPrintf("CreateSocket: Setting socket to non-blocking "
623 "failed, error %s\n",
625 return nullptr;
626 }
627 return std::make_unique<Sock>(hSocket);
628}
629
630std::function<std::unique_ptr<Sock>(const CService &)> CreateSock =
632
633template <typename... Args>
634static void LogConnectFailure(bool manual_connection, const char *fmt,
635 const Args &...args) {
636 std::string error_message = tfm::format(fmt, args...);
637 if (manual_connection) {
638 LogPrintf("%s\n", error_message);
639 } else {
640 LogPrint(BCLog::NET, "%s\n", error_message);
641 }
642}
643
644bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock,
645 int nTimeout, bool manual_connection) {
646 // Create a sockaddr from the specified service.
647 struct sockaddr_storage sockaddr;
648 socklen_t len = sizeof(sockaddr);
649 if (sock.Get() == INVALID_SOCKET) {
650 LogPrintf("Cannot connect to %s: invalid socket\n",
651 addrConnect.ToString());
652 return false;
653 }
654 if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
655 LogPrintf("Cannot connect to %s: unsupported network\n",
656 addrConnect.ToString());
657 return false;
658 }
659
660 // Connect to the addrConnect service on the hSocket socket.
661 if (sock.Connect(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
662 SOCKET_ERROR) {
663 int nErr = WSAGetLastError();
664 // WSAEINVAL is here because some legacy version of winsock uses it
665 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
666 nErr == WSAEINVAL) {
667 // Connection didn't actually fail, but is being established
668 // asynchronously. Thus, use async I/O api (select/poll)
669 // synchronously to check for successful connection with a timeout.
670 const Sock::Event requested = Sock::RECV | Sock::SEND;
671 Sock::Event occurred;
672 if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested,
673 &occurred)) {
674 LogPrintf("wait for connect to %s failed: %s\n",
675 addrConnect.ToString(),
677 return false;
678 } else if (occurred == 0) {
679 LogPrint(BCLog::NET, "connection attempt to %s timed out\n",
680 addrConnect.ToString());
681 return false;
682 }
683
684 // Even if the wait was successful, the connect might not
685 // have been successful. The reason for this failure is hidden away
686 // in the SO_ERROR for the socket in modern systems. We read it into
687 // sockerr here.
688 int sockerr;
689 socklen_t sockerr_len = sizeof(sockerr);
690 if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR,
691 (sockopt_arg_type)&sockerr,
692 &sockerr_len) == SOCKET_ERROR) {
693 LogPrintf("getsockopt() for %s failed: %s\n",
694 addrConnect.ToString(),
696 return false;
697 }
698 if (sockerr != 0) {
700 manual_connection, "connect() to %s failed after wait: %s",
701 addrConnect.ToString(), NetworkErrorString(sockerr));
702 return false;
703 }
704 }
705#ifdef WIN32
706 else if (WSAGetLastError() != WSAEISCONN)
707#else
708 else
709#endif
710 {
711 LogConnectFailure(manual_connection, "connect() to %s failed: %s",
712 addrConnect.ToString(),
714 return false;
715 }
716 }
717 return true;
718}
719
720bool SetProxy(enum Network net, const proxyType &addrProxy) {
721 assert(net >= 0 && net < NET_MAX);
722 if (!addrProxy.IsValid()) {
723 return false;
724 }
726 proxyInfo[net] = addrProxy;
727 return true;
728}
729
730bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
731 assert(net >= 0 && net < NET_MAX);
733 if (!proxyInfo[net].IsValid()) {
734 return false;
735 }
736 proxyInfoOut = proxyInfo[net];
737 return true;
738}
739
740bool SetNameProxy(const proxyType &addrProxy) {
741 if (!addrProxy.IsValid()) {
742 return false;
743 }
745 nameProxy = addrProxy;
746 return true;
747}
748
749bool GetNameProxy(proxyType &nameProxyOut) {
751 if (!nameProxy.IsValid()) {
752 return false;
753 }
754 nameProxyOut = nameProxy;
755 return true;
756}
757
760 return nameProxy.IsValid();
761}
762
763bool IsProxy(const CNetAddr &addr) {
765 for (int i = 0; i < NET_MAX; i++) {
766 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) {
767 return true;
768 }
769 }
770 return false;
771}
772
773bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest,
774 uint16_t port, const Sock &sock, int nTimeout,
775 bool &outProxyConnectionFailed) {
776 // first connect to proxy server
777 if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
778 outProxyConnectionFailed = true;
779 return false;
780 }
781 // do socks negotiation
782 if (proxy.randomize_credentials) {
783 ProxyCredentials random_auth;
784 static std::atomic_int counter(0);
785 random_auth.username = random_auth.password =
786 strprintf("%i", counter++);
787 if (!Socks5(strDest, port, &random_auth, sock)) {
788 return false;
789 }
790 } else if (!Socks5(strDest, port, 0, sock)) {
791 return false;
792 }
793 return true;
794}
795
796bool LookupSubNet(const std::string &strSubnet, CSubNet &ret,
797 DNSLookupFn dns_lookup_function) {
798 if (!ContainsNoNUL(strSubnet)) {
799 return false;
800 }
801 size_t slash = strSubnet.find_last_of('/');
802 std::vector<CNetAddr> vIP;
803
804 std::string strAddress = strSubnet.substr(0, slash);
805 // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just
806 if (LookupHost(strAddress, vIP, 1, false, dns_lookup_function)) {
807 CNetAddr network = vIP[0];
808 if (slash != strSubnet.npos) {
809 std::string strNetmask = strSubnet.substr(slash + 1);
810 uint8_t n;
811 if (ParseUInt8(strNetmask, &n)) {
812 // If valid number, assume CIDR variable-length subnet masking
813 ret = CSubNet(network, n);
814 return ret.IsValid();
815 } else {
816 // If not a valid number, try full netmask syntax
817 // Never allow lookup for netmask
818 if (LookupHost(strNetmask, vIP, 1, false,
819 dns_lookup_function)) {
820 ret = CSubNet(network, vIP[0]);
821 return ret.IsValid();
822 }
823 }
824 } else {
825 ret = CSubNet(network);
826 return ret.IsValid();
827 }
828 }
829 return false;
830}
831
832bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking) {
833 if (fNonBlocking) {
834#ifdef WIN32
835 u_long nOne = 1;
836 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
837#else
838 int fFlags = fcntl(hSocket, F_GETFL, 0);
839 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
840#endif
841 return false;
842 }
843 } else {
844#ifdef WIN32
845 u_long nZero = 0;
846 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
847#else
848 int fFlags = fcntl(hSocket, F_GETFL, 0);
849 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
850#endif
851 return false;
852 }
853 }
854
855 return true;
856}
857
858bool SetSocketNoDelay(const SOCKET &hSocket) {
859 int set = 1;
860 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY,
861 (sockopt_arg_type)&set, sizeof(int));
862 return rc == 0;
863}
864
865void InterruptSocks5(bool interrupt) {
866 interruptSocks5Recv = interrupt;
867}
868
869bool IsBadPort(uint16_t port) {
870 // Don't forget to update doc/p2p-bad-ports.md if you change this list.
871
872 switch (port) {
873 case 1: // tcpmux
874 case 7: // echo
875 case 9: // discard
876 case 11: // systat
877 case 13: // daytime
878 case 15: // netstat
879 case 17: // qotd
880 case 19: // chargen
881 case 20: // ftp data
882 case 21: // ftp access
883 case 22: // ssh
884 case 23: // telnet
885 case 25: // smtp
886 case 37: // time
887 case 42: // name
888 case 43: // nicname
889 case 53: // domain
890 case 69: // tftp
891 case 77: // priv-rjs
892 case 79: // finger
893 case 87: // ttylink
894 case 95: // supdup
895 case 101: // hostname
896 case 102: // iso-tsap
897 case 103: // gppitnp
898 case 104: // acr-nema
899 case 109: // pop2
900 case 110: // pop3
901 case 111: // sunrpc
902 case 113: // auth
903 case 115: // sftp
904 case 117: // uucp-path
905 case 119: // nntp
906 case 123: // NTP
907 case 135: // loc-srv /epmap
908 case 137: // netbios
909 case 139: // netbios
910 case 143: // imap2
911 case 161: // snmp
912 case 179: // BGP
913 case 389: // ldap
914 case 427: // SLP (Also used by Apple Filing Protocol)
915 case 465: // smtp+ssl
916 case 512: // print / exec
917 case 513: // login
918 case 514: // shell
919 case 515: // printer
920 case 526: // tempo
921 case 530: // courier
922 case 531: // chat
923 case 532: // netnews
924 case 540: // uucp
925 case 548: // AFP (Apple Filing Protocol)
926 case 554: // rtsp
927 case 556: // remotefs
928 case 563: // nntp+ssl
929 case 587: // smtp (rfc6409)
930 case 601: // syslog-conn (rfc3195)
931 case 636: // ldap+ssl
932 case 989: // ftps-data
933 case 990: // ftps
934 case 993: // ldap+ssl
935 case 995: // pop3+ssl
936 case 1719: // h323gatestat
937 case 1720: // h323hostcall
938 case 1723: // pptp
939 case 2049: // nfs
940 case 3659: // apple-sasl / PasswordServer
941 case 4045: // lockd
942 case 5060: // sip
943 case 5061: // sips
944 case 6000: // X11
945 case 6566: // sane-port
946 case 6665: // Alternate IRC
947 case 6666: // Alternate IRC
948 case 6667: // Standard IRC
949 case 6668: // Alternate IRC
950 case 6669: // Alternate IRC
951 case 6697: // IRC + TLS
952 case 10080: // Amanda
953 return true;
954 }
955 return false;
956}
Network address.
Definition: netaddress.h:121
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:545
std::string ToString() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
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:52
#define WSAEWOULDBLOCK
Definition: compat.h:45
#define WSAEINVAL
Definition: compat.h:43
#define SOCKET_ERROR
Definition: compat.h:53
#define WSAGetLastError()
Definition: compat.h:42
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:102
#define MSG_NOSIGNAL
Definition: compat.h:113
unsigned int SOCKET
Definition: compat.h:40
void * sockopt_arg_type
Definition: compat.h:87
#define WSAEINPROGRESS
Definition: compat.h:49
#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:44
@ NET_I2P
I2P.
Definition: netaddress.h:59
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:62
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:66
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:312
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:305
@ DOMAINNAME
Definition: netbase.cpp:307
@ IPV4
Definition: netbase.cpp:306
@ IPV6
Definition: netbase.cpp:308
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:285
@ UDP_ASSOCIATE
Definition: netbase.cpp:288
@ CONNECT
Definition: netbase.cpp:286
@ BIND
Definition: netbase.cpp:287
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:749
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:634
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:338
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:274
@ SOCKS4
Definition: netbase.cpp:274
@ SOCKS5
Definition: netbase.cpp:274
bool HaveNameProxy()
Definition: netbase.cpp:758
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:730
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:796
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:151
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:858
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:773
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:90
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:277
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:279
@ NOAUTH
No authentication required.
Definition: netbase.cpp:278
@ USER_PASS
Username/password.
Definition: netbase.cpp:280
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:281
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:420
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:379
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:865
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:582
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:630
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:644
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:292
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:299
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:300
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:296
@ GENFAILURE
General failure.
Definition: netbase.cpp:294
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:298
@ SUCCEEDED
Succeeded.
Definition: netbase.cpp:293
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:301
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:295
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:297
static GlobalMutex g_proxyinfo_mutex
Definition: netbase.cpp:34
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:221
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:740
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:832
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:259
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:763
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:869
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 LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:189
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:720
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:47
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:398
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:405
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())