Bitcoin Core 22.99.0
P2P Digital Currency
netbase.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 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 <sync.h>
10#include <tinyformat.h>
11#include <util/sock.h>
12#include <util/strencodings.h>
13#include <util/string.h>
14#include <util/system.h>
15#include <util/time.h>
16
17#include <atomic>
18#include <chrono>
19#include <cstdint>
20#include <functional>
21#include <limits>
22#include <memory>
23
24#ifndef WIN32
25#include <fcntl.h>
26#endif
27
28#ifdef USE_POLL
29#include <poll.h>
30#endif
31
32// Settings
35static proxyType nameProxy GUARDED_BY(g_proxyinfo_mutex);
38
39// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
40int g_socks5_recv_timeout = 20 * 1000;
41static std::atomic<bool> interruptSocks5Recv(false);
42
43std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
44{
45 addrinfo ai_hint{};
46 // We want a TCP port, which is a streaming socket type
47 ai_hint.ai_socktype = SOCK_STREAM;
48 ai_hint.ai_protocol = IPPROTO_TCP;
49 // We don't care which address family (IPv4 or IPv6) is returned
50 ai_hint.ai_family = AF_UNSPEC;
51 // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
52 // return addresses whose family we have an address configured for.
53 //
54 // If we don't allow lookups, then use the AI_NUMERICHOST flag for
55 // getaddrinfo to only decode numerical network addresses and suppress
56 // hostname lookups.
57 ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
58
59 addrinfo* ai_res{nullptr};
60 const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
61 if (n_err != 0) {
62 return {};
63 }
64
65 // Traverse the linked list starting with ai_trav.
66 addrinfo* ai_trav{ai_res};
67 std::vector<CNetAddr> resolved_addresses;
68 while (ai_trav != nullptr) {
69 if (ai_trav->ai_family == AF_INET) {
70 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
71 resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
72 }
73 if (ai_trav->ai_family == AF_INET6) {
74 assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
75 const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
76 resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
77 }
78 ai_trav = ai_trav->ai_next;
79 }
80 freeaddrinfo(ai_res);
81
82 return resolved_addresses;
83}
84
86
87enum Network ParseNetwork(const std::string& net_in) {
88 std::string net = ToLower(net_in);
89 if (net == "ipv4") return NET_IPV4;
90 if (net == "ipv6") return NET_IPV6;
91 if (net == "onion") return NET_ONION;
92 if (net == "tor") {
93 LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
94 return NET_ONION;
95 }
96 if (net == "i2p") {
97 return NET_I2P;
98 }
99 if (net == "cjdns") {
100 return NET_CJDNS;
101 }
102 return NET_UNROUTABLE;
103}
104
105std::string GetNetworkName(enum Network net)
106{
107 switch (net) {
108 case NET_UNROUTABLE: return "not_publicly_routable";
109 case NET_IPV4: return "ipv4";
110 case NET_IPV6: return "ipv6";
111 case NET_ONION: return "onion";
112 case NET_I2P: return "i2p";
113 case NET_CJDNS: return "cjdns";
114 case NET_INTERNAL: return "internal";
115 case NET_MAX: assert(false);
116 } // no default case, so the compiler can warn about missing cases
117
118 assert(false);
119}
120
121std::vector<std::string> GetNetworkNames(bool append_unroutable)
122{
123 std::vector<std::string> names;
124 for (int n = 0; n < NET_MAX; ++n) {
125 const enum Network network{static_cast<Network>(n)};
126 if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
127 names.emplace_back(GetNetworkName(network));
128 }
129 if (append_unroutable) {
130 names.emplace_back(GetNetworkName(NET_UNROUTABLE));
131 }
132 return names;
133}
134
135static bool LookupIntern(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
136{
137 vIP.clear();
138
139 if (!ValidAsCString(name)) {
140 return false;
141 }
142
143 {
144 CNetAddr addr;
145 // From our perspective, onion addresses are not hostnames but rather
146 // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
147 // or IPv6 colon-separated hextet notation. Since we can't use
148 // getaddrinfo to decode them and it wouldn't make sense to resolve
149 // them, we return a network address representing it instead. See
150 // CNetAddr::SetSpecial(const std::string&) for more details.
151 if (addr.SetSpecial(name)) {
152 vIP.push_back(addr);
153 return true;
154 }
155 }
156
157 for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
158 if (nMaxSolutions > 0 && vIP.size() >= nMaxSolutions) {
159 break;
160 }
161 /* Never allow resolving to an internal address. Consider any such result invalid */
162 if (!resolved.IsInternal()) {
163 vIP.push_back(resolved);
164 }
165 }
166
167 return (vIP.size() > 0);
168}
169
170bool LookupHost(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
171{
172 if (!ValidAsCString(name)) {
173 return false;
174 }
175 std::string strHost = name;
176 if (strHost.empty())
177 return false;
178 if (strHost.front() == '[' && strHost.back() == ']') {
179 strHost = strHost.substr(1, strHost.size() - 2);
180 }
181
182 return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
183}
184
185bool LookupHost(const std::string& name, CNetAddr& addr, bool fAllowLookup, DNSLookupFn dns_lookup_function)
186{
187 if (!ValidAsCString(name)) {
188 return false;
189 }
190 std::vector<CNetAddr> vIP;
191 LookupHost(name, vIP, 1, fAllowLookup, dns_lookup_function);
192 if(vIP.empty())
193 return false;
194 addr = vIP.front();
195 return true;
196}
197
198bool Lookup(const std::string& name, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
199{
200 if (name.empty() || !ValidAsCString(name)) {
201 return false;
202 }
203 uint16_t port{portDefault};
204 std::string hostname;
205 SplitHostPort(name, port, hostname);
206
207 std::vector<CNetAddr> vIP;
208 bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
209 if (!fRet)
210 return false;
211 vAddr.resize(vIP.size());
212 for (unsigned int i = 0; i < vIP.size(); i++)
213 vAddr[i] = CService(vIP[i], port);
214 return true;
215}
216
217bool Lookup(const std::string& name, CService& addr, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
218{
219 if (!ValidAsCString(name)) {
220 return false;
221 }
222 std::vector<CService> vService;
223 bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1, dns_lookup_function);
224 if (!fRet)
225 return false;
226 addr = vService[0];
227 return true;
228}
229
230CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
231{
232 if (!ValidAsCString(name)) {
233 return {};
234 }
235 CService addr;
236 // "1.2:345" will fail to resolve the ip, but will still set the port.
237 // If the ip fails to resolve, re-init the result.
238 if(!Lookup(name, addr, portDefault, false, dns_lookup_function))
239 addr = CService();
240 return addr;
241}
242
244enum SOCKSVersion: uint8_t {
245 SOCKS4 = 0x04,
246 SOCKS5 = 0x05
248
250enum SOCKS5Method: uint8_t {
251 NOAUTH = 0x00,
252 GSSAPI = 0x01,
253 USER_PASS = 0x02,
255};
256
258enum SOCKS5Command: uint8_t {
259 CONNECT = 0x01,
260 BIND = 0x02,
261 UDP_ASSOCIATE = 0x03
263
265enum SOCKS5Reply: uint8_t {
266 SUCCEEDED = 0x00,
267 GENFAILURE = 0x01,
268 NOTALLOWED = 0x02,
271 CONNREFUSED = 0x05,
272 TTLEXPIRED = 0x06,
275};
276
278enum SOCKS5Atyp: uint8_t {
279 IPV4 = 0x01,
281 IPV6 = 0x04,
282};
283
285enum class IntrRecvError {
286 OK,
287 Timeout,
291};
292
310static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const Sock& sock)
311{
312 int64_t curTime = GetTimeMillis();
313 int64_t endTime = curTime + timeout;
314 while (len > 0 && curTime < endTime) {
315 ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
316 if (ret > 0) {
317 len -= ret;
318 data += ret;
319 } else if (ret == 0) { // Unexpected disconnection
321 } else { // Other error or blocking
322 int nErr = WSAGetLastError();
323 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
324 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
325 // we're approaching the end of the specified total timeout
326 const auto remaining = std::chrono::milliseconds{endTime - curTime};
327 const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
328 if (!sock.Wait(timeout, Sock::RECV)) {
330 }
331 } else {
333 }
334 }
337 curTime = GetTimeMillis();
338 }
339 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
340}
341
343static std::string Socks5ErrorString(uint8_t err)
344{
345 switch(err) {
347 return "general failure";
349 return "connection not allowed";
351 return "network unreachable";
353 return "host unreachable";
355 return "connection refused";
357 return "TTL expired";
359 return "protocol error";
361 return "address type not supported";
362 default:
363 return "unknown";
364 }
365}
366
367bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
368{
369 IntrRecvError recvr;
370 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
371 if (strDest.size() > 255) {
372 return error("Hostname too long");
373 }
374 // Construct the version identifier/method selection message
375 std::vector<uint8_t> vSocks5Init;
376 vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
377 if (auth) {
378 vSocks5Init.push_back(0x02); // 2 method identifiers follow...
379 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
380 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
381 } else {
382 vSocks5Init.push_back(0x01); // 1 method identifier follows...
383 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
384 }
385 ssize_t ret = sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
386 if (ret != (ssize_t)vSocks5Init.size()) {
387 return error("Error sending to proxy");
388 }
389 uint8_t pchRet1[2];
390 if ((recvr = InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
391 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
392 return false;
393 }
394 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
395 return error("Proxy failed to initialize");
396 }
397 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
398 // Perform username/password authentication (as described in RFC1929)
399 std::vector<uint8_t> vAuth;
400 vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
401 if (auth->username.size() > 255 || auth->password.size() > 255)
402 return error("Proxy username or password too long");
403 vAuth.push_back(auth->username.size());
404 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
405 vAuth.push_back(auth->password.size());
406 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
407 ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
408 if (ret != (ssize_t)vAuth.size()) {
409 return error("Error sending authentication to proxy");
410 }
411 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
412 uint8_t pchRetA[2];
413 if ((recvr = InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
414 return error("Error reading proxy authentication response");
415 }
416 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
417 return error("Proxy authentication unsuccessful");
418 }
419 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
420 // Perform no authentication
421 } else {
422 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
423 }
424 std::vector<uint8_t> vSocks5;
425 vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
426 vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
427 vSocks5.push_back(0x00); // RSV Reserved must be 0
428 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
429 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
430 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
431 vSocks5.push_back((port >> 8) & 0xFF);
432 vSocks5.push_back((port >> 0) & 0xFF);
433 ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
434 if (ret != (ssize_t)vSocks5.size()) {
435 return error("Error sending to proxy");
436 }
437 uint8_t pchRet2[4];
438 if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
439 if (recvr == IntrRecvError::Timeout) {
440 /* If a timeout happens here, this effectively means we timed out while connecting
441 * to the remote node. This is very common for Tor, so do not print an
442 * error message. */
443 return false;
444 } else {
445 return error("Error while reading proxy response");
446 }
447 }
448 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
449 return error("Proxy failed to accept request");
450 }
451 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
452 // Failures to connect to a peer that are not proxy errors
453 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
454 return false;
455 }
456 if (pchRet2[2] != 0x00) { // Reserved field must be 0
457 return error("Error: malformed proxy response");
458 }
459 uint8_t pchRet3[256];
460 switch (pchRet2[3])
461 {
462 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
463 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
465 {
466 recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
467 if (recvr != IntrRecvError::OK) {
468 return error("Error reading from proxy");
469 }
470 int nRecv = pchRet3[0];
471 recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
472 break;
473 }
474 default: return error("Error: malformed proxy response");
475 }
476 if (recvr != IntrRecvError::OK) {
477 return error("Error reading from proxy");
478 }
479 if ((recvr = InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
480 return error("Error reading from proxy");
481 }
482 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
483 return true;
484}
485
486std::unique_ptr<Sock> CreateSockTCP(const CService& address_family)
487{
488 // Create a sockaddr from the specified service.
489 struct sockaddr_storage sockaddr;
490 socklen_t len = sizeof(sockaddr);
491 if (!address_family.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
492 LogPrintf("Cannot create socket for %s: unsupported network\n", address_family.ToString());
493 return nullptr;
494 }
495
496 // Create a TCP socket in the address family of the specified service.
497 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
498 if (hSocket == INVALID_SOCKET) {
499 return nullptr;
500 }
501
502 // Ensure that waiting for I/O on this socket won't result in undefined
503 // behavior.
504 if (!IsSelectableSocket(hSocket)) {
505 CloseSocket(hSocket);
506 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
507 return nullptr;
508 }
509
510#ifdef SO_NOSIGPIPE
511 int set = 1;
512 // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
513 // should use the MSG_NOSIGNAL flag for every send.
514 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
515#endif
516
517 // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
518 SetSocketNoDelay(hSocket);
519
520 // Set the non-blocking option on the socket.
521 if (!SetSocketNonBlocking(hSocket, true)) {
522 CloseSocket(hSocket);
523 LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
524 return nullptr;
525 }
526 return std::make_unique<Sock>(hSocket);
527}
528
529std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP;
530
531template<typename... Args>
532static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
533 std::string error_message = tfm::format(fmt, args...);
534 if (manual_connection) {
535 LogPrintf("%s\n", error_message);
536 } else {
537 LogPrint(BCLog::NET, "%s\n", error_message);
538 }
539}
540
541bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection)
542{
543 // Create a sockaddr from the specified service.
544 struct sockaddr_storage sockaddr;
545 socklen_t len = sizeof(sockaddr);
546 if (sock.Get() == INVALID_SOCKET) {
547 LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
548 return false;
549 }
550 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
551 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
552 return false;
553 }
554
555 // Connect to the addrConnect service on the hSocket socket.
556 if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
557 int nErr = WSAGetLastError();
558 // WSAEINVAL is here because some legacy version of winsock uses it
559 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
560 {
561 // Connection didn't actually fail, but is being established
562 // asynchronously. Thus, use async I/O api (select/poll)
563 // synchronously to check for successful connection with a timeout.
564 const Sock::Event requested = Sock::RECV | Sock::SEND;
565 Sock::Event occurred;
566 if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) {
567 LogPrintf("wait for connect to %s failed: %s\n",
568 addrConnect.ToString(),
570 return false;
571 } else if (occurred == 0) {
572 LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToString());
573 return false;
574 }
575
576 // Even if the wait was successful, the connect might not
577 // have been successful. The reason for this failure is hidden away
578 // in the SO_ERROR for the socket in modern systems. We read it into
579 // sockerr here.
580 int sockerr;
581 socklen_t sockerr_len = sizeof(sockerr);
582 if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
583 SOCKET_ERROR) {
584 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
585 return false;
586 }
587 if (sockerr != 0) {
588 LogConnectFailure(manual_connection,
589 "connect() to %s failed after wait: %s",
590 addrConnect.ToString(),
591 NetworkErrorString(sockerr));
592 return false;
593 }
594 }
595#ifdef WIN32
596 else if (WSAGetLastError() != WSAEISCONN)
597#else
598 else
599#endif
600 {
601 LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
602 return false;
603 }
604 }
605 return true;
606}
607
608bool SetProxy(enum Network net, const proxyType &addrProxy) {
609 assert(net >= 0 && net < NET_MAX);
610 if (!addrProxy.IsValid())
611 return false;
613 proxyInfo[net] = addrProxy;
614 return true;
615}
616
617bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
618 assert(net >= 0 && net < NET_MAX);
620 if (!proxyInfo[net].IsValid())
621 return false;
622 proxyInfoOut = proxyInfo[net];
623 return true;
624}
625
626bool SetNameProxy(const proxyType &addrProxy) {
627 if (!addrProxy.IsValid())
628 return false;
630 nameProxy = addrProxy;
631 return true;
632}
633
634bool GetNameProxy(proxyType &nameProxyOut) {
636 if(!nameProxy.IsValid())
637 return false;
638 nameProxyOut = nameProxy;
639 return true;
640}
641
644 return nameProxy.IsValid();
645}
646
647bool IsProxy(const CNetAddr &addr) {
649 for (int i = 0; i < NET_MAX; i++) {
650 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
651 return true;
652 }
653 return false;
654}
655
656bool ConnectThroughProxy(const proxyType& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed)
657{
658 // first connect to proxy server
659 if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
660 outProxyConnectionFailed = true;
661 return false;
662 }
663 // do socks negotiation
664 if (proxy.randomize_credentials) {
665 ProxyCredentials random_auth;
666 static std::atomic_int counter(0);
667 random_auth.username = random_auth.password = strprintf("%i", counter++);
668 if (!Socks5(strDest, port, &random_auth, sock)) {
669 return false;
670 }
671 } else {
672 if (!Socks5(strDest, port, 0, sock)) {
673 return false;
674 }
675 }
676 return true;
677}
678
679bool LookupSubNet(const std::string& strSubnet, CSubNet& ret, DNSLookupFn dns_lookup_function)
680{
681 if (!ValidAsCString(strSubnet)) {
682 return false;
683 }
684 size_t slash = strSubnet.find_last_of('/');
685 std::vector<CNetAddr> vIP;
686
687 std::string strAddress = strSubnet.substr(0, slash);
688 // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just get
689 // one CNetAddr.
690 if (LookupHost(strAddress, vIP, 1, false, dns_lookup_function))
691 {
692 CNetAddr network = vIP[0];
693 if (slash != strSubnet.npos)
694 {
695 std::string strNetmask = strSubnet.substr(slash + 1);
696 uint8_t n;
697 if (ParseUInt8(strNetmask, &n)) {
698 // If valid number, assume CIDR variable-length subnet masking
699 ret = CSubNet(network, n);
700 return ret.IsValid();
701 }
702 else // If not a valid number, try full netmask syntax
703 {
704 // Never allow lookup for netmask
705 if (LookupHost(strNetmask, vIP, 1, false, dns_lookup_function)) {
706 ret = CSubNet(network, vIP[0]);
707 return ret.IsValid();
708 }
709 }
710 }
711 else
712 {
713 ret = CSubNet(network);
714 return ret.IsValid();
715 }
716 }
717 return false;
718}
719
720bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
721{
722 if (fNonBlocking) {
723#ifdef WIN32
724 u_long nOne = 1;
725 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
726#else
727 int fFlags = fcntl(hSocket, F_GETFL, 0);
728 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
729#endif
730 return false;
731 }
732 } else {
733#ifdef WIN32
734 u_long nZero = 0;
735 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
736#else
737 int fFlags = fcntl(hSocket, F_GETFL, 0);
738 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
739#endif
740 return false;
741 }
742 }
743
744 return true;
745}
746
747bool SetSocketNoDelay(const SOCKET& hSocket)
748{
749 int set = 1;
750 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
751 return rc == 0;
752}
753
754void InterruptSocks5(bool interrupt)
755{
756 interruptSocks5Recv = interrupt;
757}
Network address.
Definition: netaddress.h:119
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:212
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
std::string ToString() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:993
bool IsValid() const
RAII helper class that manages a socket.
Definition: sock.h:26
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:61
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition: sock.h:119
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:81
uint8_t Event
Definition: sock.h:109
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:114
virtual SOCKET Get() const
Get the value of the contained socket.
Definition: sock.cpp:50
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:76
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:71
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:66
bool IsValid() const
Definition: netbase.h:54
CService proxy
Definition: netbase.h:56
bool randomize_credentials
Definition: netbase.h:57
#define INVALID_SOCKET
Definition: compat.h:53
#define WSAEWOULDBLOCK
Definition: compat.h:46
#define WSAEINVAL
Definition: compat.h:44
#define SOCKET_ERROR
Definition: compat.h:54
#define WSAGetLastError()
Definition: compat.h:43
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:100
#define MSG_NOSIGNAL
Definition: compat.h:110
unsigned int SOCKET
Definition: compat.h:41
void * sockopt_arg_type
Definition: compat.h:88
#define WSAEINPROGRESS
Definition: compat.h:50
#define LogPrint(category,...)
Definition: logging.h:191
#define LogPrintf(...)
Definition: logging.h:187
@ PROXY
Definition: logging.h:53
@ NET
Definition: logging.h:38
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:1062
Network
A network type.
Definition: netaddress.h:45
@ 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:285
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:278
@ DOMAINNAME
Definition: netbase.cpp:280
@ IPV4
Definition: netbase.cpp:279
@ IPV6
Definition: netbase.cpp:281
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:258
@ UDP_ASSOCIATE
Definition: netbase.cpp:261
@ CONNECT
Definition: netbase.cpp:259
@ BIND
Definition: netbase.cpp:260
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:634
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args)
Definition: netbase.cpp:532
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:105
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:244
@ SOCKS4
Definition: netbase.cpp:245
@ SOCKS5
Definition: netbase.cpp:246
int g_socks5_recv_timeout
Definition: netbase.cpp:40
bool HaveNameProxy()
Definition: netbase.cpp:642
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:617
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:679
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:135
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:747
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:656
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:529
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout, const Sock &sock)
Try to read a specified number of bytes from a socket.
Definition: netbase.cpp:310
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:87
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:250
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:252
@ NOAUTH
No authentication required.
Definition: netbase.cpp:251
@ USER_PASS
Username/password.
Definition: netbase.cpp:253
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:254
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:367
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:343
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:754
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:486
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:541
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:265
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:272
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:273
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:269
@ GENFAILURE
General failure.
Definition: netbase.cpp:267
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:271
@ SUCCEEDED
Succeeded.
Definition: netbase.cpp:266
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:274
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:268
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:270
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:198
static Mutex g_proxyinfo_mutex
Definition: netbase.cpp:33
bool fNameLookup
Definition: netbase.cpp:37
static std::atomic< bool > interruptSocks5Recv(false)
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
int nConnectTimeout
Definition: netbase.cpp:36
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:626
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:720
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:230
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:647
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
Definition: netbase.cpp:43
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:85
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:170
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:608
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:121
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:99
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:28
const char * name
Definition: rest.cpp:43
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:313
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:331
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:19
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:78
Credentials for proxy authentication.
Definition: netbase.h:62
std::string username
Definition: netbase.h:63
std::string password
Definition: netbase.h:64
#define LOCK(cs)
Definition: sync.h:226
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
assert(!tx.IsCoinBase())