Bitcoin Core  22.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.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 proxyType 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 (!ValidAsCString(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 (!ValidAsCString(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 (!ValidAsCString(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() || !ValidAsCString(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 (!ValidAsCString(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 (!ValidAsCString(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,
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 ((recvr = 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 ((recvr = 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 ((recvr = 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  // Ensure that waiting for I/O on this socket won't result in undefined
503  // behavior.
504  if (!IsSelectableSocket(hSocket)) {
505  CloseSocket(hSocket);
506  LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
507  return nullptr;
508  }
509 
510 #ifdef SO_NOSIGPIPE
511  int set = 1;
512  // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
513  // should use the MSG_NOSIGNAL flag for every send.
514  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
515 #endif
516 
517  // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
518  SetSocketNoDelay(hSocket);
519 
520  // Set the non-blocking option on the socket.
521  if (!SetSocketNonBlocking(hSocket, true)) {
522  CloseSocket(hSocket);
523  LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
524  return nullptr;
525  }
526  return std::make_unique<Sock>(hSocket);
527 }
528 
529 std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP;
530 
531 template<typename... Args>
532 static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
533  std::string error_message = tfm::format(fmt, args...);
534  if (manual_connection) {
535  LogPrintf("%s\n", error_message);
536  } else {
537  LogPrint(BCLog::NET, "%s\n", error_message);
538  }
539 }
540 
541 bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection)
542 {
543  // Create a sockaddr from the specified service.
544  struct sockaddr_storage sockaddr;
545  socklen_t len = sizeof(sockaddr);
546  if (sock.Get() == INVALID_SOCKET) {
547  LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
548  return false;
549  }
550  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
551  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
552  return false;
553  }
554 
555  // Connect to the addrConnect service on the hSocket socket.
556  if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
557  int nErr = WSAGetLastError();
558  // WSAEINVAL is here because some legacy version of winsock uses it
559  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
560  {
561  // Connection didn't actually fail, but is being established
562  // asynchronously. Thus, use async I/O api (select/poll)
563  // synchronously to check for successful connection with a timeout.
564  const Sock::Event requested = Sock::RECV | Sock::SEND;
565  Sock::Event occurred;
566  if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) {
567  LogPrintf("wait for connect to %s failed: %s\n",
568  addrConnect.ToString(),
570  return false;
571  } else if (occurred == 0) {
572  LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToString());
573  return false;
574  }
575 
576  // Even if the wait was successful, the connect might not
577  // have been successful. The reason for this failure is hidden away
578  // in the SO_ERROR for the socket in modern systems. We read it into
579  // sockerr here.
580  int sockerr;
581  socklen_t sockerr_len = sizeof(sockerr);
582  if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
583  SOCKET_ERROR) {
584  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
585  return false;
586  }
587  if (sockerr != 0) {
588  LogConnectFailure(manual_connection,
589  "connect() to %s failed after wait: %s",
590  addrConnect.ToString(),
591  NetworkErrorString(sockerr));
592  return false;
593  }
594  }
595 #ifdef WIN32
596  else if (WSAGetLastError() != WSAEISCONN)
597 #else
598  else
599 #endif
600  {
601  LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
602  return false;
603  }
604  }
605  return true;
606 }
607 
608 bool SetProxy(enum Network net, const proxyType &addrProxy) {
609  assert(net >= 0 && net < NET_MAX);
610  if (!addrProxy.IsValid())
611  return false;
613  proxyInfo[net] = addrProxy;
614  return true;
615 }
616 
617 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
618  assert(net >= 0 && net < NET_MAX);
620  if (!proxyInfo[net].IsValid())
621  return false;
622  proxyInfoOut = proxyInfo[net];
623  return true;
624 }
625 
626 bool SetNameProxy(const proxyType &addrProxy) {
627  if (!addrProxy.IsValid())
628  return false;
630  nameProxy = addrProxy;
631  return true;
632 }
633 
634 bool GetNameProxy(proxyType &nameProxyOut) {
636  if(!nameProxy.IsValid())
637  return false;
638  nameProxyOut = nameProxy;
639  return true;
640 }
641 
644  return nameProxy.IsValid();
645 }
646 
647 bool IsProxy(const CNetAddr &addr) {
649  for (int i = 0; i < NET_MAX; i++) {
650  if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
651  return true;
652  }
653  return false;
654 }
655 
656 bool ConnectThroughProxy(const proxyType& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed)
657 {
658  // first connect to proxy server
659  if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
660  outProxyConnectionFailed = true;
661  return false;
662  }
663  // do socks negotiation
664  if (proxy.randomize_credentials) {
665  ProxyCredentials random_auth;
666  static std::atomic_int counter(0);
667  random_auth.username = random_auth.password = strprintf("%i", counter++);
668  if (!Socks5(strDest, port, &random_auth, sock)) {
669  return false;
670  }
671  } else {
672  if (!Socks5(strDest, port, 0, sock)) {
673  return false;
674  }
675  }
676  return true;
677 }
678 
679 bool LookupSubNet(const std::string& subnet_str, CSubNet& subnet_out)
680 {
681  if (!ValidAsCString(subnet_str)) {
682  return false;
683  }
684 
685  const size_t slash_pos{subnet_str.find_last_of('/')};
686  const std::string str_addr{subnet_str.substr(0, slash_pos)};
687  CNetAddr addr;
688 
689  if (LookupHost(str_addr, addr, /*fAllowLookup=*/false)) {
690  if (slash_pos != subnet_str.npos) {
691  const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
692  uint8_t netmask;
693  if (ParseUInt8(netmask_str, &netmask)) {
694  // Valid number; assume CIDR variable-length subnet masking.
695  subnet_out = CSubNet{addr, netmask};
696  return subnet_out.IsValid();
697  } else {
698  // Invalid number; try full netmask syntax. Never allow lookup for netmask.
699  CNetAddr full_netmask;
700  if (LookupHost(netmask_str, full_netmask, /*fAllowLookup=*/false)) {
701  subnet_out = CSubNet{addr, full_netmask};
702  return subnet_out.IsValid();
703  }
704  }
705  } else {
706  // Single IP subnet (<ipv4>/32 or <ipv6>/128).
707  subnet_out = CSubNet{addr};
708  return subnet_out.IsValid();
709  }
710  }
711  return false;
712 }
713 
714 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
715 {
716  if (fNonBlocking) {
717 #ifdef WIN32
718  u_long nOne = 1;
719  if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
720 #else
721  int fFlags = fcntl(hSocket, F_GETFL, 0);
722  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
723 #endif
724  return false;
725  }
726  } else {
727 #ifdef WIN32
728  u_long nZero = 0;
729  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
730 #else
731  int fFlags = fcntl(hSocket, F_GETFL, 0);
732  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
733 #endif
734  return false;
735  }
736  }
737 
738  return true;
739 }
740 
741 bool SetSocketNoDelay(const SOCKET& hSocket)
742 {
743  int set = 1;
744  int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
745  return rc == 0;
746 }
747 
748 void InterruptSocks5(bool interrupt)
749 {
750  interruptSocks5Recv = interrupt;
751 }
LogConnectFailure
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args)
Definition: netbase.cpp:532
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:528
CMDUNSUPPORTED
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:273
CService::GetSockAddr
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:993
LookupHost
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
SOCKS5Method
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:250
proxyType::IsValid
bool IsValid() const
Definition: netbase.h:54
NET_UNROUTABLE
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
assert
assert(!tx.IsCoinBase())
ParseNetwork
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:87
tinyformat::format
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
NET_IPV4
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
IPV4
@ IPV4
Definition: netbase.cpp:279
CONNREFUSED
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:271
Sock::Connect
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:72
NET_INTERNAL
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:66
sync.h
WSAEINPROGRESS
#define WSAEINPROGRESS
Definition: compat.h:50
string.h
USER_PASS
@ USER_PASS
Username/password.
Definition: netbase.cpp:253
CNetAddr
Network address.
Definition: netaddress.h:118
NET_MAX
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
GUARDED_BY
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
BIND
@ BIND
Definition: netbase.cpp:260
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:36
GetNameProxy
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:634
NETUNREACHABLE
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:269
AnnotatedMixin< std::mutex >
ConnectSocketDirectly
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:541
IntrRecvError::Disconnected
@ Disconnected
SOCKS5
@ SOCKS5
Definition: netbase.cpp:246
CreateSock
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:529
ValidAsCString
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:78
WSAGetLastError
#define WSAGetLastError()
Definition: compat.h:43
GSSAPI
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:252
Network
Network
A network type.
Definition: netaddress.h:45
IntrRecvError::Interrupted
@ Interrupted
SOCKS4
@ SOCKS4
Definition: netbase.cpp:245
SOCKS5Command
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:258
proxyType
Definition: netbase.h:48
BCLog::PROXY
@ PROXY
Definition: logging.h:54
tinyformat.h
CloseSocket
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:358
Sock
RAII helper class that manages a socket.
Definition: sock.h:26
IPV6
@ IPV6
Definition: netbase.cpp:281
HaveNameProxy
bool HaveNameProxy()
Definition: netbase.cpp:642
WSAEINVAL
#define WSAEINVAL
Definition: compat.h:44
UDP_ASSOCIATE
@ UDP_ASSOCIATE
Definition: netbase.cpp:261
LookupIntern
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:135
IsProxy
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:647
strencodings.h
NET_I2P
@ NET_I2P
I2P.
Definition: netaddress.h:59
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1048
NO_ACCEPTABLE
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:254
SplitHostPort
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
Definition: strencodings.cpp:110
LookupSubNet
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:679
NOAUTH
@ NOAUTH
No authentication required.
Definition: netbase.cpp:251
Socks5ErrorString
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:343
INVALID_SOCKET
#define INVALID_SOCKET
Definition: compat.h:53
CNetAddr::SetSpecial
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:212
Socks5
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
IsSelectableSocket
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:100
g_dns_lookup
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:85
compat.h
Sock::Recv
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:67
g_socks5_recv_timeout
int g_socks5_recv_timeout
Definition: netbase.cpp:40
IntrRecvError::NetworkError
@ NetworkError
Sock::Wait
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:108
GENFAILURE
@ GENFAILURE
General failure.
Definition: netbase.cpp:267
CreateSockTCP
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:486
ProxyCredentials::password
std::string password
Definition: netbase.h:64
Sock::SEND
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition: sock.h:128
time.h
SOCKS5Atyp
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:278
LogPrintf
#define LogPrintf(...)
Definition: logging.h:188
Sock::GetSockOpt
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:103
fNameLookup
bool fNameLookup
Definition: netbase.cpp:37
CSubNet
Definition: netaddress.h:475
NetworkErrorString
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:340
Sock::Send
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:62
SOCKET_ERROR
#define SOCKET_ERROR
Definition: compat.h:54
IntrRecvError
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:285
SOCKSVersion
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:244
LogPrint
#define LogPrint(category,...)
Definition: logging.h:192
GetNetworkNames
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:121
DEFAULT_CONNECT_TIMEOUT
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:28
WSAEWOULDBLOCK
#define WSAEWOULDBLOCK
Definition: compat.h:46
ProxyCredentials
Credentials for proxy authentication.
Definition: netbase.h:61
SUCCEEDED
@ SUCCEEDED
Succeeded.
Definition: netbase.cpp:266
name
const char * name
Definition: rest.cpp:52
InterruptibleRecv
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
DEFAULT_NAME_LOOKUP
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:30
system.h
InterruptSocks5
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:748
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:608
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
WrappedGetAddrInfo
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
Definition: netbase.cpp:43
Sock::Get
virtual SOCKET Get() const
Get the value of the contained socket.
Definition: sock.cpp:51
SetNameProxy
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:626
SetSocketNoDelay
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:741
IntrRecvError::Timeout
@ Timeout
proxyType::randomize_credentials
bool randomize_credentials
Definition: netbase.h:57
LOCK
#define LOCK(cs)
Definition: sync.h:226
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
Sock::Event
uint8_t Event
Definition: sock.h:118
MSG_NOSIGNAL
#define MSG_NOSIGNAL
Definition: compat.h:110
TTLEXPIRED
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:272
ATYPEUNSUPPORTED
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:274
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:1219
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:617
MAX_WAIT_FOR_IO
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:20
NET_IPV6
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
sockopt_arg_type
void * sockopt_arg_type
Definition: compat.h:88
SOCKS5Reply
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:265
HOSTUNREACHABLE
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:270
netbase.h
GetNetworkName
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:105
DNSLookupFn
std::function< std::vector< CNetAddr >(const std::string &, bool)> DNSLookupFn
Definition: netbase.h:99
Sock::RECV
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:123
LookupNumeric
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
NET_CJDNS
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:62
CONNECT
@ CONNECT
Definition: netbase.cpp:259
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
BCLog::NET
@ NET
Definition: logging.h:39
SetSocketNonBlocking
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:714
g_proxyinfo_mutex
static Mutex g_proxyinfo_mutex
Definition: netbase.cpp:33
Lookup
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
IntrRecvError::OK
@ OK
ConnectThroughProxy
bool ConnectThroughProxy(const proxyType &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:656
ParseUInt8
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
Definition: strencodings.cpp:309
NOTALLOWED
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:268
sock.h
ProxyCredentials::username
std::string username
Definition: netbase.h:63
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
proxyType::proxy
CService proxy
Definition: netbase.h:56
interruptSocks5Recv
static std::atomic< bool > interruptSocks5Recv(false)
args
ArgsManager args
Definition: notifications.cpp:36
SOCKET
unsigned int SOCKET
Definition: compat.h:41
ToLower
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
Definition: strencodings.cpp:490
DOMAINNAME
@ DOMAINNAME
Definition: netbase.cpp:280