Bitcoin ABC  0.26.3
P2P Digital Currency
netbase.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <memory>
22 
23 #ifndef WIN32
24 #include <fcntl.h>
25 #else
26 #include <codecvt>
27 #endif
28 
29 #ifdef USE_POLL
30 #include <poll.h>
31 #endif
32 
33 // Settings
36 static proxyType nameProxy GUARDED_BY(g_proxyinfo_mutex);
39 
40 // Need ample time for negotiation for very slow proxies such as Tor
41 // (milliseconds)
42 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
43 static std::atomic<bool> interruptSocks5Recv(false);
44 
45 std::vector<CNetAddr> WrappedGetAddrInfo(const std::string &name,
46  bool allow_lookup) {
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(
74  reinterpret_cast<sockaddr_in *>(ai_trav->ai_addr)->sin_addr);
75  }
76  if (ai_trav->ai_family == AF_INET6) {
77  assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
78  const sockaddr_in6 *s6{
79  reinterpret_cast<sockaddr_in6 *>(ai_trav->ai_addr)};
80  resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
81  }
82  ai_trav = ai_trav->ai_next;
83  }
84  freeaddrinfo(ai_res);
85 
86  return resolved_addresses;
87 }
88 
90 
91 enum Network ParseNetwork(const std::string &net_in) {
92  std::string net = ToLower(net_in);
93  if (net == "ipv4") {
94  return NET_IPV4;
95  }
96  if (net == "ipv6") {
97  return NET_IPV6;
98  }
99  if (net == "onion") {
100  return NET_ONION;
101  }
102  if (net == "tor") {
103  LogPrintf("Warning: net name 'tor' is deprecated and will be removed "
104  "in the future. You should use 'onion' instead.\n");
105  return NET_ONION;
106  }
107  if (net == "i2p") {
108  return NET_I2P;
109  }
110  return NET_UNROUTABLE;
111 }
112 
113 std::string GetNetworkName(enum Network net) {
114  switch (net) {
115  case NET_UNROUTABLE:
116  return "not_publicly_routable";
117  case NET_IPV4:
118  return "ipv4";
119  case NET_IPV6:
120  return "ipv6";
121  case NET_ONION:
122  return "onion";
123  case NET_I2P:
124  return "i2p";
125  case NET_CJDNS:
126  return "cjdns";
127  case NET_INTERNAL:
128  return "internal";
129  case NET_MAX:
130  assert(false);
131  } // no default case, so the compiler can warn about missing cases
132 
133  assert(false);
134 }
135 
136 std::vector<std::string> GetNetworkNames(bool append_unroutable) {
137  std::vector<std::string> names;
138  for (int n = 0; n < NET_MAX; ++n) {
139  const enum Network network { static_cast<Network>(n) };
140  if (network == NET_UNROUTABLE || network == NET_CJDNS ||
141  network == NET_INTERNAL) {
142  continue;
143  }
144  names.emplace_back(GetNetworkName(network));
145  }
146  if (append_unroutable) {
147  names.emplace_back(GetNetworkName(NET_UNROUTABLE));
148  }
149  return names;
150 }
151 
152 static bool LookupIntern(const std::string &name, std::vector<CNetAddr> &vIP,
153  unsigned int nMaxSolutions, bool fAllowLookup,
154  DNSLookupFn dns_lookup_function) {
155  vIP.clear();
156 
157  if (!ValidAsCString(name)) {
158  return false;
159  }
160 
161  {
162  CNetAddr addr;
163  // From our perspective, onion addresses are not hostnames but rather
164  // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
165  // or IPv6 colon-separated hextet notation. Since we can't use
166  // getaddrinfo to decode them and it wouldn't make sense to resolve
167  // them, we return a network address representing it instead. See
168  // CNetAddr::SetSpecial(const std::string&) for more details.
169  if (addr.SetSpecial(name)) {
170  vIP.push_back(addr);
171  return true;
172  }
173  }
174 
175  for (const CNetAddr &resolved : dns_lookup_function(name, fAllowLookup)) {
176  if (nMaxSolutions > 0 && vIP.size() >= nMaxSolutions) {
177  break;
178  }
179 
180  // Never allow resolving to an internal address. Consider any such
181  // result invalid.
182  if (!resolved.IsInternal()) {
183  vIP.push_back(resolved);
184  }
185  }
186 
187  return (vIP.size() > 0);
188 }
189 
190 bool LookupHost(const std::string &name, std::vector<CNetAddr> &vIP,
191  unsigned int nMaxSolutions, bool fAllowLookup,
192  DNSLookupFn dns_lookup_function) {
193  if (!ValidAsCString(name)) {
194  return false;
195  }
196  std::string strHost = name;
197  if (strHost.empty()) {
198  return false;
199  }
200  if (strHost.front() == '[' && strHost.back() == ']') {
201  strHost = strHost.substr(1, strHost.size() - 2);
202  }
203 
204  return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup,
205  dns_lookup_function);
206 }
207 
208 bool LookupHost(const std::string &name, CNetAddr &addr, bool fAllowLookup,
209  DNSLookupFn dns_lookup_function) {
210  if (!ValidAsCString(name)) {
211  return false;
212  }
213  std::vector<CNetAddr> vIP;
214  LookupHost(name, vIP, 1, fAllowLookup, dns_lookup_function);
215  if (vIP.empty()) {
216  return false;
217  }
218  addr = vIP.front();
219  return true;
220 }
221 
222 bool Lookup(const std::string &name, std::vector<CService> &vAddr,
223  uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions,
224  DNSLookupFn dns_lookup_function) {
225  if (name.empty() || !ValidAsCString(name)) {
226  return false;
227  }
228  uint16_t port{portDefault};
229  std::string hostname;
230  SplitHostPort(name, port, hostname);
231 
232  std::vector<CNetAddr> vIP;
233  bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup,
234  dns_lookup_function);
235  if (!fRet) {
236  return false;
237  }
238  vAddr.resize(vIP.size());
239  for (unsigned int i = 0; i < vIP.size(); i++) {
240  vAddr[i] = CService(vIP[i], port);
241  }
242  return true;
243 }
244 
245 bool Lookup(const std::string &name, CService &addr, uint16_t portDefault,
246  bool fAllowLookup, DNSLookupFn dns_lookup_function) {
247  if (!ValidAsCString(name)) {
248  return false;
249  }
250  std::vector<CService> vService;
251  bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1,
252  dns_lookup_function);
253  if (!fRet) {
254  return false;
255  }
256  addr = vService[0];
257  return true;
258 }
259 
260 CService LookupNumeric(const std::string &name, uint16_t portDefault,
261  DNSLookupFn dns_lookup_function) {
262  if (!ValidAsCString(name)) {
263  return {};
264  }
265  CService addr;
266  // "1.2:345" will fail to resolve the ip, but will still set the port.
267  // If the ip fails to resolve, re-init the result.
268  if (!Lookup(name, addr, portDefault, false, dns_lookup_function)) {
269  addr = CService();
270  }
271  return addr;
272 }
273 
275 enum SOCKSVersion : uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 };
276 
278 enum SOCKS5Method : uint8_t {
279  NOAUTH = 0x00,
280  GSSAPI = 0x01,
281  USER_PASS = 0x02,
282  NO_ACCEPTABLE = 0xff,
283 };
284 
286 enum SOCKS5Command : uint8_t {
287  CONNECT = 0x01,
288  BIND = 0x02,
289  UDP_ASSOCIATE = 0x03
290 };
291 
293 enum SOCKS5Reply : uint8_t {
294  SUCCEEDED = 0x00,
295  GENFAILURE = 0x01,
296  NOTALLOWED = 0x02,
297  NETUNREACHABLE = 0x03,
299  CONNREFUSED = 0x05,
300  TTLEXPIRED = 0x06,
301  CMDUNSUPPORTED = 0x07,
303 };
304 
306 enum SOCKS5Atyp : uint8_t {
307  IPV4 = 0x01,
308  DOMAINNAME = 0x03,
309  IPV6 = 0x04,
310 };
311 
313 enum class IntrRecvError {
314  OK,
315  Timeout,
316  Disconnected,
317  NetworkError,
319 };
320 
339 static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout,
340  const Sock &sock) {
341  int64_t curTime = GetTimeMillis();
342  int64_t endTime = curTime + timeout;
343  while (len > 0 && curTime < endTime) {
344  // Optimistically try the recv first
345  ssize_t ret = sock.Recv(data, len, 0);
346  if (ret > 0) {
347  len -= ret;
348  data += ret;
349  } else if (ret == 0) {
350  // Unexpected disconnection
352  } else {
353  // Other error or blocking
354  int nErr = WSAGetLastError();
355  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
356  nErr == WSAEINVAL) {
357  // Only wait at most MAX_WAIT_FOR_IO at a time, unless
358  // we're approaching the end of the specified total timeout
359  const auto remaining =
360  std::chrono::milliseconds{endTime - curTime};
361  const auto timeout_ = std::min(
362  remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
363  if (!sock.Wait(timeout_, Sock::RECV)) {
365  }
366  } else {
368  }
369  }
370  if (interruptSocks5Recv) {
372  }
373  curTime = GetTimeMillis();
374  }
375  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
376 }
377 
380  std::string username;
381  std::string password;
382 };
383 
385 static std::string Socks5ErrorString(uint8_t err) {
386  switch (err) {
388  return "general failure";
390  return "connection not allowed";
392  return "network unreachable";
394  return "host unreachable";
396  return "connection refused";
398  return "TTL expired";
400  return "protocol error";
402  return "address type not supported";
403  default:
404  return "unknown";
405  }
406 }
407 
426 static bool Socks5(const std::string &strDest, uint16_t port,
427  const ProxyCredentials *auth, const Sock &sock) {
428  IntrRecvError recvr;
429  LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
430  if (strDest.size() > 255) {
431  return error("Hostname too long");
432  }
433  // Construct the version identifier/method selection message
434  std::vector<uint8_t> vSocks5Init;
435  // We want the SOCK5 protocol
436  vSocks5Init.push_back(SOCKSVersion::SOCKS5);
437  if (auth) {
438  // 2 method identifiers follow...
439  vSocks5Init.push_back(0x02);
440  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
441  vSocks5Init.push_back(SOCKS5Method::USER_PASS);
442  } else {
443  // 1 method identifier follows...
444  vSocks5Init.push_back(0x01);
445  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
446  }
447  ssize_t ret =
448  sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
449  if (ret != (ssize_t)vSocks5Init.size()) {
450  return error("Error sending to proxy");
451  }
452  uint8_t pchRet1[2];
453  if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, sock)) !=
455  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() "
456  "timeout or other failure\n",
457  strDest, port);
458  return false;
459  }
460  if (pchRet1[0] != SOCKSVersion::SOCKS5) {
461  return error("Proxy failed to initialize");
462  }
463  if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
464  // Perform username/password authentication (as described in RFC1929)
465  std::vector<uint8_t> vAuth;
466  // Current (and only) version of user/pass subnegotiation
467  vAuth.push_back(0x01);
468  if (auth->username.size() > 255 || auth->password.size() > 255) {
469  return error("Proxy username or password too long");
470  }
471  vAuth.push_back(auth->username.size());
472  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
473  vAuth.push_back(auth->password.size());
474  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
475  ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
476  if (ret != (ssize_t)vAuth.size()) {
477  return error("Error sending authentication to proxy");
478  }
479  LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n",
480  auth->username, auth->password);
481  uint8_t pchRetA[2];
482  if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT,
483  sock)) != IntrRecvError::OK) {
484  return error("Error reading proxy authentication response");
485  }
486  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
487  return error("Proxy authentication unsuccessful");
488  }
489  } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
490  // Perform no authentication
491  } else {
492  return error("Proxy requested wrong authentication method %02x",
493  pchRet1[1]);
494  }
495  std::vector<uint8_t> vSocks5;
496  // VER protocol version
497  vSocks5.push_back(SOCKSVersion::SOCKS5);
498  // CMD CONNECT
499  vSocks5.push_back(SOCKS5Command::CONNECT);
500  // RSV Reserved must be 0
501  vSocks5.push_back(0x00);
502  // ATYP DOMAINNAME
503  vSocks5.push_back(SOCKS5Atyp::DOMAINNAME);
504  // Length<=255 is checked at beginning of function
505  vSocks5.push_back(strDest.size());
506  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
507  vSocks5.push_back((port >> 8) & 0xFF);
508  vSocks5.push_back((port >> 0) & 0xFF);
509  ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
510  if (ret != (ssize_t)vSocks5.size()) {
511  return error("Error sending to proxy");
512  }
513  uint8_t pchRet2[4];
514  if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, sock)) !=
516  if (recvr == IntrRecvError::Timeout) {
522  return false;
523  } else {
524  return error("Error while reading proxy response");
525  }
526  }
527  if (pchRet2[0] != SOCKSVersion::SOCKS5) {
528  return error("Proxy failed to accept request");
529  }
530  if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
531  // Failures to connect to a peer that are not proxy errors
532  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port,
533  Socks5ErrorString(pchRet2[1]));
534  return false;
535  }
536  // Reserved field must be 0
537  if (pchRet2[2] != 0x00) {
538  return error("Error: malformed proxy response");
539  }
540  uint8_t pchRet3[256];
541  switch (pchRet2[3]) {
542  case SOCKS5Atyp::IPV4:
543  recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, sock);
544  break;
545  case SOCKS5Atyp::IPV6:
546  recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, sock);
547  break;
548  case SOCKS5Atyp::DOMAINNAME: {
549  recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, sock);
550  if (recvr != IntrRecvError::OK) {
551  return error("Error reading from proxy");
552  }
553  int nRecv = pchRet3[0];
554  recvr =
555  InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, sock);
556  break;
557  }
558  default:
559  return error("Error: malformed proxy response");
560  }
561  if (recvr != IntrRecvError::OK) {
562  return error("Error reading from proxy");
563  }
564  if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, sock)) !=
566  return error("Error reading from proxy");
567  }
568  LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
569  return true;
570 }
571 
572 std::unique_ptr<Sock> CreateSockTCP(const CService &address_family) {
573  // Create a sockaddr from the specified service.
574  struct sockaddr_storage sockaddr;
575  socklen_t len = sizeof(sockaddr);
576  if (!address_family.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
577  LogPrintf("Cannot create socket for %s: unsupported network\n",
578  address_family.ToString());
579  return nullptr;
580  }
581 
582  // Create a TCP socket in the address family of the specified service.
583  SOCKET hSocket = socket(((struct sockaddr *)&sockaddr)->sa_family,
584  SOCK_STREAM, IPPROTO_TCP);
585  if (hSocket == INVALID_SOCKET) {
586  return nullptr;
587  }
588 
589  // Ensure that waiting for I/O on this socket won't result in undefined
590  // behavior.
591  if (!IsSelectableSocket(hSocket)) {
592  CloseSocket(hSocket);
593  LogPrintf("Cannot create connection: non-selectable socket created (fd "
594  ">= FD_SETSIZE ?)\n");
595  return nullptr;
596  }
597 
598 #ifdef SO_NOSIGPIPE
599  int set = 1;
600  // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
601  // should use the MSG_NOSIGNAL flag for every send.
602  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (sockopt_arg_type)&set,
603  sizeof(int));
604 #endif
605 
606  // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
607  SetSocketNoDelay(hSocket);
608 
609  // Set the non-blocking option on the socket.
610  if (!SetSocketNonBlocking(hSocket, true)) {
611  CloseSocket(hSocket);
612  LogPrintf("CreateSocket: Setting socket to non-blocking "
613  "failed, error %s\n",
615  return nullptr;
616  }
617  return std::make_unique<Sock>(hSocket);
618 }
619 
620 std::function<std::unique_ptr<Sock>(const CService &)> CreateSock =
622 
623 template <typename... Args>
624 static void LogConnectFailure(bool manual_connection, const char *fmt,
625  const Args &...args) {
626  std::string error_message = tfm::format(fmt, args...);
627  if (manual_connection) {
628  LogPrintf("%s\n", error_message);
629  } else {
630  LogPrint(BCLog::NET, "%s\n", error_message);
631  }
632 }
633 
634 bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock,
635  int nTimeout, bool manual_connection) {
636  // Create a sockaddr from the specified service.
637  struct sockaddr_storage sockaddr;
638  socklen_t len = sizeof(sockaddr);
639  if (sock.Get() == INVALID_SOCKET) {
640  LogPrintf("Cannot connect to %s: invalid socket\n",
641  addrConnect.ToString());
642  return false;
643  }
644  if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
645  LogPrintf("Cannot connect to %s: unsupported network\n",
646  addrConnect.ToString());
647  return false;
648  }
649 
650  // Connect to the addrConnect service on the hSocket socket.
651  if (sock.Connect(reinterpret_cast<struct sockaddr *>(&sockaddr), len) ==
652  SOCKET_ERROR) {
653  int nErr = WSAGetLastError();
654  // WSAEINVAL is here because some legacy version of winsock uses it
655  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK ||
656  nErr == WSAEINVAL) {
657  // Connection didn't actually fail, but is being established
658  // asynchronously. Thus, use async I/O api (select/poll)
659  // synchronously to check for successful connection with a timeout.
660  const Sock::Event requested = Sock::RECV | Sock::SEND;
661  Sock::Event occurred;
662  if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested,
663  &occurred)) {
664  LogPrintf("wait for connect to %s failed: %s\n",
665  addrConnect.ToString(),
667  return false;
668  } else if (occurred == 0) {
669  LogPrint(BCLog::NET, "connection attempt to %s timed out\n",
670  addrConnect.ToString());
671  return false;
672  }
673 
674  // Even if the wait was successful, the connect might not
675  // have been successful. The reason for this failure is hidden away
676  // in the SO_ERROR for the socket in modern systems. We read it into
677  // sockerr here.
678  int sockerr;
679  socklen_t sockerr_len = sizeof(sockerr);
680  if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR,
681  (sockopt_arg_type)&sockerr,
682  &sockerr_len) == SOCKET_ERROR) {
683  LogPrintf("getsockopt() for %s failed: %s\n",
684  addrConnect.ToString(),
686  return false;
687  }
688  if (sockerr != 0) {
690  manual_connection, "connect() to %s failed after wait: %s",
691  addrConnect.ToString(), NetworkErrorString(sockerr));
692  return false;
693  }
694  }
695 #ifdef WIN32
696  else if (WSAGetLastError() != WSAEISCONN)
697 #else
698  else
699 #endif
700  {
701  LogConnectFailure(manual_connection, "connect() to %s failed: %s",
702  addrConnect.ToString(),
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  }
716  proxyInfo[net] = addrProxy;
717  return true;
718 }
719 
720 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
721  assert(net >= 0 && net < NET_MAX);
723  if (!proxyInfo[net].IsValid()) {
724  return false;
725  }
726  proxyInfoOut = proxyInfo[net];
727  return true;
728 }
729 
730 bool SetNameProxy(const proxyType &addrProxy) {
731  if (!addrProxy.IsValid()) {
732  return false;
733  }
735  nameProxy = addrProxy;
736  return true;
737 }
738 
739 bool GetNameProxy(proxyType &nameProxyOut) {
741  if (!nameProxy.IsValid()) {
742  return false;
743  }
744  nameProxyOut = nameProxy;
745  return true;
746 }
747 
750  return nameProxy.IsValid();
751 }
752 
753 bool IsProxy(const CNetAddr &addr) {
755  for (int i = 0; i < NET_MAX; i++) {
756  if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) {
757  return true;
758  }
759  }
760  return false;
761 }
762 
763 bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest,
764  uint16_t port, const Sock &sock, int nTimeout,
765  bool &outProxyConnectionFailed) {
766  // first connect to proxy server
767  if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
768  outProxyConnectionFailed = true;
769  return false;
770  }
771  // do socks negotiation
772  if (proxy.randomize_credentials) {
773  ProxyCredentials random_auth;
774  static std::atomic_int counter(0);
775  random_auth.username = random_auth.password =
776  strprintf("%i", counter++);
777  if (!Socks5(strDest, port, &random_auth, sock)) {
778  return false;
779  }
780  } else if (!Socks5(strDest, port, 0, sock)) {
781  return false;
782  }
783  return true;
784 }
785 
786 bool LookupSubNet(const std::string &strSubnet, CSubNet &ret,
787  DNSLookupFn dns_lookup_function) {
788  if (!ValidAsCString(strSubnet)) {
789  return false;
790  }
791  size_t slash = strSubnet.find_last_of('/');
792  std::vector<CNetAddr> vIP;
793 
794  std::string strAddress = strSubnet.substr(0, slash);
795  // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just
796  if (LookupHost(strAddress, vIP, 1, false, dns_lookup_function)) {
797  CNetAddr network = vIP[0];
798  if (slash != strSubnet.npos) {
799  std::string strNetmask = strSubnet.substr(slash + 1);
800  uint8_t n;
801  if (ParseUInt8(strNetmask, &n)) {
802  // If valid number, assume CIDR variable-length subnet masking
803  ret = CSubNet(network, n);
804  return ret.IsValid();
805  } else {
806  // If not a valid number, try full netmask syntax
807  // Never allow lookup for netmask
808  if (LookupHost(strNetmask, vIP, 1, false,
809  dns_lookup_function)) {
810  ret = CSubNet(network, vIP[0]);
811  return ret.IsValid();
812  }
813  }
814  } else {
815  ret = CSubNet(network);
816  return ret.IsValid();
817  }
818  }
819  return false;
820 }
821 
822 bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking) {
823  if (fNonBlocking) {
824 #ifdef WIN32
825  u_long nOne = 1;
826  if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
827 #else
828  int fFlags = fcntl(hSocket, F_GETFL, 0);
829  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
830 #endif
831  return false;
832  }
833  } else {
834 #ifdef WIN32
835  u_long nZero = 0;
836  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
837 #else
838  int fFlags = fcntl(hSocket, F_GETFL, 0);
839  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
840 #endif
841  return false;
842  }
843  }
844 
845  return true;
846 }
847 
848 bool SetSocketNoDelay(const SOCKET &hSocket) {
849  int set = 1;
850  int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY,
851  (sockopt_arg_type)&set, sizeof(int));
852  return rc == 0;
853 }
854 
855 void InterruptSocks5(bool interrupt) {
856  interruptSocks5Recv = interrupt;
857 }
858 
859 bool IsBadPort(uint16_t port) {
860  // Don't forget to update doc/p2p-bad-ports.md if you change this list.
861 
862  switch (port) {
863  case 1: // tcpmux
864  case 7: // echo
865  case 9: // discard
866  case 11: // systat
867  case 13: // daytime
868  case 15: // netstat
869  case 17: // qotd
870  case 19: // chargen
871  case 20: // ftp data
872  case 21: // ftp access
873  case 22: // ssh
874  case 23: // telnet
875  case 25: // smtp
876  case 37: // time
877  case 42: // name
878  case 43: // nicname
879  case 53: // domain
880  case 69: // tftp
881  case 77: // priv-rjs
882  case 79: // finger
883  case 87: // ttylink
884  case 95: // supdup
885  case 101: // hostname
886  case 102: // iso-tsap
887  case 103: // gppitnp
888  case 104: // acr-nema
889  case 109: // pop2
890  case 110: // pop3
891  case 111: // sunrpc
892  case 113: // auth
893  case 115: // sftp
894  case 117: // uucp-path
895  case 119: // nntp
896  case 123: // NTP
897  case 135: // loc-srv /epmap
898  case 137: // netbios
899  case 139: // netbios
900  case 143: // imap2
901  case 161: // snmp
902  case 179: // BGP
903  case 389: // ldap
904  case 427: // SLP (Also used by Apple Filing Protocol)
905  case 465: // smtp+ssl
906  case 512: // print / exec
907  case 513: // login
908  case 514: // shell
909  case 515: // printer
910  case 526: // tempo
911  case 530: // courier
912  case 531: // chat
913  case 532: // netnews
914  case 540: // uucp
915  case 548: // AFP (Apple Filing Protocol)
916  case 554: // rtsp
917  case 556: // remotefs
918  case 563: // nntp+ssl
919  case 587: // smtp (rfc6409)
920  case 601: // syslog-conn (rfc3195)
921  case 636: // ldap+ssl
922  case 989: // ftps-data
923  case 990: // ftps
924  case 993: // ldap+ssl
925  case 995: // pop3+ssl
926  case 1719: // h323gatestat
927  case 1720: // h323hostcall
928  case 1723: // pptp
929  case 2049: // nfs
930  case 3659: // apple-sasl / PasswordServer
931  case 4045: // lockd
932  case 5060: // sip
933  case 5061: // sips
934  case 6000: // X11
935  case 6566: // sane-port
936  case 6665: // Alternate IRC
937  case 6666: // Alternate IRC
938  case 6667: // Standard IRC
939  case 6668: // Alternate IRC
940  case 6669: // Alternate IRC
941  case 6697: // IRC + TLS
942  case 10080: // Amanda
943  return true;
944  }
945  return false;
946 }
Network address.
Definition: netaddress.h:121
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:227
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
std::string ToString() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
bool IsValid() const
Different type to mark Mutex at global scope.
Definition: sync.h:144
RAII helper class that manages a socket.
Definition: sock.h:26
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:63
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition: sock.h:128
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
uint8_t Event
Definition: sock.h:116
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:122
virtual SOCKET Get() const
Get the value of the contained socket.
Definition: sock.cpp:49
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition: sock.cpp:75
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:71
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:67
bool IsValid() const
Definition: netbase.h:38
CService proxy
Definition: netbase.h:40
bool randomize_credentials
Definition: netbase.h:41
#define INVALID_SOCKET
Definition: compat.h:52
#define WSAEWOULDBLOCK
Definition: compat.h:45
#define WSAEINVAL
Definition: compat.h:43
#define SOCKET_ERROR
Definition: compat.h:53
#define WSAGetLastError()
Definition: compat.h:42
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:102
#define MSG_NOSIGNAL
Definition: compat.h:113
unsigned int SOCKET
Definition: compat.h:40
void * sockopt_arg_type
Definition: compat.h:87
#define WSAEINPROGRESS
Definition: compat.h:49
#define LogPrint(category,...)
Definition: logging.h:210
#define LogPrintf(...)
Definition: logging.h:206
@ PROXY
Definition: logging.h:55
@ NET
Definition: logging.h:40
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1112
Network
A network type.
Definition: netaddress.h:44
@ NET_I2P
I2P.
Definition: netaddress.h:59
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:62
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:66
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:313
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:306
@ DOMAINNAME
Definition: netbase.cpp:308
@ IPV4
Definition: netbase.cpp:307
@ IPV6
Definition: netbase.cpp:309
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:286
@ UDP_ASSOCIATE
Definition: netbase.cpp:289
@ CONNECT
Definition: netbase.cpp:287
@ BIND
Definition: netbase.cpp:288
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:739
std::unique_ptr< Sock > CreateSockTCP(const CService &address_family)
Create a TCP socket in the given address family.
Definition: netbase.cpp:572
static std::atomic< bool > interruptSocks5Recv(false)
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:113
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &...args)
Definition: netbase.cpp:624
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:275
@ SOCKS4
Definition: netbase.cpp:275
@ SOCKS5
Definition: netbase.cpp:275
static 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:426
bool HaveNameProxy()
Definition: netbase.cpp:748
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:720
static const int SOCKS5_RECV_TIMEOUT
Definition: netbase.cpp:42
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:786
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Definition: netbase.cpp:152
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
Definition: netbase.cpp:848
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:763
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:339
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:91
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:278
@ GSSAPI
GSSAPI.
Definition: netbase.cpp:280
@ NOAUTH
No authentication required.
Definition: netbase.cpp:279
@ USER_PASS
Username/password.
Definition: netbase.cpp:281
@ NO_ACCEPTABLE
No acceptable methods.
Definition: netbase.cpp:282
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
Definition: netbase.cpp:45
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:385
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:855
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:634
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:293
@ TTLEXPIRED
TTL expired.
Definition: netbase.cpp:300
@ CMDUNSUPPORTED
Command not supported.
Definition: netbase.cpp:301
@ NETUNREACHABLE
Network unreachable.
Definition: netbase.cpp:297
@ GENFAILURE
General failure.
Definition: netbase.cpp:295
@ CONNREFUSED
Connection refused.
Definition: netbase.cpp:299
@ SUCCEEDED
Succeeded.
Definition: netbase.cpp:294
@ ATYPEUNSUPPORTED
Address type not supported.
Definition: netbase.cpp:302
@ NOTALLOWED
Connection not allowed by ruleset.
Definition: netbase.cpp:296
@ HOSTUNREACHABLE
Network unreachable.
Definition: netbase.cpp:298
static GlobalMutex g_proxyinfo_mutex
Definition: netbase.cpp:34
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:620
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:222
bool fNameLookup
Definition: netbase.cpp:38
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
int nConnectTimeout
Definition: netbase.cpp:37
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:136
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:730
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:822
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:260
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:753
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
Definition: netbase.cpp:859
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:89
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:190
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:710
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:29
std::function< std::vector< CNetAddr >(const std::string &, bool)> DNSLookupFn
Definition: netbase.h:83
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:27
const char * name
Definition: rest.cpp:48
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:331
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: sock.cpp:353
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:19
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:80
Credentials for proxy authentication.
Definition: netbase.cpp:379
std::string username
Definition: netbase.cpp:380
std::string password
Definition: netbase.cpp:381
#define LOCK(cs)
Definition: sync.h:306
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
assert(!tx.IsCoinBase())