Bitcoin Core  27.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;
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  }
302  if (g_socks5_interrupt) {
304  }
305  curTime = Now<SteadyMilliseconds>();
306  }
307  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
308 }
309 
311 static std::string Socks5ErrorString(uint8_t err)
312 {
313  switch(err) {
315  return "general failure";
317  return "connection not allowed";
319  return "network unreachable";
321  return "host unreachable";
323  return "connection refused";
325  return "TTL expired";
327  return "protocol error";
329  return "address type not supported";
330  default:
331  return "unknown";
332  }
333 }
334 
335 bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
336 {
337  try {
338  IntrRecvError recvr;
339  LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
340  if (strDest.size() > 255) {
341  return error("Hostname too long");
342  }
343  // Construct the version identifier/method selection message
344  std::vector<uint8_t> vSocks5Init;
345  vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
346  if (auth) {
347  vSocks5Init.push_back(0x02); // 2 method identifiers follow...
348  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
349  vSocks5Init.push_back(SOCKS5Method::USER_PASS);
350  } else {
351  vSocks5Init.push_back(0x01); // 1 method identifier follows...
352  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
353  }
355  uint8_t pchRet1[2];
356  if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
357  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
358  return false;
359  }
360  if (pchRet1[0] != SOCKSVersion::SOCKS5) {
361  return error("Proxy failed to initialize");
362  }
363  if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
364  // Perform username/password authentication (as described in RFC1929)
365  std::vector<uint8_t> vAuth;
366  vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
367  if (auth->username.size() > 255 || auth->password.size() > 255)
368  return error("Proxy username or password too long");
369  vAuth.push_back(auth->username.size());
370  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
371  vAuth.push_back(auth->password.size());
372  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
374  LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
375  uint8_t pchRetA[2];
376  if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
377  return error("Error reading proxy authentication response");
378  }
379  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
380  return error("Proxy authentication unsuccessful");
381  }
382  } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
383  // Perform no authentication
384  } else {
385  return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
386  }
387  std::vector<uint8_t> vSocks5;
388  vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
389  vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
390  vSocks5.push_back(0x00); // RSV Reserved must be 0
391  vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
392  vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
393  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
394  vSocks5.push_back((port >> 8) & 0xFF);
395  vSocks5.push_back((port >> 0) & 0xFF);
397  uint8_t pchRet2[4];
398  if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
399  if (recvr == IntrRecvError::Timeout) {
400  /* If a timeout happens here, this effectively means we timed out while connecting
401  * to the remote node. This is very common for Tor, so do not print an
402  * error message. */
403  return false;
404  } else {
405  return error("Error while reading proxy response");
406  }
407  }
408  if (pchRet2[0] != SOCKSVersion::SOCKS5) {
409  return error("Proxy failed to accept request");
410  }
411  if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
412  // Failures to connect to a peer that are not proxy errors
413  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
414  return false;
415  }
416  if (pchRet2[2] != 0x00) { // Reserved field must be 0
417  return error("Error: malformed proxy response");
418  }
419  uint8_t pchRet3[256];
420  switch (pchRet2[3]) {
421  case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
422  case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
423  case SOCKS5Atyp::DOMAINNAME: {
424  recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
425  if (recvr != IntrRecvError::OK) {
426  return error("Error reading from proxy");
427  }
428  int nRecv = pchRet3[0];
429  recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
430  break;
431  }
432  default: return error("Error: malformed proxy response");
433  }
434  if (recvr != IntrRecvError::OK) {
435  return error("Error reading from proxy");
436  }
437  if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
438  return error("Error reading from proxy");
439  }
440  LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
441  return true;
442  } catch (const std::runtime_error& e) {
443  return error("Error during SOCKS5 proxy handshake: %s", e.what());
444  }
445 }
446 
447 std::unique_ptr<Sock> CreateSockTCP(const CService& address_family)
448 {
449  // Create a sockaddr from the specified service.
450  struct sockaddr_storage sockaddr;
451  socklen_t len = sizeof(sockaddr);
452  if (!address_family.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
453  LogPrintf("Cannot create socket for %s: unsupported network\n", address_family.ToStringAddrPort());
454  return nullptr;
455  }
456 
457  // Create a TCP socket in the address family of the specified service.
458  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
459  if (hSocket == INVALID_SOCKET) {
460  return nullptr;
461  }
462 
463  auto sock = std::make_unique<Sock>(hSocket);
464 
465  // Ensure that waiting for I/O on this socket won't result in undefined
466  // behavior.
467  if (!sock->IsSelectable()) {
468  LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
469  return nullptr;
470  }
471 
472 #ifdef SO_NOSIGPIPE
473  int set = 1;
474  // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
475  // should use the MSG_NOSIGNAL flag for every send.
476  if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)) == SOCKET_ERROR) {
477  LogPrintf("Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n",
479  }
480 #endif
481 
482  // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
483  const int on{1};
484  if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
485  LogPrint(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
486  }
487 
488  // Set the non-blocking option on the socket.
489  if (!sock->SetNonBlocking()) {
490  LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
491  return nullptr;
492  }
493  return sock;
494 }
495 
496 std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP;
497 
498 template<typename... Args>
499 static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
500  std::string error_message = tfm::format(fmt, args...);
501  if (manual_connection) {
502  LogPrintf("%s\n", error_message);
503  } else {
504  LogPrint(BCLog::NET, "%s\n", error_message);
505  }
506 }
507 
508 bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection)
509 {
510  // Create a sockaddr from the specified service.
511  struct sockaddr_storage sockaddr;
512  socklen_t len = sizeof(sockaddr);
513  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
514  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToStringAddrPort());
515  return false;
516  }
517 
518  // Connect to the addrConnect service on the hSocket socket.
519  if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
520  int nErr = WSAGetLastError();
521  // WSAEINVAL is here because some legacy version of winsock uses it
522  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
523  {
524  // Connection didn't actually fail, but is being established
525  // asynchronously. Thus, use async I/O api (select/poll)
526  // synchronously to check for successful connection with a timeout.
527  const Sock::Event requested = Sock::RECV | Sock::SEND;
528  Sock::Event occurred;
529  if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) {
530  LogPrintf("wait for connect to %s failed: %s\n",
531  addrConnect.ToStringAddrPort(),
533  return false;
534  } else if (occurred == 0) {
535  LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToStringAddrPort());
536  return false;
537  }
538 
539  // Even if the wait was successful, the connect might not
540  // have been successful. The reason for this failure is hidden away
541  // in the SO_ERROR for the socket in modern systems. We read it into
542  // sockerr here.
543  int sockerr;
544  socklen_t sockerr_len = sizeof(sockerr);
545  if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
546  SOCKET_ERROR) {
547  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToStringAddrPort(), NetworkErrorString(WSAGetLastError()));
548  return false;
549  }
550  if (sockerr != 0) {
551  LogConnectFailure(manual_connection,
552  "connect() to %s failed after wait: %s",
553  addrConnect.ToStringAddrPort(),
554  NetworkErrorString(sockerr));
555  return false;
556  }
557  }
558 #ifdef WIN32
559  else if (WSAGetLastError() != WSAEISCONN)
560 #else
561  else
562 #endif
563  {
564  LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToStringAddrPort(), NetworkErrorString(WSAGetLastError()));
565  return false;
566  }
567  }
568  return true;
569 }
570 
571 bool SetProxy(enum Network net, const Proxy &addrProxy) {
572  assert(net >= 0 && net < NET_MAX);
573  if (!addrProxy.IsValid())
574  return false;
576  proxyInfo[net] = addrProxy;
577  return true;
578 }
579 
580 bool GetProxy(enum Network net, Proxy &proxyInfoOut) {
581  assert(net >= 0 && net < NET_MAX);
583  if (!proxyInfo[net].IsValid())
584  return false;
585  proxyInfoOut = proxyInfo[net];
586  return true;
587 }
588 
589 bool SetNameProxy(const Proxy &addrProxy) {
590  if (!addrProxy.IsValid())
591  return false;
593  nameProxy = addrProxy;
594  return true;
595 }
596 
597 bool GetNameProxy(Proxy &nameProxyOut) {
599  if(!nameProxy.IsValid())
600  return false;
601  nameProxyOut = nameProxy;
602  return true;
603 }
604 
607  return nameProxy.IsValid();
608 }
609 
610 bool IsProxy(const CNetAddr &addr) {
612  for (int i = 0; i < NET_MAX; i++) {
613  if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
614  return true;
615  }
616  return false;
617 }
618 
619 bool ConnectThroughProxy(const Proxy& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed)
620 {
621  // first connect to proxy server
622  if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
623  outProxyConnectionFailed = true;
624  return false;
625  }
626  // do socks negotiation
627  if (proxy.randomize_credentials) {
628  ProxyCredentials random_auth;
629  static std::atomic_int counter(0);
630  random_auth.username = random_auth.password = strprintf("%i", counter++);
631  if (!Socks5(strDest, port, &random_auth, sock)) {
632  return false;
633  }
634  } else {
635  if (!Socks5(strDest, port, nullptr, sock)) {
636  return false;
637  }
638  }
639  return true;
640 }
641 
642 CSubNet LookupSubNet(const std::string& subnet_str)
643 {
644  CSubNet subnet;
645  assert(!subnet.IsValid());
646  if (!ContainsNoNUL(subnet_str)) {
647  return subnet;
648  }
649 
650  const size_t slash_pos{subnet_str.find_last_of('/')};
651  const std::string str_addr{subnet_str.substr(0, slash_pos)};
652  std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)};
653 
654  if (addr.has_value()) {
655  addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
656  if (slash_pos != subnet_str.npos) {
657  const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
658  uint8_t netmask;
659  if (ParseUInt8(netmask_str, &netmask)) {
660  // Valid number; assume CIDR variable-length subnet masking.
661  subnet = CSubNet{addr.value(), netmask};
662  } else {
663  // Invalid number; try full netmask syntax. Never allow lookup for netmask.
664  const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)};
665  if (full_netmask.has_value()) {
666  subnet = CSubNet{addr.value(), full_netmask.value()};
667  }
668  }
669  } else {
670  // Single IP subnet (<ipv4>/32 or <ipv6>/128).
671  subnet = CSubNet{addr.value()};
672  }
673  }
674 
675  return subnet;
676 }
677 
678 bool IsBadPort(uint16_t port)
679 {
680  /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */
681 
682  switch (port) {
683  case 1: // tcpmux
684  case 7: // echo
685  case 9: // discard
686  case 11: // systat
687  case 13: // daytime
688  case 15: // netstat
689  case 17: // qotd
690  case 19: // chargen
691  case 20: // ftp data
692  case 21: // ftp access
693  case 22: // ssh
694  case 23: // telnet
695  case 25: // smtp
696  case 37: // time
697  case 42: // name
698  case 43: // nicname
699  case 53: // domain
700  case 69: // tftp
701  case 77: // priv-rjs
702  case 79: // finger
703  case 87: // ttylink
704  case 95: // supdup
705  case 101: // hostname
706  case 102: // iso-tsap
707  case 103: // gppitnp
708  case 104: // acr-nema
709  case 109: // pop2
710  case 110: // pop3
711  case 111: // sunrpc
712  case 113: // auth
713  case 115: // sftp
714  case 117: // uucp-path
715  case 119: // nntp
716  case 123: // NTP
717  case 135: // loc-srv /epmap
718  case 137: // netbios
719  case 139: // netbios
720  case 143: // imap2
721  case 161: // snmp
722  case 179: // BGP
723  case 389: // ldap
724  case 427: // SLP (Also used by Apple Filing Protocol)
725  case 465: // smtp+ssl
726  case 512: // print / exec
727  case 513: // login
728  case 514: // shell
729  case 515: // printer
730  case 526: // tempo
731  case 530: // courier
732  case 531: // chat
733  case 532: // netnews
734  case 540: // uucp
735  case 548: // AFP (Apple Filing Protocol)
736  case 554: // rtsp
737  case 556: // remotefs
738  case 563: // nntp+ssl
739  case 587: // smtp (rfc6409)
740  case 601: // syslog-conn (rfc3195)
741  case 636: // ldap+ssl
742  case 989: // ftps-data
743  case 990: // ftps
744  case 993: // ldap+ssl
745  case 995: // pop3+ssl
746  case 1719: // h323gatestat
747  case 1720: // h323hostcall
748  case 1723: // pptp
749  case 2049: // nfs
750  case 3659: // apple-sasl / PasswordServer
751  case 4045: // lockd
752  case 5060: // sip
753  case 5061: // sips
754  case 6000: // X11
755  case 6566: // sane-port
756  case 6665: // Alternate IRC
757  case 6666: // Alternate IRC
758  case 6667: // Standard IRC
759  case 6668: // Alternate IRC
760  case 6669: // Alternate IRC
761  case 6697: // IRC + TLS
762  case 10080: // Amanda
763  return true;
764  }
765  return false;
766 }
767 
769 {
770  CService ret{service};
771  if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) {
772  ret.m_net = NET_CJDNS;
773  }
774  return ret;
775 }
#define WSAEINPROGRESS
Definition: compat.h:47
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:335
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:264
assert(!tx.IsCoinBase())
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:53
Username/password.
Definition: netbase.cpp:221
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:56
bool randomize_credentials
Definition: netbase.h:55
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
virtual void SendComplete(Span< const unsigned char > data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
Definition: sock.cpp:245
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:37
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:499
void * sockopt_arg_type
Definition: compat.h:75
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
Definition: netbase.cpp:580
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:619
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:91
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:768
bool SetProxy(enum Network net, const Proxy &addrProxy)
Definition: netbase.cpp:571
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:49
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:41
List of reachable networks.
Definition: netbase.h:68
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:46
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:447
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:605
CService proxy
Definition: netbase.h:54
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:678
#define SOCKET_ERROR
Definition: compat.h:50
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:79
ArgsManager & args
Definition: bitcoind.cpp:268
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:508
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:257
const char * name
Definition: rest.cpp:49
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:530
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:589
Credentials for proxy authentication.
Definition: netbase.h:59
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:253
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:610
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:32
CThreadInterrupt g_socks5_interrupt
Interrupt SOCKS5 reads or writes.
Definition: netbase.cpp:33
bool IsValid() const
Definition: netbase.h:52
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:28
uint8_t Event
Definition: sock.h:138
A helper class for interruptible sleeps.
int nConnectTimeout
Definition: netbase.cpp:28
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:422
#define WSAEWOULDBLOCK
Definition: compat.h:43
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:311
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:39
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:81
Definition: netbase.h:46
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
bool GetNameProxy(Proxy &nameProxyOut)
Definition: netbase.cpp:597
Network address.
Definition: netaddress.h:111
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:152
TTL expired.
Definition: netbase.cpp:240
#define WSAEINVAL
Definition: compat.h:42
bool error(const char *fmt, const Args &... args)
Definition: logging.h:267
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:26
IPv6.
Definition: netaddress.h:40
TOR (v2 or v3)
Definition: netaddress.h:43
Succeeded.
Definition: netbase.cpp:234
std::string password
Definition: netbase.h:62
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:496
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:140
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:99
std::string username
Definition: netbase.h:61
static GlobalMutex g_proxyinfo_mutex
Definition: netbase.cpp:25
#define LogPrintf(...)
Definition: logging.h:245
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:246
CJDNS.
Definition: netaddress.h:49
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
CSubNet LookupSubNet(const std::string &subnet_str)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:642
ReachableNets g_reachable_nets
Definition: netbase.cpp:35
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:34