Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

netbase.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 <hash.h>
9 #include <sync.h>
10 #include <uint256.h>
11 #include <random.h>
12 #include <util.h>
13 #include <utilstrencodings.h>
14 
15 #include <atomic>
16 
17 #ifndef WIN32
18 #include <fcntl.h>
19 #endif
20 
21 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
22 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
23 #ifdef USE_POLL
24 #include <poll.h>
25 #endif
26 
27 #if !defined(HAVE_MSG_NOSIGNAL)
28 #define MSG_NOSIGNAL 0
29 #endif
30 
31 // Settings
33 static proxyType proxyInfo[NET_MAX] GUARDED_BY(cs_proxyInfos);
34 static proxyType nameProxy GUARDED_BY(cs_proxyInfos);
37 
38 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
39 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
40 static std::atomic<bool> interruptSocks5Recv(false);
41 
42 enum Network ParseNetwork(std::string net) {
43  boost::to_lower(net);
44  if (net == "ipv4") return NET_IPV4;
45  if (net == "ipv6") return NET_IPV6;
46  if (net == "tor" || net == "onion") return NET_TOR;
47  return NET_UNROUTABLE;
48 }
49 
50 std::string GetNetworkName(enum Network net) {
51  switch(net)
52  {
53  case NET_IPV4: return "ipv4";
54  case NET_IPV6: return "ipv6";
55  case NET_TOR: return "onion";
56  default: return "";
57  }
58 }
59 
60 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
61 {
62  vIP.clear();
63 
64  {
65  CNetAddr addr;
66  if (addr.SetSpecial(std::string(pszName))) {
67  vIP.push_back(addr);
68  return true;
69  }
70  }
71 
72  struct addrinfo aiHint;
73  memset(&aiHint, 0, sizeof(struct addrinfo));
74 
75  aiHint.ai_socktype = SOCK_STREAM;
76  aiHint.ai_protocol = IPPROTO_TCP;
77  aiHint.ai_family = AF_UNSPEC;
78 #ifdef WIN32
79  aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
80 #else
81  aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
82 #endif
83  struct addrinfo *aiRes = nullptr;
84  int nErr = getaddrinfo(pszName, nullptr, &aiHint, &aiRes);
85  if (nErr)
86  return false;
87 
88  struct addrinfo *aiTrav = aiRes;
89  while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
90  {
91  CNetAddr resolved;
92  if (aiTrav->ai_family == AF_INET)
93  {
94  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
95  resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
96  }
97 
98  if (aiTrav->ai_family == AF_INET6)
99  {
100  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
101  struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
102  resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
103  }
104  /* Never allow resolving to an internal address. Consider any such result invalid */
105  if (!resolved.IsInternal()) {
106  vIP.push_back(resolved);
107  }
108 
109  aiTrav = aiTrav->ai_next;
110  }
111 
112  freeaddrinfo(aiRes);
113 
114  return (vIP.size() > 0);
115 }
116 
117 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
118 {
119  std::string strHost(pszName);
120  if (strHost.empty())
121  return false;
122  if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
123  {
124  strHost = strHost.substr(1, strHost.size() - 2);
125  }
126 
127  return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
128 }
129 
130 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
131 {
132  std::vector<CNetAddr> vIP;
133  LookupHost(pszName, vIP, 1, fAllowLookup);
134  if(vIP.empty())
135  return false;
136  addr = vIP.front();
137  return true;
138 }
139 
140 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
141 {
142  if (pszName[0] == 0)
143  return false;
144  int port = portDefault;
145  std::string hostname = "";
146  SplitHostPort(std::string(pszName), port, hostname);
147 
148  std::vector<CNetAddr> vIP;
149  bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
150  if (!fRet)
151  return false;
152  vAddr.resize(vIP.size());
153  for (unsigned int i = 0; i < vIP.size(); i++)
154  vAddr[i] = CService(vIP[i], port);
155  return true;
156 }
157 
158 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
159 {
160  std::vector<CService> vService;
161  bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
162  if (!fRet)
163  return false;
164  addr = vService[0];
165  return true;
166 }
167 
168 CService LookupNumeric(const char *pszName, int portDefault)
169 {
170  CService addr;
171  // "1.2:345" will fail to resolve the ip, but will still set the port.
172  // If the ip fails to resolve, re-init the result.
173  if(!Lookup(pszName, addr, portDefault, false))
174  addr = CService();
175  return addr;
176 }
177 
178 struct timeval MillisToTimeval(int64_t nTimeout)
179 {
180  struct timeval timeout;
181  timeout.tv_sec = nTimeout / 1000;
182  timeout.tv_usec = (nTimeout % 1000) * 1000;
183  return timeout;
184 }
185 
187 enum SOCKSVersion: uint8_t {
188  SOCKS4 = 0x04,
189  SOCKS5 = 0x05
190 };
191 
193 enum SOCKS5Method: uint8_t {
194  NOAUTH = 0x00,
195  GSSAPI = 0x01,
196  USER_PASS = 0x02,
197  NO_ACCEPTABLE = 0xff,
198 };
199 
201 enum SOCKS5Command: uint8_t {
202  CONNECT = 0x01,
203  BIND = 0x02,
205 };
206 
208 enum SOCKS5Reply: uint8_t {
209  SUCCEEDED = 0x00,
210  GENFAILURE = 0x01,
211  NOTALLOWED = 0x02,
212  NETUNREACHABLE = 0x03,
214  CONNREFUSED = 0x05,
215  TTLEXPIRED = 0x06,
216  CMDUNSUPPORTED = 0x07,
218 };
219 
221 enum SOCKS5Atyp: uint8_t {
222  IPV4 = 0x01,
223  DOMAINNAME = 0x03,
224  IPV6 = 0x04,
225 };
226 
228 enum class IntrRecvError {
229  OK,
230  Timeout,
231  Disconnected,
232  NetworkError,
234 };
235 
247 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket)
248 {
249  int64_t curTime = GetTimeMillis();
250  int64_t endTime = curTime + timeout;
251  // Maximum time to wait in one select call. It will take up until this time (in millis)
252  // to break off in case of an interruption.
253  const int64_t maxWait = 1000;
254  while (len > 0 && curTime < endTime) {
255  ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first
256  if (ret > 0) {
257  len -= ret;
258  data += ret;
259  } else if (ret == 0) { // Unexpected disconnection
261  } else { // Other error or blocking
262  int nErr = WSAGetLastError();
263  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
264  if (!IsSelectableSocket(hSocket)) {
266  }
267  int timeout_ms = std::min(endTime - curTime, maxWait);
268 #ifdef USE_POLL
269  struct pollfd pollfd = {};
270  pollfd.fd = hSocket;
271  pollfd.events = POLLIN | POLLOUT;
272  int nRet = poll(&pollfd, 1, timeout_ms);
273 #else
274  struct timeval tval = MillisToTimeval(timeout_ms);
275  fd_set fdset;
276  FD_ZERO(&fdset);
277  FD_SET(hSocket, &fdset);
278  int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval);
279 #endif
280  if (nRet == SOCKET_ERROR) {
282  }
283  } else {
285  }
286  }
289  curTime = GetTimeMillis();
290  }
291  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
292 }
293 
296 {
297  std::string username;
298  std::string password;
299 };
300 
302 std::string Socks5ErrorString(uint8_t err)
303 {
304  switch(err) {
306  return "general failure";
308  return "connection not allowed";
310  return "network unreachable";
312  return "host unreachable";
314  return "connection refused";
316  return "TTL expired";
318  return "protocol error";
320  return "address type not supported";
321  default:
322  return "unknown";
323  }
324 }
325 
327 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, const SOCKET& hSocket)
328 {
329  IntrRecvError recvr;
330  LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
331  if (strDest.size() > 255) {
332  return error("Hostname too long");
333  }
334  // Accepted authentication methods
335  std::vector<uint8_t> vSocks5Init;
336  vSocks5Init.push_back(SOCKSVersion::SOCKS5);
337  if (auth) {
338  vSocks5Init.push_back(0x02); // Number of methods
339  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
340  vSocks5Init.push_back(SOCKS5Method::USER_PASS);
341  } else {
342  vSocks5Init.push_back(0x01); // Number of methods
343  vSocks5Init.push_back(SOCKS5Method::NOAUTH);
344  }
345  ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
346  if (ret != (ssize_t)vSocks5Init.size()) {
347  return error("Error sending to proxy");
348  }
349  uint8_t pchRet1[2];
350  if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
351  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
352  return false;
353  }
354  if (pchRet1[0] != SOCKSVersion::SOCKS5) {
355  return error("Proxy failed to initialize");
356  }
357  if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
358  // Perform username/password authentication (as described in RFC1929)
359  std::vector<uint8_t> vAuth;
360  vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
361  if (auth->username.size() > 255 || auth->password.size() > 255)
362  return error("Proxy username or password too long");
363  vAuth.push_back(auth->username.size());
364  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
365  vAuth.push_back(auth->password.size());
366  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
367  ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
368  if (ret != (ssize_t)vAuth.size()) {
369  return error("Error sending authentication to proxy");
370  }
371  LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
372  uint8_t pchRetA[2];
373  if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
374  return error("Error reading proxy authentication response");
375  }
376  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
377  return error("Proxy authentication unsuccessful");
378  }
379  } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
380  // Perform no authentication
381  } else {
382  return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
383  }
384  std::vector<uint8_t> vSocks5;
385  vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
386  vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
387  vSocks5.push_back(0x00); // RSV Reserved must be 0
388  vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
389  vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
390  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
391  vSocks5.push_back((port >> 8) & 0xFF);
392  vSocks5.push_back((port >> 0) & 0xFF);
393  ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
394  if (ret != (ssize_t)vSocks5.size()) {
395  return error("Error sending to proxy");
396  }
397  uint8_t pchRet2[4];
398  if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
399  if (recvr == IntrRecvError::Timeout) {
400  /* If a timeout happens here, this effectively means we timed out while connecting
401  * to the remote node. This is very common for Tor, so do not print an
402  * error message. */
403  return false;
404  } else {
405  return error("Error while reading proxy response");
406  }
407  }
408  if (pchRet2[0] != SOCKSVersion::SOCKS5) {
409  return error("Proxy failed to accept request");
410  }
411  if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
412  // Failures to connect to a peer that are not proxy errors
413  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
414  return false;
415  }
416  if (pchRet2[2] != 0x00) { // Reserved field must be 0
417  return error("Error: malformed proxy response");
418  }
419  uint8_t pchRet3[256];
420  switch (pchRet2[3])
421  {
422  case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
423  case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
425  {
426  recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
427  if (recvr != IntrRecvError::OK) {
428  return error("Error reading from proxy");
429  }
430  int nRecv = pchRet3[0];
431  recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
432  break;
433  }
434  default: return error("Error: malformed proxy response");
435  }
436  if (recvr != IntrRecvError::OK) {
437  return error("Error reading from proxy");
438  }
439  if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
440  return error("Error reading from proxy");
441  }
442  LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
443  return true;
444 }
445 
446 SOCKET CreateSocket(const CService &addrConnect)
447 {
448  struct sockaddr_storage sockaddr;
449  socklen_t len = sizeof(sockaddr);
450  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
451  LogPrintf("Cannot create socket for %s: unsupported network\n", addrConnect.ToString());
452  return INVALID_SOCKET;
453  }
454 
455  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
456  if (hSocket == INVALID_SOCKET)
457  return INVALID_SOCKET;
458 
459  if (!IsSelectableSocket(hSocket)) {
460  CloseSocket(hSocket);
461  LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
462  return INVALID_SOCKET;
463  }
464 
465 #ifdef SO_NOSIGPIPE
466  int set = 1;
467  // Different way of disabling SIGPIPE on BSD
468  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
469 #endif
470 
471  //Disable Nagle's algorithm
472  SetSocketNoDelay(hSocket);
473 
474  // Set to non-blocking
475  if (!SetSocketNonBlocking(hSocket, true)) {
476  CloseSocket(hSocket);
477  LogPrintf("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
478  }
479  return hSocket;
480 }
481 
482 bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET& hSocket, int nTimeout)
483 {
484  struct sockaddr_storage sockaddr;
485  socklen_t len = sizeof(sockaddr);
486  if (hSocket == INVALID_SOCKET) {
487  LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
488  return false;
489  }
490  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
491  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
492  return false;
493  }
494  if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
495  {
496  int nErr = WSAGetLastError();
497  // WSAEINVAL is here because some legacy version of winsock uses it
498  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
499  {
500 #ifdef USE_POLL
501  struct pollfd pollfd = {};
502  pollfd.fd = hSocket;
503  pollfd.events = POLLIN | POLLOUT;
504  int nRet = poll(&pollfd, 1, nTimeout);
505 #else
506  struct timeval timeout = MillisToTimeval(nTimeout);
507  fd_set fdset;
508  FD_ZERO(&fdset);
509  FD_SET(hSocket, &fdset);
510  int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
511 #endif
512  if (nRet == 0)
513  {
514  LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
515  return false;
516  }
517  if (nRet == SOCKET_ERROR)
518  {
519  LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
520  return false;
521  }
522  socklen_t nRetSize = sizeof(nRet);
523  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&nRet, &nRetSize) == SOCKET_ERROR)
524  {
525  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
526  return false;
527  }
528  if (nRet != 0)
529  {
530  LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
531  return false;
532  }
533  }
534 #ifdef WIN32
535  else if (WSAGetLastError() != WSAEISCONN)
536 #else
537  else
538 #endif
539  {
540  LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
541  return false;
542  }
543  }
544  return true;
545 }
546 
547 bool SetProxy(enum Network net, const proxyType &addrProxy) {
548  assert(net >= 0 && net < NET_MAX);
549  if (!addrProxy.IsValid())
550  return false;
552  proxyInfo[net] = addrProxy;
553  return true;
554 }
555 
556 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
557  assert(net >= 0 && net < NET_MAX);
559  if (!proxyInfo[net].IsValid())
560  return false;
561  proxyInfoOut = proxyInfo[net];
562  return true;
563 }
564 
565 bool SetNameProxy(const proxyType &addrProxy) {
566  if (!addrProxy.IsValid())
567  return false;
569  nameProxy = addrProxy;
570  return true;
571 }
572 
573 bool GetNameProxy(proxyType &nameProxyOut) {
575  if(!nameProxy.IsValid())
576  return false;
577  nameProxyOut = nameProxy;
578  return true;
579 }
580 
583  return nameProxy.IsValid();
584 }
585 
586 bool IsProxy(const CNetAddr &addr) {
588  for (int i = 0; i < NET_MAX; i++) {
589  if (addr == (CNetAddr)proxyInfo[i].proxy)
590  return true;
591  }
592  return false;
593 }
594 
595 bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, const SOCKET& hSocket, int nTimeout, bool *outProxyConnectionFailed)
596 {
597  // first connect to proxy server
598  if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
599  if (outProxyConnectionFailed)
600  *outProxyConnectionFailed = true;
601  return false;
602  }
603  // do socks negotiation
604  if (proxy.randomize_credentials) {
605  ProxyCredentials random_auth;
606  static std::atomic_int counter(0);
607  random_auth.username = random_auth.password = strprintf("%i", counter++);
608  if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) {
609  return false;
610  }
611  } else {
612  if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) {
613  return false;
614  }
615  }
616  return true;
617 }
618 bool LookupSubNet(const char* pszName, CSubNet& ret)
619 {
620  std::string strSubnet(pszName);
621  size_t slash = strSubnet.find_last_of('/');
622  std::vector<CNetAddr> vIP;
623 
624  std::string strAddress = strSubnet.substr(0, slash);
625  if (LookupHost(strAddress.c_str(), vIP, 1, false))
626  {
627  CNetAddr network = vIP[0];
628  if (slash != strSubnet.npos)
629  {
630  std::string strNetmask = strSubnet.substr(slash + 1);
631  int32_t n;
632  // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
633  if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
634  ret = CSubNet(network, n);
635  return ret.IsValid();
636  }
637  else // If not a valid number, try full netmask syntax
638  {
639  // Never allow lookup for netmask
640  if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
641  ret = CSubNet(network, vIP[0]);
642  return ret.IsValid();
643  }
644  }
645  }
646  else
647  {
648  ret = CSubNet(network);
649  return ret.IsValid();
650  }
651  }
652  return false;
653 }
654 
655 #ifdef WIN32
656 std::string NetworkErrorString(int err)
657 {
658  char buf[256];
659  buf[0] = 0;
660  if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
661  nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
662  buf, sizeof(buf), nullptr))
663  {
664  return strprintf("%s (%d)", buf, err);
665  }
666  else
667  {
668  return strprintf("Unknown error (%d)", err);
669  }
670 }
671 #else
672 std::string NetworkErrorString(int err)
673 {
674  char buf[256];
675  buf[0] = 0;
676  /* Too bad there are two incompatible implementations of the
677  * thread-safe strerror. */
678  const char *s;
679 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
680  s = strerror_r(err, buf, sizeof(buf));
681 #else /* POSIX variant always returns message in buffer */
682  s = buf;
683  if (strerror_r(err, buf, sizeof(buf)))
684  buf[0] = 0;
685 #endif
686  return strprintf("%s (%d)", s, err);
687 }
688 #endif
689 
690 bool CloseSocket(SOCKET& hSocket)
691 {
692  if (hSocket == INVALID_SOCKET)
693  return false;
694 #ifdef WIN32
695  int ret = closesocket(hSocket);
696 #else
697  int ret = close(hSocket);
698 #endif
699  if (ret) {
700  LogPrintf("Socket close failed: %d. Error: %s\n", hSocket, NetworkErrorString(WSAGetLastError()));
701  }
702  hSocket = INVALID_SOCKET;
703  return ret != SOCKET_ERROR;
704 }
705 
706 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
707 {
708  if (fNonBlocking) {
709 #ifdef WIN32
710  u_long nOne = 1;
711  if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
712 #else
713  int fFlags = fcntl(hSocket, F_GETFL, 0);
714  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
715 #endif
716  return false;
717  }
718  } else {
719 #ifdef WIN32
720  u_long nZero = 0;
721  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
722 #else
723  int fFlags = fcntl(hSocket, F_GETFL, 0);
724  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
725 #endif
726  return false;
727  }
728  }
729 
730  return true;
731 }
732 
733 bool SetSocketNoDelay(const SOCKET& hSocket)
734 {
735  int set = 1;
736  int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
737  return rc == 0;
738 }
739 
740 void InterruptSocks5(bool interrupt)
741 {
742  interruptSocks5Recv = interrupt;
743 }
#define WSAEINPROGRESS
Definition: compat.h:70
Network unreachable.
Definition: netbase.cpp:214
SOCKS5Reply
Values defined for REP in RFC1928.
Definition: netbase.cpp:208
std::string ToString(bool fUseGetnameinfo=true) const
Definition: netaddress.cpp:581
GSSAPI.
Definition: netbase.cpp:196
static bool IsSelectableSocket(const SOCKET &s)
Definition: compat.h:117
No authentication required.
Definition: netbase.cpp:195
#define strprintf
Definition: tinyformat.h:1066
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout, const SOCKET &hSocket)
Read bytes from socket.
Definition: netbase.cpp:247
Connection not allowed by ruleset.
Definition: netbase.cpp:212
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:168
void * sockopt_arg_type
Definition: compat.h:101
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:573
bool IsInternal() const
Definition: netaddress.cpp:239
#define INVALID_SOCKET
Definition: compat.h:73
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:565
#define WSAGetLastError()
Definition: compat.h:64
static CCriticalSection cs_proxyInfos
Definition: netbase.cpp:32
SOCKS5Command
Values defined for CMD in RFC1928.
Definition: netbase.cpp:201
static const int SOCKS5_RECV_TIMEOUT
Definition: netbase.cpp:39
std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
Definition: netbase.cpp:302
bool HaveNameProxy()
Definition: netbase.cpp:581
#define SOCKET_ERROR
Definition: compat.h:74
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:42
#define LogPrintf(...)
Definition: util.h:203
static bool LookupIntern(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:60
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout)
Definition: netbase.cpp:482
bool randomize_credentials
Definition: netbase.h:38
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
Username/password.
Definition: netbase.cpp:197
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netaddress.cpp:527
#define LOCK(cs)
Definition: sync.h:178
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:143
Credentials for proxy authentication.
Definition: netbase.cpp:295
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
Definition: netbase.cpp:228
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool *outProxyConnectionFailed)
Definition: netbase.cpp:595
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:586
SOCKSVersion
SOCKS version.
Definition: netbase.cpp:187
Succeeded.
Definition: netbase.cpp:210
Network
Definition: netaddress.h:21
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 using SOCKS5 (as described in RFC1928)
Definition: netbase.cpp:327
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:690
int nConnectTimeout
Definition: netbase.cpp:35
#define WSAEWOULDBLOCK
Definition: compat.h:67
SOCKS5Method
Values defined for METHOD in RFC1928.
Definition: netbase.cpp:193
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:618
unsigned int SOCKET
Definition: compat.h:62
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:547
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:706
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:178
#define LogPrint(category,...)
Definition: util.h:214
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:33
Network unreachable.
Definition: netbase.cpp:213
bool IsValid() const
Definition: netaddress.cpp:711
CService proxy
Definition: netbase.h:37
bool IsValid() const
Definition: netbase.h:35
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Connection refused.
Definition: netbase.cpp:215
#define WSAEINVAL
Definition: compat.h:65
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:733
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:56
#define MSG_NOSIGNAL
Definition: netbase.cpp:28
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:24
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:140
SOCKET CreateSocket(const CService &addrConnect)
Definition: netbase.cpp:446
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
bool SetSpecial(const std::string &strName)
Definition: netaddress.cpp:59
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:740
std::string password
Definition: netbase.cpp:298
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:556
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:672
Command not supported.
Definition: netbase.cpp:217
TTL expired.
Definition: netbase.cpp:216
General failure.
Definition: netbase.cpp:211
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:50
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:117
std::string username
Definition: netbase.cpp:297
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
Definition: netbase.cpp:221
bool fNameLookup
Definition: netbase.cpp:36
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
Released under the MIT license