Dogecoin Core  1.14.2
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 #ifdef HAVE_CONFIG_H
7 #include "config/bitcoin-config.h"
8 #endif
9 
10 #include "netbase.h"
11 
12 #include "hash.h"
13 #include "sync.h"
14 #include "uint256.h"
15 #include "random.h"
16 #include "util.h"
17 #include "utilstrencodings.h"
18 
19 #include <atomic>
20 
21 #ifndef WIN32
22 #include <fcntl.h>
23 #endif
24 
25 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
26 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
27 
28 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
29 #define MSG_NOSIGNAL 0
30 #endif
31 
32 // Settings
33 static proxyType proxyInfo[NET_MAX];
34 static proxyType nameProxy;
35 static CCriticalSection cs_proxyInfos;
36 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
37 bool fNameLookup = DEFAULT_NAME_LOOKUP;
38 
39 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
40 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
41 static std::atomic<bool> interruptSocks5Recv(false);
42 
43 enum Network ParseNetwork(std::string net) {
44  boost::to_lower(net);
45  if (net == "ipv4") return NET_IPV4;
46  if (net == "ipv6") return NET_IPV6;
47  if (net == "tor" || net == "onion") return NET_TOR;
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_TOR: return "onion";
57  default: return "";
58  }
59 }
60 
61 void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
62  size_t colon = in.find_last_of(':');
63  // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
64  bool fHaveColon = colon != in.npos;
65  bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
66  bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
67  if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
68  int32_t n;
69  if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
70  in = in.substr(0, colon);
71  portOut = n;
72  }
73  }
74  if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
75  hostOut = in.substr(1, in.size()-2);
76  else
77  hostOut = in;
78 }
79 
80 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
81 {
82  vIP.clear();
83 
84  {
85  CNetAddr addr;
86  if (addr.SetSpecial(std::string(pszName))) {
87  vIP.push_back(addr);
88  return true;
89  }
90  }
91 
92  struct addrinfo aiHint;
93  memset(&aiHint, 0, sizeof(struct addrinfo));
94 
95  aiHint.ai_socktype = SOCK_STREAM;
96  aiHint.ai_protocol = IPPROTO_TCP;
97  aiHint.ai_family = AF_UNSPEC;
98 #ifdef WIN32
99  aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
100 #else
101  aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
102 #endif
103  struct addrinfo *aiRes = NULL;
104  int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
105  if (nErr)
106  return false;
107 
108  struct addrinfo *aiTrav = aiRes;
109  while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
110  {
111  if (aiTrav->ai_family == AF_INET)
112  {
113  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
114  vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
115  }
116 
117  if (aiTrav->ai_family == AF_INET6)
118  {
119  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
120  struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
121  vIP.push_back(CNetAddr(s6->sin6_addr, s6->sin6_scope_id));
122  }
123 
124  aiTrav = aiTrav->ai_next;
125  }
126 
127  freeaddrinfo(aiRes);
128 
129  return (vIP.size() > 0);
130 }
131 
132 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
133 {
134  std::string strHost(pszName);
135  if (strHost.empty())
136  return false;
137  if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
138  {
139  strHost = strHost.substr(1, strHost.size() - 2);
140  }
141 
142  return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
143 }
144 
145 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
146 {
147  std::vector<CNetAddr> vIP;
148  LookupHost(pszName, vIP, 1, fAllowLookup);
149  if(vIP.empty())
150  return false;
151  addr = vIP.front();
152  return true;
153 }
154 
155 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
156 {
157  if (pszName[0] == 0)
158  return false;
159  int port = portDefault;
160  std::string hostname = "";
161  SplitHostPort(std::string(pszName), port, hostname);
162 
163  std::vector<CNetAddr> vIP;
164  bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
165  if (!fRet)
166  return false;
167  vAddr.resize(vIP.size());
168  for (unsigned int i = 0; i < vIP.size(); i++)
169  vAddr[i] = CService(vIP[i], port);
170  return true;
171 }
172 
173 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
174 {
175  std::vector<CService> vService;
176  bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
177  if (!fRet)
178  return false;
179  addr = vService[0];
180  return true;
181 }
182 
183 CService LookupNumeric(const char *pszName, int portDefault)
184 {
185  CService addr;
186  // "1.2:345" will fail to resolve the ip, but will still set the port.
187  // If the ip fails to resolve, re-init the result.
188  if(!Lookup(pszName, addr, portDefault, false))
189  addr = CService();
190  return addr;
191 }
192 
193 struct timeval MillisToTimeval(int64_t nTimeout)
194 {
195  struct timeval timeout;
196  timeout.tv_sec = nTimeout / 1000;
197  timeout.tv_usec = (nTimeout % 1000) * 1000;
198  return timeout;
199 }
200 
201 enum class IntrRecvError {
202  OK,
203  Timeout,
204  Disconnected,
205  NetworkError,
207 };
208 
220 static IntrRecvError InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
221 {
222  int64_t curTime = GetTimeMillis();
223  int64_t endTime = curTime + timeout;
224  // Maximum time to wait in one select call. It will take up until this time (in millis)
225  // to break off in case of an interruption.
226  const int64_t maxWait = 1000;
227  while (len > 0 && curTime < endTime) {
228  ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
229  if (ret > 0) {
230  len -= ret;
231  data += ret;
232  } else if (ret == 0) { // Unexpected disconnection
234  } else { // Other error or blocking
235  int nErr = WSAGetLastError();
236  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
237  if (!IsSelectableSocket(hSocket)) {
239  }
240  struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
241  fd_set fdset;
242  FD_ZERO(&fdset);
243  FD_SET(hSocket, &fdset);
244  int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
245  if (nRet == SOCKET_ERROR) {
247  }
248  } else {
250  }
251  }
252  if (interruptSocks5Recv)
254  curTime = GetTimeMillis();
255  }
256  return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
257 }
258 
260 {
261  std::string username;
262  std::string password;
263 };
264 
265 std::string Socks5ErrorString(int err)
266 {
267  switch(err) {
268  case 0x01: return "general failure";
269  case 0x02: return "connection not allowed";
270  case 0x03: return "network unreachable";
271  case 0x04: return "host unreachable";
272  case 0x05: return "connection refused";
273  case 0x06: return "TTL expired";
274  case 0x07: return "protocol error";
275  case 0x08: return "address type not supported";
276  default: return "unknown";
277  }
278 }
279 
281 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
282 {
283  IntrRecvError recvr;
284  LogPrint("net", "SOCKS5 connecting %s\n", strDest);
285  if (strDest.size() > 255) {
286  CloseSocket(hSocket);
287  return error("Hostname too long");
288  }
289  // Accepted authentication methods
290  std::vector<uint8_t> vSocks5Init;
291  vSocks5Init.push_back(0x05);
292  if (auth) {
293  vSocks5Init.push_back(0x02); // # METHODS
294  vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
295  vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
296  } else {
297  vSocks5Init.push_back(0x01); // # METHODS
298  vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
299  }
300  ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
301  if (ret != (ssize_t)vSocks5Init.size()) {
302  CloseSocket(hSocket);
303  return error("Error sending to proxy");
304  }
305  char pchRet1[2];
306  if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
307  CloseSocket(hSocket);
308  LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
309  return false;
310  }
311  if (pchRet1[0] != 0x05) {
312  CloseSocket(hSocket);
313  return error("Proxy failed to initialize");
314  }
315  if (pchRet1[1] == 0x02 && auth) {
316  // Perform username/password authentication (as described in RFC1929)
317  std::vector<uint8_t> vAuth;
318  vAuth.push_back(0x01);
319  if (auth->username.size() > 255 || auth->password.size() > 255)
320  return error("Proxy username or password too long");
321  vAuth.push_back(auth->username.size());
322  vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
323  vAuth.push_back(auth->password.size());
324  vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
325  ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
326  if (ret != (ssize_t)vAuth.size()) {
327  CloseSocket(hSocket);
328  return error("Error sending authentication to proxy");
329  }
330  LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
331  char pchRetA[2];
332  if (( recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
333  CloseSocket(hSocket);
334  return error("Error reading proxy authentication response");
335  }
336  if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
337  CloseSocket(hSocket);
338  return error("Proxy authentication unsuccessful");
339  }
340  } else if (pchRet1[1] == 0x00) {
341  // Perform no authentication
342  } else {
343  CloseSocket(hSocket);
344  return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
345  }
346  std::vector<uint8_t> vSocks5;
347  vSocks5.push_back(0x05); // VER protocol version
348  vSocks5.push_back(0x01); // CMD CONNECT
349  vSocks5.push_back(0x00); // RSV Reserved
350  vSocks5.push_back(0x03); // ATYP DOMAINNAME
351  vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
352  vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
353  vSocks5.push_back((port >> 8) & 0xFF);
354  vSocks5.push_back((port >> 0) & 0xFF);
355  ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
356  if (ret != (ssize_t)vSocks5.size()) {
357  CloseSocket(hSocket);
358  return error("Error sending to proxy");
359  }
360  char pchRet2[4];
361  if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
362  CloseSocket(hSocket);
363  if (recvr == IntrRecvError::Timeout) {
364  /* If a timeout happens here, this effectively means we timed out while connecting
365  * to the remote node. This is very common for Tor, so do not print an
366  * error message. */
367  return false;
368  } else {
369  return error("Error while reading proxy response");
370  }
371  }
372  if (pchRet2[0] != 0x05) {
373  CloseSocket(hSocket);
374  return error("Proxy failed to accept request");
375  }
376  if (pchRet2[1] != 0x00) {
377  // Failures to connect to a peer that are not proxy errors
378  CloseSocket(hSocket);
379  LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
380  return false;
381  }
382  if (pchRet2[2] != 0x00) {
383  CloseSocket(hSocket);
384  return error("Error: malformed proxy response");
385  }
386  char pchRet3[256];
387  switch (pchRet2[3])
388  {
389  case 0x01: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
390  case 0x04: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
391  case 0x03:
392  {
393  recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
394  if (recvr != IntrRecvError::OK) {
395  CloseSocket(hSocket);
396  return error("Error reading from proxy");
397  }
398  int nRecv = pchRet3[0];
399  recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
400  break;
401  }
402  default: CloseSocket(hSocket); return error("Error: malformed proxy response");
403  }
404  if (recvr != IntrRecvError::OK) {
405  CloseSocket(hSocket);
406  return error("Error reading from proxy");
407  }
408  if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
409  CloseSocket(hSocket);
410  return error("Error reading from proxy");
411  }
412  LogPrint("net", "SOCKS5 connected %s\n", strDest);
413  return true;
414 }
415 
416 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
417 {
418  hSocketRet = INVALID_SOCKET;
419 
420  struct sockaddr_storage sockaddr;
421  socklen_t len = sizeof(sockaddr);
422  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
423  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
424  return false;
425  }
426 
427  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
428  if (hSocket == INVALID_SOCKET)
429  return false;
430 
431  int set = 1;
432 #ifdef SO_NOSIGPIPE
433  // Different way of disabling SIGPIPE on BSD
434  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
435 #endif
436 
437  //Disable Nagle's algorithm
438 #ifdef WIN32
439  setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
440 #else
441  setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
442 #endif
443 
444  // Set to non-blocking
445  if (!SetSocketNonBlocking(hSocket, true))
446  return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
447 
448  if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
449  {
450  int nErr = WSAGetLastError();
451  // WSAEINVAL is here because some legacy version of winsock uses it
452  if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
453  {
454  struct timeval timeout = MillisToTimeval(nTimeout);
455  fd_set fdset;
456  FD_ZERO(&fdset);
457  FD_SET(hSocket, &fdset);
458  int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
459  if (nRet == 0)
460  {
461  LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
462  CloseSocket(hSocket);
463  return false;
464  }
465  if (nRet == SOCKET_ERROR)
466  {
467  LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
468  CloseSocket(hSocket);
469  return false;
470  }
471  socklen_t nRetSize = sizeof(nRet);
472 #ifdef WIN32
473  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
474 #else
475  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
476 #endif
477  {
478  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
479  CloseSocket(hSocket);
480  return false;
481  }
482  if (nRet != 0)
483  {
484  LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
485  CloseSocket(hSocket);
486  return false;
487  }
488  }
489 #ifdef WIN32
490  else if (WSAGetLastError() != WSAEISCONN)
491 #else
492  else
493 #endif
494  {
495  LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
496  CloseSocket(hSocket);
497  return false;
498  }
499  }
500 
501  hSocketRet = hSocket;
502  return true;
503 }
504 
505 bool SetProxy(enum Network net, const proxyType &addrProxy) {
506  assert(net >= 0 && net < NET_MAX);
507  if (!addrProxy.IsValid())
508  return false;
509  LOCK(cs_proxyInfos);
510  proxyInfo[net] = addrProxy;
511  return true;
512 }
513 
514 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
515  assert(net >= 0 && net < NET_MAX);
516  LOCK(cs_proxyInfos);
517  if (!proxyInfo[net].IsValid())
518  return false;
519  proxyInfoOut = proxyInfo[net];
520  return true;
521 }
522 
523 bool SetNameProxy(const proxyType &addrProxy) {
524  if (!addrProxy.IsValid())
525  return false;
526  LOCK(cs_proxyInfos);
527  nameProxy = addrProxy;
528  return true;
529 }
530 
531 bool GetNameProxy(proxyType &nameProxyOut) {
532  LOCK(cs_proxyInfos);
533  if(!nameProxy.IsValid())
534  return false;
535  nameProxyOut = nameProxy;
536  return true;
537 }
538 
540  LOCK(cs_proxyInfos);
541  return nameProxy.IsValid();
542 }
543 
544 bool IsProxy(const CNetAddr &addr) {
545  LOCK(cs_proxyInfos);
546  for (int i = 0; i < NET_MAX; i++) {
547  if (addr == (CNetAddr)proxyInfo[i].proxy)
548  return true;
549  }
550  return false;
551 }
552 
553 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
554 {
555  SOCKET hSocket = INVALID_SOCKET;
556  // first connect to proxy server
557  if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
558  if (outProxyConnectionFailed)
559  *outProxyConnectionFailed = true;
560  return false;
561  }
562  // do socks negotiation
563  if (proxy.randomize_credentials) {
564  ProxyCredentials random_auth;
565  static std::atomic_int counter;
566  random_auth.username = random_auth.password = strprintf("%i", counter++);
567  if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
568  return false;
569  } else {
570  if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
571  return false;
572  }
573 
574  hSocketRet = hSocket;
575  return true;
576 }
577 
578 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
579 {
580  proxyType proxy;
581  if (outProxyConnectionFailed)
582  *outProxyConnectionFailed = false;
583 
584  if (GetProxy(addrDest.GetNetwork(), proxy))
585  return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
586  else // no proxy needed (none set for target network)
587  return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
588 }
589 
590 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
591 {
592  std::string strDest;
593  int port = portDefault;
594 
595  if (outProxyConnectionFailed)
596  *outProxyConnectionFailed = false;
597 
598  SplitHostPort(std::string(pszDest), port, strDest);
599 
600  proxyType proxy;
601  GetNameProxy(proxy);
602 
603  std::vector<CService> addrResolved;
604  if (Lookup(strDest.c_str(), addrResolved, port, fNameLookup && !HaveNameProxy(), 256)) {
605  if (addrResolved.size() > 0) {
606  addr = addrResolved[GetRand(addrResolved.size())];
607  return ConnectSocket(addr, hSocketRet, nTimeout);
608  }
609  }
610 
611  addr = CService();
612 
613  if (!HaveNameProxy())
614  return false;
615  return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
616 }
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  NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
662  buf, sizeof(buf), NULL))
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  const char *s = buf;
676  buf[0] = 0;
677  /* Too bad there are two incompatible implementations of the
678  * thread-safe strerror. */
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  if (strerror_r(err, buf, sizeof(buf)))
683  buf[0] = 0;
684 #endif
685  return strprintf("%s (%d)", s, err);
686 }
687 #endif
688 
689 bool CloseSocket(SOCKET& hSocket)
690 {
691  if (hSocket == INVALID_SOCKET)
692  return false;
693 #ifdef WIN32
694  int ret = closesocket(hSocket);
695 #else
696  int ret = close(hSocket);
697 #endif
698  hSocket = INVALID_SOCKET;
699  return ret != SOCKET_ERROR;
700 }
701 
702 bool SetSocketNonBlocking(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  CloseSocket(hSocket);
713  return false;
714  }
715  } else {
716 #ifdef WIN32
717  u_long nZero = 0;
718  if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
719 #else
720  int fFlags = fcntl(hSocket, F_GETFL, 0);
721  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
722 #endif
723  CloseSocket(hSocket);
724  return false;
725  }
726  }
727 
728  return true;
729 }
730 
731 void InterruptSocks5(bool interrupt)
732 {
733  interruptSocks5Recv = interrupt;
734 }
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:93
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:31
std::string ToStringIP() const
Definition: netaddress.cpp:243
bool SetSpecial(const std::string &strName)
Definition: netaddress.cpp:45
enum Network GetNetwork() const
Definition: netaddress.cpp:229
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:134
std::string ToString() const
Definition: netaddress.cpp:568
unsigned short GetPort() const
Definition: netaddress.cpp:494
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netaddress.cpp:514
bool IsValid() const
Definition: netaddress.cpp:698
bool IsValid() const
Definition: netbase.h:34
CService proxy
Definition: netbase.h:36
bool randomize_credentials
Definition: netbase.h:37
#define INVALID_SOCKET
Definition: compat.h:64
u_int SOCKET
Definition: compat.h:53
#define WSAEWOULDBLOCK
Definition: compat.h:58
#define WSAEINVAL
Definition: compat.h:56
#define SOCKET_ERROR
Definition: compat.h:65
#define WSAGetLastError()
Definition: compat.h:55
#define MSG_NOSIGNAL
Definition: compat.h:79
#define WSAEINPROGRESS
Definition: compat.h:61
Network
Definition: netaddress.h:20
@ NET_MAX
Definition: netaddress.h:26
@ NET_IPV6
Definition: netaddress.h:23
@ NET_TOR
Definition: netaddress.h:24
@ NET_IPV4
Definition: netaddress.h:22
@ NET_UNROUTABLE
Definition: netaddress.h:21
IntrRecvError
Definition: netbase.cpp:201
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:193
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
Definition: netbase.cpp:578
bool GetNameProxy(proxyType &nameProxyOut)
Definition: netbase.cpp:531
std::string Socks5ErrorString(int err)
Definition: netbase.cpp:265
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:61
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:43
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:132
bool HaveNameProxy()
Definition: netbase.cpp:539
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:514
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:618
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:155
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
Definition: netbase.cpp:590
bool SetSocketNonBlocking(SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
Definition: netbase.cpp:702
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:183
void InterruptSocks5(bool interrupt)
Definition: netbase.cpp:731
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:672
bool fNameLookup
Definition: netbase.cpp:37
int nConnectTimeout
Definition: netbase.cpp:36
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:523
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
Definition: netbase.cpp:689
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:544
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:505
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:153
std::string username
Definition: netbase.cpp:261
std::string password
Definition: netbase.cpp:262
#define LOCK(cs)
Definition: sync.h:177
#define strprintf
Definition: tinyformat.h:1047
#define LogPrint(category,...)
Definition: util.h:76
bool error(const char *fmt, const Args &... args)
Definition: util.h:87
#define LogPrintf(...)
Definition: util.h:82
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
int64_t GetTimeMillis()
Definition: utiltime.cpp:33