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