Bitcoin Core  0.20.99
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 <sync.h>
9 #include <tinyformat.h>
10 #include <util/strencodings.h>
11 #include <util/string.h>
12 #include <util/system.h>
13 
14 #include <atomic>
15 
16 #ifndef WIN32
17 #include <fcntl.h>
18 #else
19 #include <codecvt>
20 #endif
21 
22 #ifdef USE_POLL
23 #include <poll.h>
24 #endif
25 
26 #if !defined(MSG_NOSIGNAL)
27 #define MSG_NOSIGNAL 0
28 #endif
29 
30 // Settings
32 static proxyType proxyInfo[NET_MAX] GUARDED_BY(cs_proxyInfos);
33 static proxyType nameProxy GUARDED_BY(cs_proxyInfos);
36 
37 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
38 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
39 static std::atomic<bool> interruptSocks5Recv(false);
40 
41 enum Network ParseNetwork(const std::string& net_in) {
42  std::string net = ToLower(net_in);
43  if (net == "ipv4") return NET_IPV4;
44  if (net == "ipv6") return NET_IPV6;
45  if (net == "onion") return NET_ONION;
46  if (net == "tor") {
47  LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
48  return NET_ONION;
49  }
50  return NET_UNROUTABLE;
51 }
52 
53 std::string GetNetworkName(enum Network net) {
54  switch(net)
55  {
56  case NET_IPV4: return "ipv4";
57  case NET_IPV6: return "ipv6";
58  case NET_ONION: return "onion";
59  default: return "";
60  }
61 }
62 
63 bool static LookupIntern(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
64 {
65  vIP.clear();
66 
67  if (!ValidAsCString(name)) {
68  return false;
69  }
70 
71  {
72  CNetAddr addr;
73  // From our perspective, onion addresses are not hostnames but rather
74  // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
75  // or IPv6 colon-separated hextet notation. Since we can't use
76  // getaddrinfo to decode them and it wouldn't make sense to resolve
77  // them, we return a network address representing it instead. See
78  // CNetAddr::SetSpecial(const std::string&) for more details.
79  if (addr.SetSpecial(name)) {
80  vIP.push_back(addr);
81  return true;
82  }
83  }
84 
85  struct addrinfo aiHint;
86  memset(&aiHint, 0, sizeof(struct addrinfo));
87 
88  // We want a TCP port, which is a streaming socket type
89  aiHint.ai_socktype = SOCK_STREAM;
90  aiHint.ai_protocol = IPPROTO_TCP;
91  // We don't care which address family (IPv4 or IPv6) is returned
92  aiHint.ai_family = AF_UNSPEC;
93  // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
94  // return addresses whose family we have an address configured for.
95  //
96  // If we don't allow lookups, then use the AI_NUMERICHOST flag for
97  // getaddrinfo to only decode numerical network addresses and suppress
98  // hostname lookups.
99  aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
100  struct addrinfo *aiRes = nullptr;
101  int nErr = getaddrinfo(name.c_str(), nullptr, &aiHint, &aiRes);
102  if (nErr)
103  return false;
104 
105  // Traverse the linked list starting with aiTrav, add all non-internal
106  // IPv4,v6 addresses to vIP while respecting nMaxSolutions.
107  struct addrinfo *aiTrav = aiRes;
108  while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
109  {
110  CNetAddr resolved;
111  if (aiTrav->ai_family == AF_INET)
112  {
113  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
114  resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
115  }
116 
117  if (aiTrav->ai_family == AF_INET6)
118  {
119  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
120  struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
121  resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
122  }
123  /* Never allow resolving to an internal address. Consider any such result invalid */
124  if (!resolved.IsInternal()) {
125  vIP.push_back(resolved);
126  }
127 
128  aiTrav = aiTrav->ai_next;
129  }
130 
131  freeaddrinfo(aiRes);
132 
133  return (vIP.size() > 0);
134 }
135 
151 bool LookupHost(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
152 {
153  if (!ValidAsCString(name)) {
154  return false;
155  }
156  std::string strHost = name;
157  if (strHost.empty())
158  return false;
159  if (strHost.front() == '[' && strHost.back() == ']') {
160  strHost = strHost.substr(1, strHost.size() - 2);
161  }
162 
163  return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup);
164 }
165 
172 bool LookupHost(const std::string& name, CNetAddr& addr, bool fAllowLookup)
173 {
174  if (!ValidAsCString(name)) {
175  return false;
176  }
177  std::vector<CNetAddr> vIP;
178  LookupHost(name, vIP, 1, fAllowLookup);
179  if(vIP.empty())
180  return false;
181  addr = vIP.front();
182  return true;
183 }
184 
205 bool Lookup(const std::string& name, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
206 {
207  if (name.empty() || !ValidAsCString(name)) {
208  return false;
209  }
210  int port = portDefault;
211  std::string hostname;
212  SplitHostPort(name, port, hostname);
213 
214  std::vector<CNetAddr> vIP;
215  bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup);
216  if (!fRet)
217  return false;
218  vAddr.resize(vIP.size());
219  for (unsigned int i = 0; i < vIP.size(); i++)
220  vAddr[i] = CService(vIP[i], port);
221  return true;
222 }
223 
230 bool Lookup(const std::string& name, CService& addr, int portDefault, bool fAllowLookup)
231 {
232  if (!ValidAsCString(name)) {
233  return false;
234  }
235  std::vector<CService> vService;
236  bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1);
237  if (!fRet)
238  return false;
239  addr = vService[0];
240  return true;
241 }
242 
253 CService LookupNumeric(const std::string& name, int portDefault)
254 {
255  if (!ValidAsCString(name)) {
256  return {};
257  }
258  CService addr;
259  // "1.2:345" will fail to resolve the ip, but will still set the port.
260  // If the ip fails to resolve, re-init the result.
261  if(!Lookup(name, addr, portDefault, false))
262  addr = CService();
263  return addr;
264 }
265 
266 struct timeval MillisToTimeval(int64_t nTimeout)
267 {
268  struct timeval timeout;
269  timeout.tv_sec = nTimeout / 1000;
270  timeout.tv_usec = (nTimeout % 1000) * 1000;
271  return timeout;
272 }
273 
275 enum SOCKSVersion: uint8_t {
276  SOCKS4 = 0x04,
277  SOCKS5 = 0x05
278 };
279 
281 enum SOCKS5Method: uint8_t {
282  NOAUTH = 0x00,
283  GSSAPI = 0x01,
284  USER_PASS = 0x02,
285  NO_ACCEPTABLE = 0xff,
286 };
287 
289 enum SOCKS5Command: uint8_t {
290  CONNECT = 0x01,
291  BIND = 0x02,
293 };
294 
296 enum SOCKS5Reply: uint8_t {
297  SUCCEEDED = 0x00,
298  GENFAILURE = 0x01,
299  NOTALLOWED = 0x02,
300  NETUNREACHABLE = 0x03,
302  CONNREFUSED = 0x05,
303  TTLEXPIRED = 0x06,
304  CMDUNSUPPORTED = 0x07,
306 };
307 
309 enum SOCKS5Atyp: uint8_t {
310  IPV4 = 0x01,
311  DOMAINNAME = 0x03,
312  IPV6 = 0x04,
313 };
314 
316 enum class IntrRecvError {
317  OK,
318  Timeout,
319  Disconnected,
320  NetworkError,
322 };
323 
342 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket)
343 {
344  int64_t curTime = GetTimeMillis();
345  int64_t endTime = curTime + timeout;
346  // Maximum time to wait for I/O readiness. It will take up until this time
347  // (in millis) to break off in case of an interruption.
348  const int64_t maxWait = 1000;
349  while (len > 0 && curTime < endTime) {
350  ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first
351  if (ret > 0) {
352  len -= ret;
353  data += ret;
354  } else if (ret == 0) { // Unexpected disconnection
356  } else { // Other error or blocking
357  int nErr = WSAGetLastError();
358  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
359  if (!IsSelectableSocket(hSocket)) {
361  }
362  // Only wait at most maxWait milliseconds at a time, unless
363  // we're approaching the end of the specified total timeout
364  int timeout_ms = std::min(endTime - curTime, maxWait);
365 #ifdef USE_POLL
366  struct pollfd pollfd = {};
367  pollfd.fd = hSocket;
368  pollfd.events = POLLIN;
369  int nRet = poll(&pollfd, 1, timeout_ms);
370 #else
371  struct timeval tval = MillisToTimeval(timeout_ms);
372  fd_set fdset;
373  FD_ZERO(&fdset);
374  FD_SET(hSocket, &fdset);
375  int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval);
376 #endif
377  if (nRet == SOCKET_ERROR) {
379  }
380  } else {
382  }
383  }
386  curTime = GetTimeMillis();
387  }
388  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
389 }
390 
393 {
394  std::string username;
395  std::string password;
396 };
397 
399 static std::string Socks5ErrorString(uint8_t err)
400 {
401  switch(err) {
403  return "general failure";
405  return "connection not allowed";
407  return "network unreachable";
409  return "host unreachable";
411  return "connection refused";
413  return "TTL expired";
415  return "protocol error";
417  return "address type not supported";
418  default:
419  return "unknown";
420  }
421 }
422 
441 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, const SOCKET& hSocket)
442 {
443  IntrRecvError recvr;
444  LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
445  if (strDest.size() > 255) {
446  return error("Hostname too long");
447  }
448  // Construct the version identifier/method selection message
449  std::vector<uint8_t> vSocks5Init;
450  vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
451  if (auth) {
452  vSocks5Init.push_back(0x02); // 2 method identifiers follow...
453  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
454  vSocks5Init.push_back(SOCKS5Method::USER_PASS);
455  } else {
456  vSocks5Init.push_back(0x01); // 1 method identifier follows...
457  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
458  }
459  ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
460  if (ret != (ssize_t)vSocks5Init.size()) {
461  return error("Error sending to proxy");
462  }
463  uint8_t pchRet1[2];
464  if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
465  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
466  return false;
467  }
468  if (pchRet1[0] != SOCKSVersion::SOCKS5) {
469  return error("Proxy failed to initialize");
470  }
471  if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
472  // Perform username/password authentication (as described in RFC1929)
473  std::vector<uint8_t> vAuth;
474  vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
475  if (auth->username.size() > 255 || auth->password.size() > 255)
476  return error("Proxy username or password too long");
477  vAuth.push_back(auth->username.size());
478  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
479  vAuth.push_back(auth->password.size());
480  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
481  ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
482  if (ret != (ssize_t)vAuth.size()) {
483  return error("Error sending authentication to proxy");
484  }
485  LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
486  uint8_t pchRetA[2];
487  if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
488  return error("Error reading proxy authentication response");
489  }
490  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
491  return error("Proxy authentication unsuccessful");
492  }
493  } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
494  // Perform no authentication
495  } else {
496  return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
497  }
498  std::vector<uint8_t> vSocks5;
499  vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
500  vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
501  vSocks5.push_back(0x00); // RSV Reserved must be 0
502  vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
503  vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
504  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
505  vSocks5.push_back((port >> 8) & 0xFF);
506  vSocks5.push_back((port >> 0) & 0xFF);
507  ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
508  if (ret != (ssize_t)vSocks5.size()) {
509  return error("Error sending to proxy");
510  }
511  uint8_t pchRet2[4];
512  if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
513  if (recvr == IntrRecvError::Timeout) {
514  /* If a timeout happens here, this effectively means we timed out while connecting
515  * to the remote node. This is very common for Tor, so do not print an
516  * error message. */
517  return false;
518  } else {
519  return error("Error while reading proxy response");
520  }
521  }
522  if (pchRet2[0] != SOCKSVersion::SOCKS5) {
523  return error("Proxy failed to accept request");
524  }
525  if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
526  // Failures to connect to a peer that are not proxy errors
527  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
528  return false;
529  }
530  if (pchRet2[2] != 0x00) { // Reserved field must be 0
531  return error("Error: malformed proxy response");
532  }
533  uint8_t pchRet3[256];
534  switch (pchRet2[3])
535  {
536  case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
537  case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
539  {
540  recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
541  if (recvr != IntrRecvError::OK) {
542  return error("Error reading from proxy");
543  }
544  int nRecv = pchRet3[0];
545  recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
546  break;
547  }
548  default: return error("Error: malformed proxy response");
549  }
550  if (recvr != IntrRecvError::OK) {
551  return error("Error reading from proxy");
552  }
553  if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
554  return error("Error reading from proxy");
555  }
556  LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
557  return true;
558 }
559 
567 SOCKET CreateSocket(const CService &addrConnect)
568 {
569  // Create a sockaddr from the specified service.
570  struct sockaddr_storage sockaddr;
571  socklen_t len = sizeof(sockaddr);
572  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
573  LogPrintf("Cannot create socket for %s: unsupported network\n", addrConnect.ToString());
574  return INVALID_SOCKET;
575  }
576 
577  // Create a TCP socket in the address family of the specified service.
578  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
579  if (hSocket == INVALID_SOCKET)
580  return INVALID_SOCKET;
581 
582  // Ensure that waiting for I/O on this socket won't result in undefined
583  // behavior.
584  if (!IsSelectableSocket(hSocket)) {
585  CloseSocket(hSocket);
586  LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
587  return INVALID_SOCKET;
588  }
589 
590 #ifdef SO_NOSIGPIPE
591  int set = 1;
592  // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
593  // should use the MSG_NOSIGNAL flag for every send.
594  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
595 #endif
596 
597  // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
598  SetSocketNoDelay(hSocket);
599 
600  // Set the non-blocking option on the socket.
601  if (!SetSocketNonBlocking(hSocket, true)) {
602  CloseSocket(hSocket);
603  LogPrintf("CreateSocket: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
604  }
605  return hSocket;
606 }
607 
608 template<typename... Args>
609 static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
610  std::string error_message = tfm::format(fmt, args...);
611  if (manual_connection) {
612  LogPrintf("%s\n", error_message);
613  } else {
614  LogPrint(BCLog::NET, "%s\n", error_message);
615  }
616 }
617 
630 bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET& hSocket, int nTimeout, bool manual_connection)
631 {
632  // Create a sockaddr from the specified service.
633  struct sockaddr_storage sockaddr;
634  socklen_t len = sizeof(sockaddr);
635  if (hSocket == INVALID_SOCKET) {
636  LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
637  return false;
638  }
639  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
640  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
641  return false;
642  }
643 
644  // Connect to the addrConnect service on the hSocket socket.
645  if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
646  {
647  int nErr = WSAGetLastError();
648  // WSAEINVAL is here because some legacy version of winsock uses it
649  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
650  {
651  // Connection didn't actually fail, but is being established
652  // asynchronously. Thus, use async I/O api (select/poll)
653  // synchronously to check for successful connection with a timeout.
654 #ifdef USE_POLL
655  struct pollfd pollfd = {};
656  pollfd.fd = hSocket;
657  pollfd.events = POLLIN | POLLOUT;
658  int nRet = poll(&pollfd, 1, nTimeout);
659 #else
660  struct timeval timeout = MillisToTimeval(nTimeout);
661  fd_set fdset;
662  FD_ZERO(&fdset);
663  FD_SET(hSocket, &fdset);
664  int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
665 #endif
666  // Upon successful completion, both select and poll return the total
667  // number of file descriptors that have been selected. A value of 0
668  // indicates that the call timed out and no file descriptors have
669  // been selected.
670  if (nRet == 0)
671  {
672  LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
673  return false;
674  }
675  if (nRet == SOCKET_ERROR)
676  {
677  LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
678  return false;
679  }
680 
681  // Even if the select/poll was successful, the connect might not
682  // have been successful. The reason for this failure is hidden away
683  // in the SO_ERROR for the socket in modern systems. We read it into
684  // nRet here.
685  socklen_t nRetSize = sizeof(nRet);
686  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&nRet, &nRetSize) == SOCKET_ERROR)
687  {
688  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
689  return false;
690  }
691  if (nRet != 0)
692  {
693  LogConnectFailure(manual_connection, "connect() to %s failed after select(): %s", addrConnect.ToString(), NetworkErrorString(nRet));
694  return false;
695  }
696  }
697 #ifdef WIN32
698  else if (WSAGetLastError() != WSAEISCONN)
699 #else
700  else
701 #endif
702  {
703  LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
704  return false;
705  }
706  }
707  return true;
708 }
709 
710 bool SetProxy(enum Network net, const proxyType &addrProxy) {
711  assert(net >= 0 && net < NET_MAX);
712  if (!addrProxy.IsValid())
713  return false;
714  LOCK(cs_proxyInfos);
715  proxyInfo[net] = addrProxy;
716  return true;
717 }
718 
719 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
720  assert(net >= 0 && net < NET_MAX);
721  LOCK(cs_proxyInfos);
722  if (!proxyInfo[net].IsValid())
723  return false;
724  proxyInfoOut = proxyInfo[net];
725  return true;
726 }
727 
744 bool SetNameProxy(const proxyType &addrProxy) {
745  if (!addrProxy.IsValid())
746  return false;
747  LOCK(cs_proxyInfos);
748  nameProxy = addrProxy;
749  return true;
750 }
751 
752 bool GetNameProxy(proxyType &nameProxyOut) {
753  LOCK(cs_proxyInfos);
754  if(!nameProxy.IsValid())
755  return false;
756  nameProxyOut = nameProxy;
757  return true;
758 }
759 
761  LOCK(cs_proxyInfos);
762  return nameProxy.IsValid();
763 }
764 
765 bool IsProxy(const CNetAddr &addr) {
766  LOCK(cs_proxyInfos);
767  for (int i = 0; i < NET_MAX; i++) {
768  if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
769  return true;
770  }
771  return false;
772 }
773 
789 bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, const SOCKET& hSocket, int nTimeout, bool& outProxyConnectionFailed)
790 {
791  // first connect to proxy server
792  if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout, true)) {
793  outProxyConnectionFailed = true;
794  return false;
795  }
796  // do socks negotiation
797  if (proxy.randomize_credentials) {
798  ProxyCredentials random_auth;
799  static std::atomic_int counter(0);
800  random_auth.username = random_auth.password = strprintf("%i", counter++);
801  if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) {
802  return false;
803  }
804  } else {
805  if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) {
806  return false;
807  }
808  }
809  return true;
810 }
811 
823 bool LookupSubNet(const std::string& strSubnet, CSubNet& ret)
824 {
825  if (!ValidAsCString(strSubnet)) {
826  return false;
827  }
828  size_t slash = strSubnet.find_last_of('/');
829  std::vector<CNetAddr> vIP;
830 
831  std::string strAddress = strSubnet.substr(0, slash);
832  // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just get
833  // one CNetAddr.
834  if (LookupHost(strAddress, vIP, 1, false))
835  {
836  CNetAddr network = vIP[0];
837  if (slash != strSubnet.npos)
838  {
839  std::string strNetmask = strSubnet.substr(slash + 1);
840  int32_t n;
841  if (ParseInt32(strNetmask, &n)) {
842  // If valid number, assume CIDR variable-length subnet masking
843  ret = CSubNet(network, n);
844  return ret.IsValid();
845  }
846  else // If not a valid number, try full netmask syntax
847  {
848  // Never allow lookup for netmask
849  if (LookupHost(strNetmask, vIP, 1, false)) {
850  ret = CSubNet(network, vIP[0]);
851  return ret.IsValid();
852  }
853  }
854  }
855  else
856  {
857  ret = CSubNet(network);
858  return ret.IsValid();
859  }
860  }
861  return false;
862 }
863 
864 #ifdef WIN32
865 std::string NetworkErrorString(int err)
866 {
867  wchar_t buf[256];
868  buf[0] = 0;
869  if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
870  nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
871  buf, ARRAYSIZE(buf), nullptr))
872  {
873  return strprintf("%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf), err);
874  }
875  else
876  {
877  return strprintf("Unknown error (%d)", err);
878  }
879 }
880 #else
881 std::string NetworkErrorString(int err)
882 {
883  char buf[256];
884  buf[0] = 0;
885  /* Too bad there are two incompatible implementations of the
886  * thread-safe strerror. */
887  const char *s;
888 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
889  s = strerror_r(err, buf, sizeof(buf));
890 #else /* POSIX variant always returns message in buffer */
891  s = buf;
892  if (strerror_r(err, buf, sizeof(buf)))
893  buf[0] = 0;
894 #endif
895  return strprintf("%s (%d)", s, err);
896 }
897 #endif
898 
899 bool CloseSocket(SOCKET& hSocket)
900 {
901  if (hSocket == INVALID_SOCKET)
902  return false;
903 #ifdef WIN32
904  int ret = closesocket(hSocket);
905 #else
906  int ret = close(hSocket);
907 #endif
908  if (ret) {
909  LogPrintf("Socket close failed: %d. Error: %s\n", hSocket, NetworkErrorString(WSAGetLastError()));
910  }
911  hSocket = INVALID_SOCKET;
912  return ret != SOCKET_ERROR;
913 }
914 
915 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
916 {
917  if (fNonBlocking) {
918 #ifdef WIN32
919  u_long nOne = 1;
920  if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
921 #else
922  int fFlags = fcntl(hSocket, F_GETFL, 0);
923  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
924 #endif
925  return false;
926  }
927  } else {
928 #ifdef WIN32
929  u_long nZero = 0;
930  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
931 #else
932  int fFlags = fcntl(hSocket, F_GETFL, 0);
933  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
934 #endif
935  return false;
936  }
937  }
938 
939  return true;
940 }
941 
942 bool SetSocketNoDelay(const SOCKET& hSocket)
943 {
944  int set = 1;
945  int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
946  return rc == 0;
947 }
948 
949 void InterruptSocks5(bool interrupt)
950 {
951  interruptSocks5Recv = interrupt;
952 }
#define WSAEINPROGRESS
Definition: compat.h:56
Connection refused.
Definition: netbase.cpp:302
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:296
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
Definition: netbase.cpp:630
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:253
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
#define LogPrint(category,...)
Definition: logging.h:180
Username/password.
Definition: netbase.cpp:284
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:98
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:57
GSSAPI.
Definition: netbase.cpp:283
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout, const SOCKET &hSocket)
Try to read a specified number of bytes from a socket.
Definition: netbase.cpp:342
NODISCARD bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:60
Network unreachable.
Definition: netbase.cpp:300
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args)
Definition: netbase.cpp:609
void * sockopt_arg_type
Definition: compat.h:86
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:752
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:164
bool IsInternal() const
Definition: netaddress.cpp:311
#define INVALID_SOCKET
Definition: compat.h:59
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:744
#define WSAGetLastError()
Definition: compat.h:50
No authentication required.
Definition: netbase.cpp:282
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:289
static const int SOCKS5_RECV_TIMEOUT
Definition: netbase.cpp:38
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
Definition: netbase.cpp:789
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:823
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:205
bool HaveNameProxy()
Definition: netbase.cpp:760
#define SOCKET_ERROR
Definition: compat.h:60
bool randomize_credentials
Definition: netbase.h:37
No acceptable methods.
Definition: netbase.cpp:285
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:693
#define LOCK(cs)
Definition: sync.h:218
const char * name
Definition: rest.cpp:41
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:138
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
Credentials for proxy authentication.
Definition: netbase.cpp:392
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:316
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:63
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:765
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:275
General failure.
Definition: netbase.cpp:298
Network
Definition: netaddress.h:19
static std::atomic< bool > interruptSocks5Recv(false)
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:26
static bool Socks5(const std::string &strDest, int port, const ProxyCredentials *auth, const SOCKET &hSocket)
Connect to a specified destination service through an already connected SOCKS5 proxy.
Definition: netbase.cpp:441
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:899
int nConnectTimeout
Definition: netbase.cpp:34
#define WSAEWOULDBLOCK
Definition: compat.h:53
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:399
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:281
unsigned int SOCKET
Definition: compat.h:48
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:710
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:915
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:41
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:266
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:31
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:151
Network unreachable.
Definition: netbase.cpp:301
bool IsValid() const
Definition: netaddress.cpp:883
CService proxy
Definition: netbase.h:36
bool IsValid() const
Definition: netbase.h:34
TTL expired.
Definition: netbase.cpp:303
#define WSAEINVAL
Definition: compat.h:51
static proxyType proxyInfo [NET_MAX] GUARDED_BY(cs_proxyInfos)
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:942
static RecursiveMutex cs_proxyInfos
Definition: netbase.cpp:31
#define MSG_NOSIGNAL
Definition: netbase.cpp:27
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:24
SOCKET CreateSocket(const CService &addrConnect)
Try to create a socket file descriptor with specific properties in the communications domain (address...
Definition: netbase.cpp:567
Succeeded.
Definition: netbase.cpp:297
bool SetSpecial(const std::string &strName)
Try to make this a dummy address that maps the specified onion address into IPv6 using OnionCat&#39;s ran...
Definition: netaddress.cpp:85
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:949
std::string password
Definition: netbase.cpp:395
std::string ToString() const
Definition: netaddress.cpp:750
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:719
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:881
Address type not supported.
Definition: netbase.cpp:305
Command not supported.
Definition: netbase.cpp:304
Connection not allowed by ruleset.
Definition: netbase.cpp:299
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:53
std::string username
Definition: netbase.cpp:394
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:309
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
bool fNameLookup
Definition: netbase.cpp:35
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)