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