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