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