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