Bitcoin Core  21.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-2020 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 #else
27 #include <codecvt>
28 #endif
29 
30 #ifdef USE_POLL
31 #include <poll.h>
32 #endif
33 
34 // Settings
37 static proxyType nameProxy GUARDED_BY(g_proxyinfo_mutex);
40 
41 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
42 int g_socks5_recv_timeout = 20 * 1000;
43 static std::atomic<bool> interruptSocks5Recv(false);
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  // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
54  // return addresses whose family we have an address configured for.
55  //
56  // If we don't allow lookups, then use the AI_NUMERICHOST flag for
57  // getaddrinfo to only decode numerical network addresses and suppress
58  // hostname lookups.
59  ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
60 
61  addrinfo* ai_res{nullptr};
62  const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
63  if (n_err != 0) {
64  return {};
65  }
66 
67  // Traverse the linked list starting with ai_trav.
68  addrinfo* ai_trav{ai_res};
69  std::vector<CNetAddr> resolved_addresses;
70  while (ai_trav != nullptr) {
71  if (ai_trav->ai_family == AF_INET) {
72  assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
73  resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
74  }
75  if (ai_trav->ai_family == AF_INET6) {
76  assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
77  const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
78  resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
79  }
80  ai_trav = ai_trav->ai_next;
81  }
82  freeaddrinfo(ai_res);
83 
84  return resolved_addresses;
85 }
86 
88 
89 enum Network ParseNetwork(const std::string& net_in) {
90  std::string net = ToLower(net_in);
91  if (net == "ipv4") return NET_IPV4;
92  if (net == "ipv6") return NET_IPV6;
93  if (net == "onion") return NET_ONION;
94  if (net == "tor") {
95  LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
96  return NET_ONION;
97  }
98  if (net == "i2p") {
99  return NET_I2P;
100  }
101  return NET_UNROUTABLE;
102 }
103 
104 std::string GetNetworkName(enum Network net)
105 {
106  switch (net) {
107  case NET_UNROUTABLE: return "not_publicly_routable";
108  case NET_IPV4: return "ipv4";
109  case NET_IPV6: return "ipv6";
110  case NET_ONION: return "onion";
111  case NET_I2P: return "i2p";
112  case NET_CJDNS: return "cjdns";
113  case NET_INTERNAL: return "internal";
114  case NET_MAX: assert(false);
115  } // no default case, so the compiler can warn about missing cases
116 
117  assert(false);
118 }
119 
120 std::vector<std::string> GetNetworkNames(bool append_unroutable)
121 {
122  std::vector<std::string> names;
123  for (int n = 0; n < NET_MAX; ++n) {
124  const enum Network network{static_cast<Network>(n)};
125  if (network == NET_UNROUTABLE || network == NET_CJDNS || network == NET_INTERNAL) continue;
126  names.emplace_back(GetNetworkName(network));
127  }
128  if (append_unroutable) {
129  names.emplace_back(GetNetworkName(NET_UNROUTABLE));
130  }
131  return names;
132 }
133 
134 static bool LookupIntern(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
135 {
136  vIP.clear();
137 
138  if (!ValidAsCString(name)) {
139  return false;
140  }
141 
142  {
143  CNetAddr addr;
144  // From our perspective, onion addresses are not hostnames but rather
145  // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
146  // or IPv6 colon-separated hextet notation. Since we can't use
147  // getaddrinfo to decode them and it wouldn't make sense to resolve
148  // them, we return a network address representing it instead. See
149  // CNetAddr::SetSpecial(const std::string&) for more details.
150  if (addr.SetSpecial(name)) {
151  vIP.push_back(addr);
152  return true;
153  }
154  }
155 
156  for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
157  if (nMaxSolutions > 0 && vIP.size() >= nMaxSolutions) {
158  break;
159  }
160  /* Never allow resolving to an internal address. Consider any such result invalid */
161  if (!resolved.IsInternal()) {
162  vIP.push_back(resolved);
163  }
164  }
165 
166  return (vIP.size() > 0);
167 }
168 
169 bool LookupHost(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
170 {
171  if (!ValidAsCString(name)) {
172  return false;
173  }
174  std::string strHost = name;
175  if (strHost.empty())
176  return false;
177  if (strHost.front() == '[' && strHost.back() == ']') {
178  strHost = strHost.substr(1, strHost.size() - 2);
179  }
180 
181  return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
182 }
183 
184 bool LookupHost(const std::string& name, CNetAddr& addr, bool fAllowLookup, DNSLookupFn dns_lookup_function)
185 {
186  if (!ValidAsCString(name)) {
187  return false;
188  }
189  std::vector<CNetAddr> vIP;
190  LookupHost(name, vIP, 1, fAllowLookup, dns_lookup_function);
191  if(vIP.empty())
192  return false;
193  addr = vIP.front();
194  return true;
195 }
196 
197 bool Lookup(const std::string& name, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
198 {
199  if (name.empty() || !ValidAsCString(name)) {
200  return false;
201  }
202  uint16_t port{portDefault};
203  std::string hostname;
204  SplitHostPort(name, port, hostname);
205 
206  std::vector<CNetAddr> vIP;
207  bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
208  if (!fRet)
209  return false;
210  vAddr.resize(vIP.size());
211  for (unsigned int i = 0; i < vIP.size(); i++)
212  vAddr[i] = CService(vIP[i], port);
213  return true;
214 }
215 
216 bool Lookup(const std::string& name, CService& addr, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
217 {
218  if (!ValidAsCString(name)) {
219  return false;
220  }
221  std::vector<CService> vService;
222  bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1, dns_lookup_function);
223  if (!fRet)
224  return false;
225  addr = vService[0];
226  return true;
227 }
228 
229 CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
230 {
231  if (!ValidAsCString(name)) {
232  return {};
233  }
234  CService addr;
235  // "1.2:345" will fail to resolve the ip, but will still set the port.
236  // If the ip fails to resolve, re-init the result.
237  if(!Lookup(name, addr, portDefault, false, dns_lookup_function))
238  addr = CService();
239  return addr;
240 }
241 
243 enum SOCKSVersion: uint8_t {
244  SOCKS4 = 0x04,
245  SOCKS5 = 0x05
246 };
247 
249 enum SOCKS5Method: uint8_t {
250  NOAUTH = 0x00,
251  GSSAPI = 0x01,
252  USER_PASS = 0x02,
253  NO_ACCEPTABLE = 0xff,
254 };
255 
257 enum SOCKS5Command: uint8_t {
258  CONNECT = 0x01,
259  BIND = 0x02,
261 };
262 
264 enum SOCKS5Reply: uint8_t {
265  SUCCEEDED = 0x00,
266  GENFAILURE = 0x01,
267  NOTALLOWED = 0x02,
268  NETUNREACHABLE = 0x03,
270  CONNREFUSED = 0x05,
271  TTLEXPIRED = 0x06,
272  CMDUNSUPPORTED = 0x07,
274 };
275 
277 enum SOCKS5Atyp: uint8_t {
278  IPV4 = 0x01,
279  DOMAINNAME = 0x03,
280  IPV6 = 0x04,
281 };
282 
284 enum class IntrRecvError {
285  OK,
286  Timeout,
287  Disconnected,
288  NetworkError,
290 };
291 
309 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const Sock& sock)
310 {
311  int64_t curTime = GetTimeMillis();
312  int64_t endTime = curTime + timeout;
313  while (len > 0 && curTime < endTime) {
314  ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
315  if (ret > 0) {
316  len -= ret;
317  data += ret;
318  } else if (ret == 0) { // Unexpected disconnection
320  } else { // Other error or blocking
321  int nErr = WSAGetLastError();
322  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
323  // Only wait at most MAX_WAIT_FOR_IO at a time, unless
324  // we're approaching the end of the specified total timeout
325  const auto remaining = std::chrono::milliseconds{endTime - curTime};
326  const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
327  if (!sock.Wait(timeout, Sock::RECV)) {
329  }
330  } else {
332  }
333  }
336  curTime = GetTimeMillis();
337  }
338  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
339 }
340 
342 static std::string Socks5ErrorString(uint8_t err)
343 {
344  switch(err) {
346  return "general failure";
348  return "connection not allowed";
350  return "network unreachable";
352  return "host unreachable";
354  return "connection refused";
356  return "TTL expired";
358  return "protocol error";
360  return "address type not supported";
361  default:
362  return "unknown";
363  }
364 }
365 
366 bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
367 {
368  IntrRecvError recvr;
369  LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
370  if (strDest.size() > 255) {
371  return error("Hostname too long");
372  }
373  // Construct the version identifier/method selection message
374  std::vector<uint8_t> vSocks5Init;
375  vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
376  if (auth) {
377  vSocks5Init.push_back(0x02); // 2 method identifiers follow...
378  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
379  vSocks5Init.push_back(SOCKS5Method::USER_PASS);
380  } else {
381  vSocks5Init.push_back(0x01); // 1 method identifier follows...
382  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
383  }
384  ssize_t ret = sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
385  if (ret != (ssize_t)vSocks5Init.size()) {
386  return error("Error sending to proxy");
387  }
388  uint8_t pchRet1[2];
389  if ((recvr = InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
390  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
391  return false;
392  }
393  if (pchRet1[0] != SOCKSVersion::SOCKS5) {
394  return error("Proxy failed to initialize");
395  }
396  if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
397  // Perform username/password authentication (as described in RFC1929)
398  std::vector<uint8_t> vAuth;
399  vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
400  if (auth->username.size() > 255 || auth->password.size() > 255)
401  return error("Proxy username or password too long");
402  vAuth.push_back(auth->username.size());
403  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
404  vAuth.push_back(auth->password.size());
405  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
406  ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
407  if (ret != (ssize_t)vAuth.size()) {
408  return error("Error sending authentication to proxy");
409  }
410  LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
411  uint8_t pchRetA[2];
412  if ((recvr = InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
413  return error("Error reading proxy authentication response");
414  }
415  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
416  return error("Proxy authentication unsuccessful");
417  }
418  } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
419  // Perform no authentication
420  } else {
421  return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
422  }
423  std::vector<uint8_t> vSocks5;
424  vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
425  vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
426  vSocks5.push_back(0x00); // RSV Reserved must be 0
427  vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
428  vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
429  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
430  vSocks5.push_back((port >> 8) & 0xFF);
431  vSocks5.push_back((port >> 0) & 0xFF);
432  ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
433  if (ret != (ssize_t)vSocks5.size()) {
434  return error("Error sending to proxy");
435  }
436  uint8_t pchRet2[4];
437  if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
438  if (recvr == IntrRecvError::Timeout) {
439  /* If a timeout happens here, this effectively means we timed out while connecting
440  * to the remote node. This is very common for Tor, so do not print an
441  * error message. */
442  return false;
443  } else {
444  return error("Error while reading proxy response");
445  }
446  }
447  if (pchRet2[0] != SOCKSVersion::SOCKS5) {
448  return error("Proxy failed to accept request");
449  }
450  if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
451  // Failures to connect to a peer that are not proxy errors
452  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
453  return false;
454  }
455  if (pchRet2[2] != 0x00) { // Reserved field must be 0
456  return error("Error: malformed proxy response");
457  }
458  uint8_t pchRet3[256];
459  switch (pchRet2[3])
460  {
461  case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
462  case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
464  {
465  recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
466  if (recvr != IntrRecvError::OK) {
467  return error("Error reading from proxy");
468  }
469  int nRecv = pchRet3[0];
470  recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
471  break;
472  }
473  default: return error("Error: malformed proxy response");
474  }
475  if (recvr != IntrRecvError::OK) {
476  return error("Error reading from proxy");
477  }
478  if ((recvr = InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
479  return error("Error reading from proxy");
480  }
481  LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
482  return true;
483 }
484 
485 std::unique_ptr<Sock> CreateSockTCP(const CService& address_family)
486 {
487  // Create a sockaddr from the specified service.
488  struct sockaddr_storage sockaddr;
489  socklen_t len = sizeof(sockaddr);
490  if (!address_family.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
491  LogPrintf("Cannot create socket for %s: unsupported network\n", address_family.ToString());
492  return nullptr;
493  }
494 
495  // Create a TCP socket in the address family of the specified service.
496  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
497  if (hSocket == INVALID_SOCKET) {
498  return nullptr;
499  }
500 
501  // Ensure that waiting for I/O on this socket won't result in undefined
502  // behavior.
503  if (!IsSelectableSocket(hSocket)) {
504  CloseSocket(hSocket);
505  LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
506  return nullptr;
507  }
508 
509 #ifdef SO_NOSIGPIPE
510  int set = 1;
511  // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
512  // should use the MSG_NOSIGNAL flag for every send.
513  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
514 #endif
515 
516  // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
517  SetSocketNoDelay(hSocket);
518 
519  // Set the non-blocking option on the socket.
520  if (!SetSocketNonBlocking(hSocket, true)) {
521  CloseSocket(hSocket);
522  LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
523  return nullptr;
524  }
525  return std::make_unique<Sock>(hSocket);
526 }
527 
528 std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP;
529 
530 template<typename... Args>
531 static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
532  std::string error_message = tfm::format(fmt, args...);
533  if (manual_connection) {
534  LogPrintf("%s\n", error_message);
535  } else {
536  LogPrint(BCLog::NET, "%s\n", error_message);
537  }
538 }
539 
540 bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection)
541 {
542  // Create a sockaddr from the specified service.
543  struct sockaddr_storage sockaddr;
544  socklen_t len = sizeof(sockaddr);
545  if (sock.Get() == INVALID_SOCKET) {
546  LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
547  return false;
548  }
549  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
550  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
551  return false;
552  }
553 
554  // Connect to the addrConnect service on the hSocket socket.
555  if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
556  int nErr = WSAGetLastError();
557  // WSAEINVAL is here because some legacy version of winsock uses it
558  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
559  {
560  // Connection didn't actually fail, but is being established
561  // asynchronously. Thus, use async I/O api (select/poll)
562  // synchronously to check for successful connection with a timeout.
563  const Sock::Event requested = Sock::RECV | Sock::SEND;
564  Sock::Event occurred;
565  if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) {
566  LogPrintf("wait for connect to %s failed: %s\n",
567  addrConnect.ToString(),
569  return false;
570  } else if (occurred == 0) {
571  LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToString());
572  return false;
573  }
574 
575  // Even if the wait was successful, the connect might not
576  // have been successful. The reason for this failure is hidden away
577  // in the SO_ERROR for the socket in modern systems. We read it into
578  // sockerr here.
579  int sockerr;
580  socklen_t sockerr_len = sizeof(sockerr);
581  if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
582  SOCKET_ERROR) {
583  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
584  return false;
585  }
586  if (sockerr != 0) {
587  LogConnectFailure(manual_connection,
588  "connect() to %s failed after wait: %s",
589  addrConnect.ToString(),
590  NetworkErrorString(sockerr));
591  return false;
592  }
593  }
594 #ifdef WIN32
595  else if (WSAGetLastError() != WSAEISCONN)
596 #else
597  else
598 #endif
599  {
600  LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
601  return false;
602  }
603  }
604  return true;
605 }
606 
607 bool SetProxy(enum Network net, const proxyType &addrProxy) {
608  assert(net >= 0 && net < NET_MAX);
609  if (!addrProxy.IsValid())
610  return false;
612  proxyInfo[net] = addrProxy;
613  return true;
614 }
615 
616 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
617  assert(net >= 0 && net < NET_MAX);
619  if (!proxyInfo[net].IsValid())
620  return false;
621  proxyInfoOut = proxyInfo[net];
622  return true;
623 }
624 
625 bool SetNameProxy(const proxyType &addrProxy) {
626  if (!addrProxy.IsValid())
627  return false;
629  nameProxy = addrProxy;
630  return true;
631 }
632 
633 bool GetNameProxy(proxyType &nameProxyOut) {
635  if(!nameProxy.IsValid())
636  return false;
637  nameProxyOut = nameProxy;
638  return true;
639 }
640 
643  return nameProxy.IsValid();
644 }
645 
646 bool IsProxy(const CNetAddr &addr) {
648  for (int i = 0; i < NET_MAX; i++) {
649  if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
650  return true;
651  }
652  return false;
653 }
654 
655 bool ConnectThroughProxy(const proxyType& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed)
656 {
657  // first connect to proxy server
658  if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
659  outProxyConnectionFailed = true;
660  return false;
661  }
662  // do socks negotiation
663  if (proxy.randomize_credentials) {
664  ProxyCredentials random_auth;
665  static std::atomic_int counter(0);
666  random_auth.username = random_auth.password = strprintf("%i", counter++);
667  if (!Socks5(strDest, port, &random_auth, sock)) {
668  return false;
669  }
670  } else {
671  if (!Socks5(strDest, port, 0, sock)) {
672  return false;
673  }
674  }
675  return true;
676 }
677 
678 bool LookupSubNet(const std::string& strSubnet, CSubNet& ret, DNSLookupFn dns_lookup_function)
679 {
680  if (!ValidAsCString(strSubnet)) {
681  return false;
682  }
683  size_t slash = strSubnet.find_last_of('/');
684  std::vector<CNetAddr> vIP;
685 
686  std::string strAddress = strSubnet.substr(0, slash);
687  // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just get
688  // one CNetAddr.
689  if (LookupHost(strAddress, vIP, 1, false, dns_lookup_function))
690  {
691  CNetAddr network = vIP[0];
692  if (slash != strSubnet.npos)
693  {
694  std::string strNetmask = strSubnet.substr(slash + 1);
695  uint8_t n;
696  if (ParseUInt8(strNetmask, &n)) {
697  // If valid number, assume CIDR variable-length subnet masking
698  ret = CSubNet(network, n);
699  return ret.IsValid();
700  }
701  else // If not a valid number, try full netmask syntax
702  {
703  // Never allow lookup for netmask
704  if (LookupHost(strNetmask, vIP, 1, false, dns_lookup_function)) {
705  ret = CSubNet(network, vIP[0]);
706  return ret.IsValid();
707  }
708  }
709  }
710  else
711  {
712  ret = CSubNet(network);
713  return ret.IsValid();
714  }
715  }
716  return false;
717 }
718 
719 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
720 {
721  if (fNonBlocking) {
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  } else {
732 #ifdef WIN32
733  u_long nZero = 0;
734  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
735 #else
736  int fFlags = fcntl(hSocket, F_GETFL, 0);
737  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
738 #endif
739  return false;
740  }
741  }
742 
743  return true;
744 }
745 
746 bool SetSocketNoDelay(const SOCKET& hSocket)
747 {
748  int set = 1;
749  int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
750  return rc == 0;
751 }
752 
753 void InterruptSocks5(bool interrupt)
754 {
755  interruptSocks5Recv = interrupt;
756 }
LogConnectFailure
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args)
Definition: netbase.cpp:531
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:551
CMDUNSUPPORTED
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:272
CService::GetSockAddr
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:973
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:169
SOCKS5Method
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:249
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:46
ParseNetwork
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:89
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:49
LookupSubNet
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:678
IPV4
@ IPV4
Definition: netbase.cpp:278
CONNREFUSED
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:270
Sock::Connect
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:69
NET_INTERNAL
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
sync.h
WSAEINPROGRESS
#define WSAEINPROGRESS
Definition: compat.h:50
string.h
USER_PASS
@ USER_PASS
Username/password.
Definition: netbase.cpp:252
CNetAddr
Network address.
Definition: netaddress.h:119
NET_MAX
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
GUARDED_BY
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
BIND
@ BIND
Definition: netbase.cpp:259
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:38
GetNameProxy
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:633
NETUNREACHABLE
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:268
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:540
IntrRecvError::Disconnected
@ Disconnected
SOCKS5
@ SOCKS5
Definition: netbase.cpp:245
CreateSock
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:528
ValidAsCString
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:70
WSAGetLastError
#define WSAGetLastError()
Definition: compat.h:43
GSSAPI
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:251
Network
Network
A network type.
Definition: netaddress.h:43
IntrRecvError::Interrupted
@ Interrupted
SOCKS4
@ SOCKS4
Definition: netbase.cpp:244
SOCKS5Command
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:257
proxyType
Definition: netbase.h:48
BCLog::PROXY
@ PROXY
Definition: logging.h:53
tinyformat.h
CloseSocket
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:329
Sock
RAII helper class that manages a socket.
Definition: sock.h:25
IPV6
@ IPV6
Definition: netbase.cpp:280
HaveNameProxy
bool HaveNameProxy()
Definition: netbase.cpp:641
WSAEINVAL
#define WSAEINVAL
Definition: compat.h:44
UDP_ASSOCIATE
@ UDP_ASSOCIATE
Definition: netbase.cpp:260
LookupIntern
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:134
IsProxy
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:646
strencodings.h
NET_I2P
@ NET_I2P
I2P.
Definition: netaddress.h:58
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1028
NO_ACCEPTABLE
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:253
SplitHostPort
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
Definition: strencodings.cpp:110
NOAUTH
@ NOAUTH
No authentication required.
Definition: netbase.cpp:250
Socks5ErrorString
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:342
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:224
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:366
IsSelectableSocket
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:100
g_dns_lookup
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:87
compat.h
Sock::Recv
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:64
g_socks5_recv_timeout
int g_socks5_recv_timeout
Definition: netbase.cpp:42
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:79
GENFAILURE
@ GENFAILURE
General failure.
Definition: netbase.cpp:266
CreateSockTCP
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:485
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:116
time.h
SOCKS5Atyp
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:277
LogPrintf
#define LogPrintf(...)
Definition: logging.h:183
Sock::GetSockOpt
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:74
fNameLookup
bool fNameLookup
Definition: netbase.cpp:39
CSubNet
Definition: netaddress.h:480
NetworkErrorString
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:311
Sock::Send
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:59
SOCKET_ERROR
#define SOCKET_ERROR
Definition: compat.h:54
IntrRecvError
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:284
SOCKSVersion
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:243
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
GetNetworkNames
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:120
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:265
name
const char * name
Definition: rest.cpp:43
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:309
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:753
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:607
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:45
Sock::Get
virtual SOCKET Get() const
Get the value of the contained socket.
Definition: sock.cpp:48
SetNameProxy
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:625
SetSocketNoDelay
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:746
IntrRecvError::Timeout
@ Timeout
proxyType::randomize_credentials
bool randomize_credentials
Definition: netbase.h:57
LOCK
#define LOCK(cs)
Definition: sync.h:232
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
Sock::Event
uint8_t Event
Definition: sock.h:106
MSG_NOSIGNAL
#define MSG_NOSIGNAL
Definition: compat.h:110
TTLEXPIRED
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:271
ATYPEUNSUPPORTED
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:273
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:1199
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:616
MAX_WAIT_FOR_IO
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:19
NET_IPV6
@ NET_IPV6
IPv6.
Definition: netaddress.h:52
sockopt_arg_type
void * sockopt_arg_type
Definition: compat.h:88
SOCKS5Reply
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:264
HOSTUNREACHABLE
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:269
netbase.h
GetNetworkName
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:104
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:111
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:229
NET_CJDNS
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:61
CONNECT
@ CONNECT
Definition: netbase.cpp:258
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:50
BCLog::NET
@ NET
Definition: logging.h:38
SetSocketNonBlocking
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:719
g_proxyinfo_mutex
static Mutex g_proxyinfo_mutex
Definition: netbase.cpp:35
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:197
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:655
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:327
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
NOTALLOWED
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:267
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)
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:573
DOMAINNAME
@ DOMAINNAME
Definition: netbase.cpp:279