Master Core  v0.0.9 - 2abfd2849db8ba7a83957c64eb976b406713c123
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
netbase.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT/X11 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 "util.h"
12 
13 #ifndef WIN32
14 #include <fcntl.h>
15 #endif
16 
17 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
18 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
19 
20 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
21 #define MSG_NOSIGNAL 0
22 #endif
23 
24 using namespace std;
25 
26 // Settings
30 int nConnectTimeout = 5000;
31 bool fNameLookup = false;
32 
33 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
34 
35 enum Network ParseNetwork(std::string net) {
36  boost::to_lower(net);
37  if (net == "ipv4") return NET_IPV4;
38  if (net == "ipv6") return NET_IPV6;
39  if (net == "tor") return NET_TOR;
40  return NET_UNROUTABLE;
41 }
42 
43 void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
44  size_t colon = in.find_last_of(':');
45  // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
46  bool fHaveColon = colon != in.npos;
47  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
48  bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
49  if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
50  char *endp = NULL;
51  int n = strtol(in.c_str() + colon + 1, &endp, 10);
52  if (endp && *endp == 0 && n >= 0) {
53  in = in.substr(0, colon);
54  if (n > 0 && n < 0x10000)
55  portOut = n;
56  }
57  }
58  if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
59  hostOut = in.substr(1, in.size()-2);
60  else
61  hostOut = in;
62 }
63 
64 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
65 {
66  vIP.clear();
67 
68  {
69  CNetAddr addr;
70  if (addr.SetSpecial(std::string(pszName))) {
71  vIP.push_back(addr);
72  return true;
73  }
74  }
75 
76  struct addrinfo aiHint;
77  memset(&aiHint, 0, sizeof(struct addrinfo));
78 
79  aiHint.ai_socktype = SOCK_STREAM;
80  aiHint.ai_protocol = IPPROTO_TCP;
81  aiHint.ai_family = AF_UNSPEC;
82 #ifdef WIN32
83  aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
84 #else
85  aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
86 #endif
87  struct addrinfo *aiRes = NULL;
88  int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
89  if (nErr)
90  return false;
91 
92  struct addrinfo *aiTrav = aiRes;
93  while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
94  {
95  if (aiTrav->ai_family == AF_INET)
96  {
97  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
98  vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
99  }
100 
101  if (aiTrav->ai_family == AF_INET6)
102  {
103  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
104  vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
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 (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
121  {
122  strHost = strHost.substr(1, strHost.size() - 2);
123  }
124 
125  return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
126 }
127 
128 bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
129 {
130  return LookupHost(pszName, vIP, nMaxSolutions, false);
131 }
132 
133 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
134 {
135  if (pszName[0] == 0)
136  return false;
137  int port = portDefault;
138  std::string hostname = "";
139  SplitHostPort(std::string(pszName), port, hostname);
140 
141  std::vector<CNetAddr> vIP;
142  bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
143  if (!fRet)
144  return false;
145  vAddr.resize(vIP.size());
146  for (unsigned int i = 0; i < vIP.size(); i++)
147  vAddr[i] = CService(vIP[i], port);
148  return true;
149 }
150 
151 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
152 {
153  std::vector<CService> vService;
154  bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
155  if (!fRet)
156  return false;
157  addr = vService[0];
158  return true;
159 }
160 
161 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
162 {
163  return Lookup(pszName, addr, portDefault, false);
164 }
165 
166 bool static Socks4(const CService &addrDest, SOCKET& hSocket)
167 {
168  LogPrintf("SOCKS4 connecting %s\n", addrDest.ToString());
169  if (!addrDest.IsIPv4())
170  {
171  closesocket(hSocket);
172  return error("Proxy destination is not IPv4");
173  }
174  char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
175  struct sockaddr_in addr;
176  socklen_t len = sizeof(addr);
177  if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
178  {
179  closesocket(hSocket);
180  return error("Cannot get proxy destination address");
181  }
182  memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
183  memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
184  char* pszSocks4 = pszSocks4IP;
185  int nSize = sizeof(pszSocks4IP);
186 
187  int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
188  if (ret != nSize)
189  {
190  closesocket(hSocket);
191  return error("Error sending to proxy");
192  }
193  char pchRet[8];
194  if (recv(hSocket, pchRet, 8, 0) != 8)
195  {
196  closesocket(hSocket);
197  return error("Error reading proxy response");
198  }
199  if (pchRet[1] != 0x5a)
200  {
201  closesocket(hSocket);
202  if (pchRet[1] != 0x5b)
203  LogPrintf("ERROR: Proxy returned error %d\n", pchRet[1]);
204  return false;
205  }
206  LogPrintf("SOCKS4 connected %s\n", addrDest.ToString());
207  return true;
208 }
209 
210 bool static Socks5(string strDest, int port, SOCKET& hSocket)
211 {
212  LogPrintf("SOCKS5 connecting %s\n", strDest);
213  if (strDest.size() > 255)
214  {
215  closesocket(hSocket);
216  return error("Hostname too long");
217  }
218  char pszSocks5Init[] = "\5\1\0";
219  ssize_t nSize = sizeof(pszSocks5Init) - 1;
220 
221  ssize_t ret = send(hSocket, pszSocks5Init, nSize, MSG_NOSIGNAL);
222  if (ret != nSize)
223  {
224  closesocket(hSocket);
225  return error("Error sending to proxy");
226  }
227  char pchRet1[2];
228  if (recv(hSocket, pchRet1, 2, 0) != 2)
229  {
230  closesocket(hSocket);
231  return error("Error reading proxy response");
232  }
233  if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
234  {
235  closesocket(hSocket);
236  return error("Proxy failed to initialize");
237  }
238  string strSocks5("\5\1");
239  strSocks5 += '\000'; strSocks5 += '\003';
240  strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
241  strSocks5 += strDest;
242  strSocks5 += static_cast<char>((port >> 8) & 0xFF);
243  strSocks5 += static_cast<char>((port >> 0) & 0xFF);
244  ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
245  if (ret != (ssize_t)strSocks5.size())
246  {
247  closesocket(hSocket);
248  return error("Error sending to proxy");
249  }
250  char pchRet2[4];
251  if (recv(hSocket, pchRet2, 4, 0) != 4)
252  {
253  closesocket(hSocket);
254  return error("Error reading proxy response");
255  }
256  if (pchRet2[0] != 0x05)
257  {
258  closesocket(hSocket);
259  return error("Proxy failed to accept request");
260  }
261  if (pchRet2[1] != 0x00)
262  {
263  closesocket(hSocket);
264  switch (pchRet2[1])
265  {
266  case 0x01: return error("Proxy error: general failure");
267  case 0x02: return error("Proxy error: connection not allowed");
268  case 0x03: return error("Proxy error: network unreachable");
269  case 0x04: return error("Proxy error: host unreachable");
270  case 0x05: return error("Proxy error: connection refused");
271  case 0x06: return error("Proxy error: TTL expired");
272  case 0x07: return error("Proxy error: protocol error");
273  case 0x08: return error("Proxy error: address type not supported");
274  default: return error("Proxy error: unknown");
275  }
276  }
277  if (pchRet2[2] != 0x00)
278  {
279  closesocket(hSocket);
280  return error("Error: malformed proxy response");
281  }
282  char pchRet3[256];
283  switch (pchRet2[3])
284  {
285  case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
286  case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
287  case 0x03:
288  {
289  ret = recv(hSocket, pchRet3, 1, 0) != 1;
290  if (ret) {
291  closesocket(hSocket);
292  return error("Error reading from proxy");
293  }
294  int nRecv = pchRet3[0];
295  ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
296  break;
297  }
298  default: closesocket(hSocket); return error("Error: malformed proxy response");
299  }
300  if (ret)
301  {
302  closesocket(hSocket);
303  return error("Error reading from proxy");
304  }
305  if (recv(hSocket, pchRet3, 2, 0) != 2)
306  {
307  closesocket(hSocket);
308  return error("Error reading from proxy");
309  }
310  LogPrintf("SOCKS5 connected %s\n", strDest);
311  return true;
312 }
313 
314 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
315 {
316  hSocketRet = INVALID_SOCKET;
317 
318  struct sockaddr_storage sockaddr;
319  socklen_t len = sizeof(sockaddr);
320  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
321  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
322  return false;
323  }
324 
325  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
326  if (hSocket == INVALID_SOCKET)
327  return false;
328 #ifdef SO_NOSIGPIPE
329  int set = 1;
330  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
331 #endif
332 
333 #ifdef WIN32
334  u_long fNonblock = 1;
335  if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
336 #else
337  int fFlags = fcntl(hSocket, F_GETFL, 0);
338  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
339 #endif
340  {
341  closesocket(hSocket);
342  return false;
343  }
344 
345  if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
346  {
347  // WSAEINVAL is here because some legacy version of winsock uses it
349  {
350  struct timeval timeout;
351  timeout.tv_sec = nTimeout / 1000;
352  timeout.tv_usec = (nTimeout % 1000) * 1000;
353 
354  fd_set fdset;
355  FD_ZERO(&fdset);
356  FD_SET(hSocket, &fdset);
357  int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
358  if (nRet == 0)
359  {
360  LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
361  closesocket(hSocket);
362  return false;
363  }
364  if (nRet == SOCKET_ERROR)
365  {
366  LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
367  closesocket(hSocket);
368  return false;
369  }
370  socklen_t nRetSize = sizeof(nRet);
371 #ifdef WIN32
372  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
373 #else
374  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
375 #endif
376  {
377  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
378  closesocket(hSocket);
379  return false;
380  }
381  if (nRet != 0)
382  {
383  LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
384  closesocket(hSocket);
385  return false;
386  }
387  }
388 #ifdef WIN32
389  else if (WSAGetLastError() != WSAEISCONN)
390 #else
391  else
392 #endif
393  {
394  LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
395  closesocket(hSocket);
396  return false;
397  }
398  }
399 
400  // this isn't even strictly necessary
401  // CNode::ConnectNode immediately turns the socket back to non-blocking
402  // but we'll turn it back to blocking just in case
403 #ifdef WIN32
404  fNonblock = 0;
405  if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
406 #else
407  fFlags = fcntl(hSocket, F_GETFL, 0);
408  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
409 #endif
410  {
411  closesocket(hSocket);
412  return false;
413  }
414 
415  hSocketRet = hSocket;
416  return true;
417 }
418 
419 bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
420  assert(net >= 0 && net < NET_MAX);
421  if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
422  return false;
423  if (nSocksVersion != 0 && !addrProxy.IsValid())
424  return false;
425  LOCK(cs_proxyInfos);
426  proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
427  return true;
428 }
429 
430 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
431  assert(net >= 0 && net < NET_MAX);
432  LOCK(cs_proxyInfos);
433  if (!proxyInfo[net].second)
434  return false;
435  proxyInfoOut = proxyInfo[net];
436  return true;
437 }
438 
439 bool SetNameProxy(CService addrProxy, int nSocksVersion) {
440  if (nSocksVersion != 0 && nSocksVersion != 5)
441  return false;
442  if (nSocksVersion != 0 && !addrProxy.IsValid())
443  return false;
444  LOCK(cs_proxyInfos);
445  nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
446  return true;
447 }
448 
449 bool GetNameProxy(proxyType &nameproxyInfoOut) {
450  LOCK(cs_proxyInfos);
451  if (!nameproxyInfo.second)
452  return false;
453  nameproxyInfoOut = nameproxyInfo;
454  return true;
455 }
456 
458  LOCK(cs_proxyInfos);
459  return nameproxyInfo.second != 0;
460 }
461 
462 bool IsProxy(const CNetAddr &addr) {
463  LOCK(cs_proxyInfos);
464  for (int i = 0; i < NET_MAX; i++) {
465  if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
466  return true;
467  }
468  return false;
469 }
470 
471 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
472 {
473  proxyType proxy;
474 
475  // no proxy needed
476  if (!GetProxy(addrDest.GetNetwork(), proxy))
477  return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
478 
479  SOCKET hSocket = INVALID_SOCKET;
480 
481  // first connect to proxy server
482  if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
483  return false;
484 
485  // do socks negotiation
486  switch (proxy.second) {
487  case 4:
488  if (!Socks4(addrDest, hSocket))
489  return false;
490  break;
491  case 5:
492  if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
493  return false;
494  break;
495  default:
496  closesocket(hSocket);
497  return false;
498  }
499 
500  hSocketRet = hSocket;
501  return true;
502 }
503 
504 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
505 {
506  string strDest;
507  int port = portDefault;
508  SplitHostPort(string(pszDest), port, strDest);
509 
510  SOCKET hSocket = INVALID_SOCKET;
511 
512  proxyType nameproxy;
513  GetNameProxy(nameproxy);
514 
515  CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
516  if (addrResolved.IsValid()) {
517  addr = addrResolved;
518  return ConnectSocket(addr, hSocketRet, nTimeout);
519  }
520  addr = CService("0.0.0.0:0");
521  if (!nameproxy.second)
522  return false;
523  if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
524  return false;
525 
526  switch(nameproxy.second) {
527  default:
528  case 4:
529  closesocket(hSocket);
530  return false;
531  case 5:
532  if (!Socks5(strDest, port, hSocket))
533  return false;
534  break;
535  }
536 
537  hSocketRet = hSocket;
538  return true;
539 }
540 
542 {
543  memset(ip, 0, sizeof(ip));
544 }
545 
546 void CNetAddr::SetIP(const CNetAddr& ipIn)
547 {
548  memcpy(ip, ipIn.ip, sizeof(ip));
549 }
550 
551 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
552 
553 bool CNetAddr::SetSpecial(const std::string &strName)
554 {
555  if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
556  std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
557  if (vchAddr.size() != 16-sizeof(pchOnionCat))
558  return false;
559  memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
560  for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
561  ip[i + sizeof(pchOnionCat)] = vchAddr[i];
562  return true;
563  }
564  return false;
565 }
566 
568 {
569  Init();
570 }
571 
572 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
573 {
574  memcpy(ip, pchIPv4, 12);
575  memcpy(ip+12, &ipv4Addr, 4);
576 }
577 
578 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
579 {
580  memcpy(ip, &ipv6Addr, 16);
581 }
582 
583 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
584 {
585  Init();
586  std::vector<CNetAddr> vIP;
587  if (LookupHost(pszIp, vIP, 1, fAllowLookup))
588  *this = vIP[0];
589 }
590 
591 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
592 {
593  Init();
594  std::vector<CNetAddr> vIP;
595  if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
596  *this = vIP[0];
597 }
598 
599 unsigned int CNetAddr::GetByte(int n) const
600 {
601  return ip[15-n];
602 }
603 
604 bool CNetAddr::IsIPv4() const
605 {
606  return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
607 }
608 
609 bool CNetAddr::IsIPv6() const
610 {
611  return (!IsIPv4() && !IsTor());
612 }
613 
615 {
616  return IsIPv4() && (
617  GetByte(3) == 10 ||
618  (GetByte(3) == 192 && GetByte(2) == 168) ||
619  (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
620 }
621 
623 {
624  return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
625 }
626 
628 {
629  return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
630 }
631 
633 {
634  return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
635 }
636 
638 {
639  static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
640  return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
641 }
642 
644 {
645  return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
646 }
647 
649 {
650  static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
651  return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
652 }
653 
655 {
656  return ((GetByte(15) & 0xFE) == 0xFC);
657 }
658 
660 {
661  static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
662  return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
663 }
664 
666 {
667  return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
668 }
669 
670 bool CNetAddr::IsTor() const
671 {
672  return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
673 }
674 
675 bool CNetAddr::IsLocal() const
676 {
677  // IPv4 loopback
678  if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
679  return true;
680 
681  // IPv6 loopback (::1/128)
682  static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
683  if (memcmp(ip, pchLocal, 16) == 0)
684  return true;
685 
686  return false;
687 }
688 
690 {
691  return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
692  || (GetByte(15) == 0xFF);
693 }
694 
695 bool CNetAddr::IsValid() const
696 {
697  // Cleanup 3-byte shifted addresses caused by garbage in size field
698  // of addr messages from versions before 0.2.9 checksum.
699  // Two consecutive addr messages look like this:
700  // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
701  // so if the first length field is garbled, it reads the second batch
702  // of addr misaligned by 3 bytes.
703  if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
704  return false;
705 
706  // unspecified IPv6 address (::/128)
707  unsigned char ipNone[16] = {};
708  if (memcmp(ip, ipNone, 16) == 0)
709  return false;
710 
711  // documentation IPv6 address
712  if (IsRFC3849())
713  return false;
714 
715  if (IsIPv4())
716  {
717  // INADDR_NONE
718  uint32_t ipNone = INADDR_NONE;
719  if (memcmp(ip+12, &ipNone, 4) == 0)
720  return false;
721 
722  // 0
723  ipNone = 0;
724  if (memcmp(ip+12, &ipNone, 4) == 0)
725  return false;
726  }
727 
728  return true;
729 }
730 
732 {
733  return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
734 }
735 
737 {
738  if (!IsRoutable())
739  return NET_UNROUTABLE;
740 
741  if (IsIPv4())
742  return NET_IPV4;
743 
744  if (IsTor())
745  return NET_TOR;
746 
747  return NET_IPV6;
748 }
749 
750 std::string CNetAddr::ToStringIP() const
751 {
752  if (IsTor())
753  return EncodeBase32(&ip[6], 10) + ".onion";
754  CService serv(*this, 0);
755  struct sockaddr_storage sockaddr;
756  socklen_t socklen = sizeof(sockaddr);
757  if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
758  char name[1025] = "";
759  if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
760  return std::string(name);
761  }
762  if (IsIPv4())
763  return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
764  else
765  return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
766  GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
767  GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
768  GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
769  GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
770 }
771 
772 std::string CNetAddr::ToString() const
773 {
774  return ToStringIP();
775 }
776 
777 bool operator==(const CNetAddr& a, const CNetAddr& b)
778 {
779  return (memcmp(a.ip, b.ip, 16) == 0);
780 }
781 
782 bool operator!=(const CNetAddr& a, const CNetAddr& b)
783 {
784  return (memcmp(a.ip, b.ip, 16) != 0);
785 }
786 
787 bool operator<(const CNetAddr& a, const CNetAddr& b)
788 {
789  return (memcmp(a.ip, b.ip, 16) < 0);
790 }
791 
792 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
793 {
794  if (!IsIPv4())
795  return false;
796  memcpy(pipv4Addr, ip+12, 4);
797  return true;
798 }
799 
800 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
801 {
802  memcpy(pipv6Addr, ip, 16);
803  return true;
804 }
805 
806 // get canonical identifier of an address' group
807 // no two connections will be attempted to addresses with the same group
808 std::vector<unsigned char> CNetAddr::GetGroup() const
809 {
810  std::vector<unsigned char> vchRet;
811  int nClass = NET_IPV6;
812  int nStartByte = 0;
813  int nBits = 16;
814 
815  // all local addresses belong to the same group
816  if (IsLocal())
817  {
818  nClass = 255;
819  nBits = 0;
820  }
821 
822  // all unroutable addresses belong to the same group
823  if (!IsRoutable())
824  {
825  nClass = NET_UNROUTABLE;
826  nBits = 0;
827  }
828  // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
829  // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
830  else if (IsIPv4() || IsRFC6145() || IsRFC6052())
831  {
832  nClass = NET_IPV4;
833  nStartByte = 12;
834  }
835  // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
836  else if (IsRFC3964())
837  {
838  nClass = NET_IPV4;
839  nStartByte = 2;
840  }
841  // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
842  else if (IsRFC4380())
843  {
844  vchRet.push_back(NET_IPV4);
845  vchRet.push_back(GetByte(3) ^ 0xFF);
846  vchRet.push_back(GetByte(2) ^ 0xFF);
847  return vchRet;
848  }
849  else if (IsTor())
850  {
851  nClass = NET_TOR;
852  nStartByte = 6;
853  nBits = 4;
854  }
855  // for he.net, use /36 groups
856  else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
857  nBits = 36;
858  // for the rest of the IPv6 network, use /32 groups
859  else
860  nBits = 32;
861 
862  vchRet.push_back(nClass);
863  while (nBits >= 8)
864  {
865  vchRet.push_back(GetByte(15 - nStartByte));
866  nStartByte++;
867  nBits -= 8;
868  }
869  if (nBits > 0)
870  vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
871 
872  return vchRet;
873 }
874 
875 uint64_t CNetAddr::GetHash() const
876 {
877  uint256 hash = Hash(&ip[0], &ip[16]);
878  uint64_t nRet;
879  memcpy(&nRet, &hash, sizeof(nRet));
880  return nRet;
881 }
882 
883 void CNetAddr::print() const
884 {
885  LogPrintf("CNetAddr(%s)\n", ToString());
886 }
887 
888 // private extensions to enum Network, only returned by GetExtNetwork,
889 // and only used in GetReachabilityFrom
890 static const int NET_UNKNOWN = NET_MAX + 0;
891 static const int NET_TEREDO = NET_MAX + 1;
892 int static GetExtNetwork(const CNetAddr *addr)
893 {
894  if (addr == NULL)
895  return NET_UNKNOWN;
896  if (addr->IsRFC4380())
897  return NET_TEREDO;
898  return addr->GetNetwork();
899 }
900 
902 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
903 {
904  enum Reachability {
905  REACH_UNREACHABLE,
906  REACH_DEFAULT,
907  REACH_TEREDO,
908  REACH_IPV6_WEAK,
909  REACH_IPV4,
910  REACH_IPV6_STRONG,
911  REACH_PRIVATE
912  };
913 
914  if (!IsRoutable())
915  return REACH_UNREACHABLE;
916 
917  int ourNet = GetExtNetwork(this);
918  int theirNet = GetExtNetwork(paddrPartner);
919  bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
920 
921  switch(theirNet) {
922  case NET_IPV4:
923  switch(ourNet) {
924  default: return REACH_DEFAULT;
925  case NET_IPV4: return REACH_IPV4;
926  }
927  case NET_IPV6:
928  switch(ourNet) {
929  default: return REACH_DEFAULT;
930  case NET_TEREDO: return REACH_TEREDO;
931  case NET_IPV4: return REACH_IPV4;
932  case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
933  }
934  case NET_TOR:
935  switch(ourNet) {
936  default: return REACH_DEFAULT;
937  case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
938  case NET_TOR: return REACH_PRIVATE;
939  }
940  case NET_TEREDO:
941  switch(ourNet) {
942  default: return REACH_DEFAULT;
943  case NET_TEREDO: return REACH_TEREDO;
944  case NET_IPV6: return REACH_IPV6_WEAK;
945  case NET_IPV4: return REACH_IPV4;
946  }
947  case NET_UNKNOWN:
948  case NET_UNROUTABLE:
949  default:
950  switch(ourNet) {
951  default: return REACH_DEFAULT;
952  case NET_TEREDO: return REACH_TEREDO;
953  case NET_IPV6: return REACH_IPV6_WEAK;
954  case NET_IPV4: return REACH_IPV4;
955  case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
956  }
957  }
958 }
959 
961 {
962  port = 0;
963 }
964 
966 {
967  Init();
968 }
969 
970 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
971 {
972 }
973 
974 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
975 {
976 }
977 
978 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
979 {
980 }
981 
982 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
983 {
984  assert(addr.sin_family == AF_INET);
985 }
986 
987 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
988 {
989  assert(addr.sin6_family == AF_INET6);
990 }
991 
992 bool CService::SetSockAddr(const struct sockaddr *paddr)
993 {
994  switch (paddr->sa_family) {
995  case AF_INET:
996  *this = CService(*(const struct sockaddr_in*)paddr);
997  return true;
998  case AF_INET6:
999  *this = CService(*(const struct sockaddr_in6*)paddr);
1000  return true;
1001  default:
1002  return false;
1003  }
1004 }
1005 
1006 CService::CService(const char *pszIpPort, bool fAllowLookup)
1007 {
1008  Init();
1009  CService ip;
1010  if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1011  *this = ip;
1012 }
1013 
1014 CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
1015 {
1016  Init();
1017  CService ip;
1018  if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1019  *this = ip;
1020 }
1021 
1022 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1023 {
1024  Init();
1025  CService ip;
1026  if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1027  *this = ip;
1028 }
1029 
1030 CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
1031 {
1032  Init();
1033  CService ip;
1034  if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1035  *this = ip;
1036 }
1037 
1038 unsigned short CService::GetPort() const
1039 {
1040  return port;
1041 }
1042 
1043 bool operator==(const CService& a, const CService& b)
1044 {
1045  return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1046 }
1047 
1048 bool operator!=(const CService& a, const CService& b)
1049 {
1050  return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1051 }
1052 
1053 bool operator<(const CService& a, const CService& b)
1054 {
1055  return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1056 }
1057 
1058 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1059 {
1060  if (IsIPv4()) {
1061  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1062  return false;
1063  *addrlen = sizeof(struct sockaddr_in);
1064  struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1065  memset(paddrin, 0, *addrlen);
1066  if (!GetInAddr(&paddrin->sin_addr))
1067  return false;
1068  paddrin->sin_family = AF_INET;
1069  paddrin->sin_port = htons(port);
1070  return true;
1071  }
1072  if (IsIPv6()) {
1073  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1074  return false;
1075  *addrlen = sizeof(struct sockaddr_in6);
1076  struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1077  memset(paddrin6, 0, *addrlen);
1078  if (!GetIn6Addr(&paddrin6->sin6_addr))
1079  return false;
1080  paddrin6->sin6_family = AF_INET6;
1081  paddrin6->sin6_port = htons(port);
1082  return true;
1083  }
1084  return false;
1085 }
1086 
1087 std::vector<unsigned char> CService::GetKey() const
1088 {
1089  std::vector<unsigned char> vKey;
1090  vKey.resize(18);
1091  memcpy(&vKey[0], ip, 16);
1092  vKey[16] = port / 0x100;
1093  vKey[17] = port & 0x0FF;
1094  return vKey;
1095 }
1096 
1097 std::string CService::ToStringPort() const
1098 {
1099  return strprintf("%u", port);
1100 }
1101 
1102 std::string CService::ToStringIPPort() const
1103 {
1104  if (IsIPv4() || IsTor()) {
1105  return ToStringIP() + ":" + ToStringPort();
1106  } else {
1107  return "[" + ToStringIP() + "]:" + ToStringPort();
1108  }
1109 }
1110 
1111 std::string CService::ToString() const
1112 {
1113  return ToStringIPPort();
1114 }
1115 
1116 void CService::print() const
1117 {
1118  LogPrintf("CService(%s)\n", ToString());
1119 }
1120 
1121 void CService::SetPort(unsigned short portIn)
1122 {
1123  port = portIn;
1124 }
1125 
1126 #ifdef WIN32
1127 std::string NetworkErrorString(int err)
1128 {
1129  char buf[256];
1130  buf[0] = 0;
1131  if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1132  NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1133  buf, sizeof(buf), NULL))
1134  {
1135  return strprintf("%s (%d)", buf, err);
1136  }
1137  else
1138  {
1139  return strprintf("Unknown error (%d)", err);
1140  }
1141 }
1142 #else
1143 std::string NetworkErrorString(int err)
1144 {
1145  char buf[256];
1146  const char *s = buf;
1147  buf[0] = 0;
1148  /* Too bad there are two incompatible implementations of the
1149  * thread-safe strerror. */
1150 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1151  s = strerror_r(err, buf, sizeof(buf));
1152 #else /* POSIX variant always returns message in buffer */
1153  (void) strerror_r(err, buf, sizeof(buf));
1154 #endif
1155  return strprintf("%s (%d)", s, err);
1156 }
1157 #endif
1158 
#define WSAEINPROGRESS
Definition: compat.h:55
bool IsRFC4843() const
Definition: netbase.cpp:665
unsigned short GetPort() const
Definition: netbase.cpp:1038
void SetIP(const CNetAddr &ip)
Definition: netbase.cpp:546
static bool ConnectSocketDirectly(const CService &addrConnect, SOCKET &hSocketRet, int nTimeout)
Definition: netbase.cpp:314
uint64_t GetHash() const
Definition: netbase.cpp:875
bool operator<(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:787
std::string ToStringIP() const
Definition: netbase.cpp:750
void print() const
Definition: netbase.cpp:883
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Definition: netbase.cpp:800
void Init()
Definition: netbase.cpp:960
std::string ToStringIPPort() const
Definition: netbase.cpp:1102
#define closesocket(s)
Definition: compat.h:74
bool IsRFC6145() const
Definition: netbase.cpp:659
static bool Socks5(string strDest, int port, SOCKET &hSocket)
Definition: netbase.cpp:210
void SetPort(unsigned short portIn)
Definition: netbase.cpp:1121
u_int SOCKET
Definition: compat.h:47
#define strprintf
Definition: util.h:116
STL namespace.
bool LookupNumeric(const char *pszName, CService &addr, int portDefault)
Definition: netbase.cpp:161
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout)
Definition: netbase.cpp:504
bool IsRFC4380() const
Definition: netbase.cpp:643
#define INVALID_SOCKET
Definition: compat.h:58
static const unsigned char pchIPv4[12]
Definition: netbase.cpp:33
bool IsIPv6() const
Definition: netbase.cpp:609
#define WSAGetLastError()
Definition: compat.h:49
bool IsLocal() const
Definition: netbase.cpp:675
static CCriticalSection cs_proxyInfos
Definition: netbase.cpp:29
unsigned int GetByte(int n) const
Definition: netbase.cpp:599
bool IsRFC3927() const
Definition: netbase.cpp:622
CService()
Definition: netbase.cpp:965
bool HaveNameProxy()
Definition: netbase.cpp:457
bool IsRFC4862() const
Definition: netbase.cpp:648
bool IsIPv4() const
Definition: netbase.cpp:604
#define SOCKET_ERROR
Definition: compat.h:59
bool IsRFC1918() const
Definition: netbase.cpp:614
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:777
int GetReachabilityFrom(const CNetAddr *paddrPartner=NULL) const
Calculates a metric for how reachable (*this) is from a given partner.
Definition: netbase.cpp:902
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:35
#define LogPrintf(...)
Definition: util.h:117
static bool LookupIntern(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:64
bool IsRFC3964() const
Definition: netbase.cpp:632
bool IsMulticast() const
Definition: netbase.cpp:689
static int LogPrint(const char *category, const char *format)
Definition: util.h:143
bool IsValid() const
Definition: netbase.cpp:695
#define LOCK(cs)
Definition: sync.h:156
bool IsRFC4193() const
Definition: netbase.cpp:654
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netbase.h:94
unsigned short port
Definition: netbase.h:97
static bool error(const char *format)
Definition: util.h:148
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:462
string EncodeBase32(const unsigned char *pch, size_t len)
Definition: util.cpp:687
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout)
Definition: netbase.cpp:471
static int GetExtNetwork(const CNetAddr *addr)
Definition: netbase.cpp:892
bool SetNameProxy(CService addrProxy, int nSocksVersion)
Definition: netbase.cpp:439
std::string ToString() const
Definition: netbase.cpp:1111
bool IsTor() const
Definition: netbase.cpp:670
uint256 Hash(const T1 pbegin, const T1 pend)
Definition: hash.h:19
#define MSG_NOSIGNAL
Definition: util.h:76
void Init()
Definition: netbase.cpp:541
bool IsRFC6052() const
Definition: netbase.cpp:637
bool IsRoutable() const
Definition: netbase.cpp:731
int nConnectTimeout
Definition: netbase.cpp:30
#define WSAEWOULDBLOCK
Definition: compat.h:52
bool GetInAddr(struct in_addr *pipv4Addr) const
Definition: netbase.cpp:792
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:43
Network
Definition: netbase.h:26
std::vector< unsigned char > GetGroup() const
Definition: netbase.cpp:808
static const int NET_UNKNOWN
Definition: netbase.cpp:890
static proxyType nameproxyInfo
Definition: netbase.cpp:28
void print() const
Definition: netbase.cpp:1116
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netbase.h:40
static proxyType proxyInfo[NET_MAX]
Definition: netbase.cpp:27
256-bit unsigned integer
Definition: uint256.h:531
vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)
Definition: util.cpp:751
#define WSAEINVAL
Definition: compat.h:50
bool IsRFC3849() const
Definition: netbase.cpp:627
void * memcpy(void *a, const void *b, size_t c)
Definition: glibc_compat.cpp:7
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:133
static const unsigned char pchOnionCat[]
Definition: netbase.cpp:551
unsigned char ip[16]
Definition: netbase.h:43
std::pair< CService, int > proxyType
Definition: netbase.h:136
bool operator!=(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:782
bool SetSpecial(const std::string &strName)
Definition: netbase.cpp:553
static bool Socks4(const CService &addrDest, SOCKET &hSocket)
Definition: netbase.cpp:166
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:430
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:1143
std::string ToString() const
Definition: netbase.cpp:772
std::string ToStringPort() const
Definition: netbase.cpp:1097
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:115
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netbase.cpp:992
bool GetNameProxy(proxyType &nameproxyInfoOut)
Definition: netbase.cpp:449
static const int NET_TEREDO
Definition: netbase.cpp:891
bool fNameLookup
Definition: netbase.cpp:31
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netbase.cpp:1058
bool LookupHostNumeric(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions)
Definition: netbase.cpp:128
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion)
Definition: netbase.cpp:419
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:286
std::vector< unsigned char > GetKey() const
Definition: netbase.cpp:1087
enum Network GetNetwork() const
Definition: netbase.cpp:736
CNetAddr()
Definition: netbase.cpp:567