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