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