Anoncoin  0.9.4
P2P Digital Currency
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 // Copyright (c) 2013-2015 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 // Many builder specific things set in the config file, don't forget to include it this way in your source files.
8 #ifdef HAVE_CONFIG_H
10 #endif
11 
12 #ifdef HAVE_GETADDRINFO_A
13 #include <netdb.h>
14 #endif
15 
16 #include "netbase.h"
17 
18 #include "hash.h"
19 #include "sync.h"
20 #include "uint256.h"
21 #include "util.h"
22 
23 #ifndef WIN32
24 #if HAVE_INET_PTON
25 #include <arpa/inet.h>
26 #endif
27 #include <fcntl.h>
28 #endif
29 
30 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
31 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
32 
33 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
34 #define MSG_NOSIGNAL 0
35 #endif
36 
37 using namespace std;
38 
39 // Settings
40 static proxyType proxyInfo[NET_MAX];
41 static CService nameProxy;
42 static CCriticalSection cs_proxyInfos;
43 // ToDo: Further analysis from debuging i2p connections may reveil that this setting is too low.
44 // Connected peertable entries show ping times >13000ms Changing this number's default
45 // to 4 times what Bitcoin had it set too... Or possibly add a new variable for I2p specifically.
46 // int nConnectTimeout = 5000;
47 int nConnectTimeout = 20000;
48 bool fNameLookup = false;
49 
50 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
51 
52 enum Network ParseNetwork(std::string net) {
53  boost::to_lower(net);
54  if (net == "ipv4") return NET_IPV4;
55  if (net == "ipv6") return NET_IPV6;
56  if (net == "tor" || net == "onion") return NET_TOR;
57 #ifdef ENABLE_I2PSAM
58  if (net == "i2p") return NET_NATIVE_I2P;
59 #endif
60  return NET_UNROUTABLE;
61 }
62 
63 std::string GetNetworkName(enum Network net) {
64  switch(net)
65  {
66  case NET_IPV4: return "ipv4";
67  case NET_IPV6: return "ipv6";
68  case NET_TOR: return "onion";
69 #ifdef ENABLE_I2PSAM
70  case NET_NATIVE_I2P: return "i2p";
71 #endif
72 
73  default: return "";
74  }
75 }
76 
77 void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
78  size_t colon = in.find_last_of(':');
79  // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
80  bool fHaveColon = colon != in.npos;
81  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
82  bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
83  if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
84  char *endp = NULL;
85  int n = strtol(in.c_str() + colon + 1, &endp, 10);
86  if (endp && *endp == 0 && n >= 0) {
87  in = in.substr(0, colon);
88  if (n > 0 && n < 0x10000)
89  portOut = n;
90  }
91  }
92  if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
93  hostOut = in.substr(1, in.size()-2);
94  else
95  hostOut = in;
96 }
97 
98 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
99 {
100  vIP.clear();
101 
102  {
103  CNetAddr addr;
104  std::string strName( pszName );
105  if (addr.SetSpecial(strName)) {
106  vIP.push_back(addr);
107  return true;
108  }
109 #ifdef ENABLE_I2PSAM
110  // ToDo: Possibly needs more fix'n, so we don't duplicate code that was just run from within SetSpecial(),
111  // for now that is how a problem with repeated i2p dns seed node lookups (that failed) is being solved.
112  // The dnsseed node b32 addresses are being hunted for, more than once even when it was clear that
113  // the addresss could not be looked up by this nodes i2p router. So we double check here, and
114  // if SetSpecial() returned false, then we check again, if this name string is a b32 i2p address (aka DNSSeed),
115  // then we make sure that this function returns false too, and right now, without executing all the rest of
116  // the code in this function, which could return I'm not sure what...true, which would account for the problem seen.
117  else if ( isValidI2pB32( strName ) )
118  return false; // we're done here, a dns seed node could not be found
119 #endif
120  }
121 
122 #ifdef HAVE_GETADDRINFO_A
123  struct in_addr ipv4_addr;
124 #ifdef HAVE_INET_PTON
125  if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
126  vIP.push_back(CNetAddr(ipv4_addr));
127  return true;
128  }
129 
130  struct in6_addr ipv6_addr;
131  if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
132  vIP.push_back(CNetAddr(ipv6_addr));
133  return true;
134  }
135 #else
136  ipv4_addr.s_addr = inet_addr(pszName);
137  if (ipv4_addr.s_addr != INADDR_NONE) {
138  vIP.push_back(CNetAddr(ipv4_addr));
139  return true;
140  }
141 #endif
142 #endif
143 
144  struct addrinfo aiHint;
145  memset(&aiHint, 0, sizeof(struct addrinfo));
146  aiHint.ai_socktype = SOCK_STREAM;
147  aiHint.ai_protocol = IPPROTO_TCP;
148  aiHint.ai_family = AF_UNSPEC;
149 #ifdef WIN32
150  aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
151 #else
152  aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
153 #endif
154 
155  struct addrinfo *aiRes = NULL;
156 #ifdef HAVE_GETADDRINFO_A
157  struct gaicb gcb, *query = &gcb;
158  memset(query, 0, sizeof(struct gaicb));
159  gcb.ar_name = pszName;
160  gcb.ar_request = &aiHint;
161  int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
162  if (nErr)
163  return false;
164 
165  do {
166  // Should set the timeout limit to a resonable value to avoid
167  // generating unnecessary checking call during the polling loop,
168  // while it can still response to stop request quick enough.
169  // 2 seconds looks fine in our situation.
170  struct timespec ts = { 2, 0 };
171  gai_suspend(&query, 1, &ts);
172  boost::this_thread::interruption_point();
173 
174  nErr = gai_error(query);
175  if (0 == nErr)
176  aiRes = query->ar_result;
177  } while (nErr == EAI_INPROGRESS);
178 #else
179  int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
180 #endif
181  if (nErr)
182  return false;
183 
184  struct addrinfo *aiTrav = aiRes;
185  while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
186  {
187  if (aiTrav->ai_family == AF_INET)
188  {
189  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
190  vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
191  }
192 
193  if (aiTrav->ai_family == AF_INET6)
194  {
195  assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
196  vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
197  }
198 
199  aiTrav = aiTrav->ai_next;
200  }
201 
202  freeaddrinfo(aiRes);
203 
204  return (vIP.size() > 0);
205 }
206 
207 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
208 {
209  std::string strHost(pszName);
210  if (strHost.empty())
211  return false;
212  if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
213  {
214  strHost = strHost.substr(1, strHost.size() - 2);
215  }
216 
217  return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
218 }
219 
220 bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
221 {
222  return LookupHost(pszName, vIP, nMaxSolutions, false);
223 }
224 
225 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
226 {
227  if (pszName[0] == 0)
228  return false;
229  int port = portDefault;
230  std::string hostname = "";
231  SplitHostPort(std::string(pszName), port, hostname);
232 
233  std::vector<CNetAddr> vIP;
234  bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
235  if (!fRet)
236  return false;
237  vAddr.resize(vIP.size());
238  for (unsigned int i = 0; i < vIP.size(); i++)
239  vAddr[i] = CService(vIP[i], port);
240  return true;
241 }
242 
243 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
244 {
245  std::vector<CService> vService;
246  bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
247  if (!fRet)
248  return false;
249  addr = vService[0];
250  return true;
251 }
252 
253 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
254 {
255  return Lookup(pszName, addr, portDefault, false);
256 }
257 
258 bool static Socks5(string strDest, int port, SOCKET& hSocket)
259 {
260  LogPrintf("SOCKS5 connecting %s\n", strDest);
261  if (strDest.size() > 255)
262  {
263  closesocket(hSocket);
264  return error("Hostname too long");
265  }
266  char pszSocks5Init[] = "\5\1\0";
267  ssize_t nSize = sizeof(pszSocks5Init) - 1;
268 
269  ssize_t ret = send(hSocket, pszSocks5Init, nSize, MSG_NOSIGNAL);
270  if (ret != nSize)
271  {
272  closesocket(hSocket);
273  return error("Error sending to proxy");
274  }
275  char pchRet1[2];
276  if (recv(hSocket, pchRet1, 2, 0) != 2)
277  {
278  closesocket(hSocket);
279  return error("Error reading proxy response");
280  }
281  if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
282  {
283  closesocket(hSocket);
284  return error("Proxy failed to initialize");
285  }
286  string strSocks5("\5\1");
287  strSocks5 += '\000'; strSocks5 += '\003';
288  strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
289  strSocks5 += strDest;
290  strSocks5 += static_cast<char>((port >> 8) & 0xFF);
291  strSocks5 += static_cast<char>((port >> 0) & 0xFF);
292  ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
293  if (ret != (ssize_t)strSocks5.size())
294  {
295  closesocket(hSocket);
296  return error("Error sending to proxy");
297  }
298  char pchRet2[4];
299  if (recv(hSocket, pchRet2, 4, 0) != 4)
300  {
301  closesocket(hSocket);
302  return error("Error reading proxy response");
303  }
304  if (pchRet2[0] != 0x05)
305  {
306  closesocket(hSocket);
307  return error("Proxy failed to accept request");
308  }
309  if (pchRet2[1] != 0x00)
310  {
311  closesocket(hSocket);
312  switch (pchRet2[1])
313  {
314  case 0x01: return error("Proxy error: general failure");
315  case 0x02: return error("Proxy error: connection not allowed");
316  case 0x03: return error("Proxy error: network unreachable");
317  case 0x04: return error("Proxy error: host unreachable");
318  case 0x05: return error("Proxy error: connection refused");
319  case 0x06: return error("Proxy error: TTL expired");
320  case 0x07: return error("Proxy error: protocol error");
321  case 0x08: return error("Proxy error: address type not supported");
322  default: return error("Proxy error: unknown");
323  }
324  }
325  if (pchRet2[2] != 0x00)
326  {
327  closesocket(hSocket);
328  return error("Error: malformed proxy response");
329  }
330  char pchRet3[256];
331  switch (pchRet2[3])
332  {
333  case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
334  case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
335  case 0x03:
336  {
337  ret = recv(hSocket, pchRet3, 1, 0) != 1;
338  if (ret) {
339  closesocket(hSocket);
340  return error("Error reading from proxy");
341  }
342  int nRecv = pchRet3[0];
343  ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
344  break;
345  }
346  default: closesocket(hSocket); return error("Error: malformed proxy response");
347  }
348  if (ret)
349  {
350  closesocket(hSocket);
351  return error("Error reading from proxy");
352  }
353  if (recv(hSocket, pchRet3, 2, 0) != 2)
354  {
355  closesocket(hSocket);
356  return error("Error reading from proxy");
357  }
358  LogPrintf("SOCKS5 connected %s\n", strDest);
359  return true;
360 }
361 
362 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
363 {
364  hSocketRet = INVALID_SOCKET;
365 
366  struct sockaddr_storage sockaddr;
367  socklen_t len = sizeof(sockaddr);
368  if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
369  LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
370  return false;
371  }
372 
373  SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
374  if (hSocket == INVALID_SOCKET)
375  return false;
376 #ifdef SO_NOSIGPIPE
377  int set = 1;
378  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
379 #endif
380 
381 #ifdef WIN32
382  u_long fNonblock = 1;
383  if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
384 #else
385  int fFlags = fcntl(hSocket, F_GETFL, 0);
386  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
387 #endif
388  {
389  closesocket(hSocket);
390  return false;
391  }
392 
393  if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
394  {
395  // WSAEINVAL is here because some legacy version of winsock uses it
397  {
398  struct timeval timeout;
399  timeout.tv_sec = nTimeout / 1000;
400  timeout.tv_usec = (nTimeout % 1000) * 1000;
401 
402  fd_set fdset;
403  FD_ZERO(&fdset);
404  FD_SET(hSocket, &fdset);
405  int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
406  if (nRet == 0)
407  {
408  LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
409  closesocket(hSocket);
410  return false;
411  }
412  if (nRet == SOCKET_ERROR)
413  {
414  LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
415  closesocket(hSocket);
416  return false;
417  }
418  socklen_t nRetSize = sizeof(nRet);
419 #ifdef WIN32
420  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
421 #else
422  if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
423 #endif
424  {
425  LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
426  closesocket(hSocket);
427  return false;
428  }
429  if (nRet != 0)
430  {
431  LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
432  closesocket(hSocket);
433  return false;
434  }
435  }
436 #ifdef WIN32
437  else if (WSAGetLastError() != WSAEISCONN)
438 #else
439  else
440 #endif
441  {
442  LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
443  closesocket(hSocket);
444  return false;
445  }
446  }
447 
448  // this isn't even strictly necessary
449  // CNode::ConnectNode immediately turns the socket back to non-blocking
450  // but we'll turn it back to blocking just in case
451 #ifdef WIN32
452  fNonblock = 0;
453  if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
454 #else
455  fFlags = fcntl(hSocket, F_GETFL, 0);
456  if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
457 #endif
458  {
459  closesocket(hSocket);
460  return false;
461  }
462 
463  hSocketRet = hSocket;
464  return true;
465 }
466 
467 bool SetProxy(enum Network net, CService addrProxy) {
468  assert(net >= 0 && net < NET_MAX);
469  if (!addrProxy.IsValid())
470  return false;
471  LOCK(cs_proxyInfos);
472  proxyInfo[net] = addrProxy;
473  return true;
474 }
475 
476 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
477  assert(net >= 0 && net < NET_MAX);
478  LOCK(cs_proxyInfos);
479  if (!proxyInfo[net].IsValid())
480  return false;
481  proxyInfoOut = proxyInfo[net];
482  return true;
483 }
484 
485 bool SetNameProxy(CService addrProxy) {
486  if (!addrProxy.IsValid())
487  return false;
488  LOCK(cs_proxyInfos);
489  nameProxy = addrProxy;
490  return true;
491 }
492 
493 bool GetNameProxy(CService &nameProxyOut) {
494  LOCK(cs_proxyInfos);
495  if(!nameProxy.IsValid())
496  return false;
497  nameProxyOut = nameProxy;
498  return true;
499 }
500 
502  LOCK(cs_proxyInfos);
503  return nameProxy.IsValid();
504 }
505 
506 bool IsProxy(const CNetAddr &addr) {
507  LOCK(cs_proxyInfos);
508  for (int i = 0; i < NET_MAX; i++) {
509  if (addr == (CNetAddr)proxyInfo[i])
510  return true;
511  }
512  return false;
513 }
514 
515 #ifdef ENABLE_I2PSAM
516 bool static SetI2pSocketOptions(SOCKET& hSocket)
517 {
518  if (hSocket == INVALID_SOCKET)
519  return false;
520 #ifdef SO_NOSIGPIPE
521  int set = 1;
522  setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
523 #endif
524 
525 #ifdef WIN32
526  u_long fNonblock = 1;
527  if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
528 #else
529  int fFlags = fcntl(hSocket, F_GETFL, 0);
530  if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
531 #endif
532  {
533  closesocket(hSocket);
534  hSocket = INVALID_SOCKET;
535  return false;
536  }
537  return true;
538 }
539 #endif // ENABLE_I2PSAM
540 
541 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
542 {
543  proxyType proxy;
544 
545 #ifdef ENABLE_I2PSAM
546  if (addrDest.IsNativeI2P()) {
547  SOCKET streamSocket = I2PSession::Instance().connect(addrDest.GetI2PDestination(), false/*, streamSocket*/);
548  if( SetI2pSocketOptions(streamSocket) ) {
549  hSocketRet = streamSocket;
550  return true;
551  }
552  return false;
553  }
554 #endif // ENABLE_I2PSAM
555 
556  // no proxy needed (none set for target network)
557  if (!GetProxy(addrDest.GetNetwork(), proxy))
558  return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
559 
560  SOCKET hSocket = INVALID_SOCKET;
561 
562  // first connect to proxy server
563  if (!ConnectSocketDirectly(proxy, hSocket, nTimeout))
564  return false;
565  // do socks negotiation
566  if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
567  return false;
568 
569  hSocketRet = hSocket;
570  return true;
571 }
572 
573 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
574 {
575  string strDest;
576  int port = portDefault;
577  SplitHostPort(string(pszDest), port, strDest);
578 
579  SOCKET hSocket = INVALID_SOCKET;
580 
581  CService nameProxy;
582  GetNameProxy(nameProxy);
583 
584  CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
585  if (addrResolved.IsValid()) {
586  addr = addrResolved;
587  return ConnectSocket(addr, hSocketRet, nTimeout);
588  }
589 
590  addr = CService("0.0.0.0:0");
591 
592  if (!HaveNameProxy())
593  return false;
594  // first connect to name proxy server
595  if (!ConnectSocketDirectly(nameProxy, hSocket, nTimeout))
596  return false;
597  // do socks negotiation
598  if (!Socks5(strDest, (unsigned short)port, hSocket))
599  return false;
600 
601  hSocketRet = hSocket;
602  return true;
603 }
604 
606 {
607  memset(ip, 0, sizeof(ip));
608 #ifdef ENABLE_I2PSAM
609  memset(i2pDest, 0, NATIVE_I2P_DESTINATION_SIZE);
610 #endif
611 }
612 
613 void CNetAddr::SetIP(const CNetAddr& ipIn)
614 {
615  memcpy(ip, ipIn.ip, sizeof(ip));
616 #ifdef ENABLE_I2PSAM
617  memcpy(i2pDest, ipIn.i2pDest, NATIVE_I2P_DESTINATION_SIZE);
618 #endif
619 }
620 
621 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
622 
626 bool CNetAddr::SetSpecial(const std::string &strName)
627 {
628 #ifdef ENABLE_I2PSAM
629  const bool isBase32Addr = isValidI2pB32( strName );
630 
631  if( isBase32Addr || isValidI2pAddress( strName ) ) // Perhaps we've been given a full I2P native address
632  { // We're given a possible valid .b32.i2p address or a native I2P destination
633  std::string addr;
634  if( isBase32Addr ) {
635  addr = I2PSession::Instance().namingLookup(strName); // This could take a very long while...
636  if( !isValidI2pAddress( addr ) ) return false; // Not something we can use
637  // Otherwise the I2P router was able to convert it into a I2P address we can use, and it's now stored in 'addr'
638  } else // It was a native I2P address
639  addr = strName; // Prep for memcpy()
640  // If we make it here 'addr' has the native i2p address in it...
641  memcpy(i2pDest, addr.c_str(), NATIVE_I2P_DESTINATION_SIZE); // So now copy it to our CNetAddr obect variable
642  return true; // Special handling taken care of
643  }
644 #endif // ENABLE_I2PSAM
645 
646  if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
647  std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
648  if (vchAddr.size() != 16-sizeof(pchOnionCat))
649  return false;
650  memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
651  for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
652  ip[i + sizeof(pchOnionCat)] = vchAddr[i];
653  return true;
654  }
655  return false;
656 }
657 
659 {
660  Init();
661 }
662 
663 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
664 {
665  memcpy(ip, pchIPv4, 12);
666  memcpy(ip+12, &ipv4Addr, 4);
667 #ifdef ENABLE_I2PSAM
668  memset(i2pDest, 0, NATIVE_I2P_DESTINATION_SIZE);
669 #endif
670 }
671 
672 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
673 {
674  memcpy(ip, &ipv6Addr, 16);
675 #ifdef ENABLE_I2PSAM
676  memset(i2pDest, 0, NATIVE_I2P_DESTINATION_SIZE);
677 #endif
678 }
679 
680 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
681 {
682  Init();
683  std::vector<CNetAddr> vIP;
684  if (LookupHost(pszIp, vIP, 1, fAllowLookup))
685  *this = vIP[0];
686 }
687 
688 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
689 {
690  Init();
691  std::vector<CNetAddr> vIP;
692  if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
693  *this = vIP[0];
694 }
695 
696 unsigned int CNetAddr::GetByte(int n) const
697 {
698  return ip[15-n];
699 }
700 
701 bool CNetAddr::IsIPv4() const
702 {
703  return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
704 }
705 
706 bool CNetAddr::IsIPv6() const
707 {
708 #ifdef ENABLE_I2PSAM
709  return (!IsIPv4() && !IsTor() && !IsNativeI2P());
710 #else // Original Code
711  return (!IsIPv4() && !IsTor());
712 #endif
713 }
714 
716 {
717  return IsIPv4() && (
718  GetByte(3) == 10 ||
719  (GetByte(3) == 192 && GetByte(2) == 168) ||
720  (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
721 }
722 
724 {
725  return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
726 }
727 
729 {
730  return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
731 }
732 
734 {
735  return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
736 }
737 
739 {
740  static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
741  return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
742 }
743 
745 {
746  return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
747 }
748 
750 {
751  static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
752  return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
753 }
754 
756 {
757  return ((GetByte(15) & 0xFE) == 0xFC);
758 }
759 
761 {
762  static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
763  return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
764 }
765 
767 {
768  return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
769 }
770 
771 bool CNetAddr::IsTor() const
772 {
773  return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
774 }
775 
776 #ifdef ENABLE_I2PSAM
777 bool CNetAddr::IsNativeI2P() const
778 {
779  // For unsigned char [] it's quicker here to just do a memory comparision .verses. conversion to a string.
780  // In order for this to work however, it's important that the memory has been cleared when this object
781  // was created. ToDo: investigate this and confirm it will never mistakely see a valid native i2p address.
782  static const unsigned char pchAAAA[] = {'A','A','A','A'};
783  return (memcmp(i2pDest + NATIVE_I2P_DESTINATION_SIZE - sizeof(pchAAAA), pchAAAA, sizeof(pchAAAA)) == 0);
784 }
785 
786 std::string CNetAddr::GetI2PDestination() const
787 {
788  return std::string(i2pDest, i2pDest + NATIVE_I2P_DESTINATION_SIZE);
789 }
790 #endif // ENABLE_I2PSAM
791 
792 bool CNetAddr::IsLocal() const
793 {
794 #ifdef ENABLE_I2PSAM
795  if (IsNativeI2P()) return false;
796 #endif
797 
798  // IPv4 loopback
799  if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
800  return true;
801 
802  // IPv6 loopback (::1/128)
803  static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
804  if (memcmp(ip, pchLocal, 16) == 0)
805  return true;
806 
807  return false;
808 }
809 
811 {
812  return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
813  || (GetByte(15) == 0xFF);
814 }
815 
816 bool CNetAddr::IsValid() const
817 {
818 #ifdef ENABLE_I2PSAM
819  if (IsNativeI2P()) return true;
820 #endif
821  // Cleanup 3-byte shifted addresses caused by garbage in size field
822  // of addr messages from versions before 0.2.9 checksum.
823  // Two consecutive addr messages look like this:
824  // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
825  // so if the first length field is garbled, it reads the second batch
826  // of addr misaligned by 3 bytes.
827  if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
828  return false;
829 
830  // unspecified IPv6 address (::/128)
831  unsigned char ipNone[16] = {};
832  if (memcmp(ip, ipNone, 16) == 0)
833  return false;
834 
835  // documentation IPv6 address
836  if (IsRFC3849())
837  return false;
838 
839  if (IsIPv4())
840  {
841  // INADDR_NONE
842  uint32_t ipNone = INADDR_NONE;
843  if (memcmp(ip+12, &ipNone, 4) == 0)
844  return false;
845 
846  // 0
847  ipNone = 0;
848  if (memcmp(ip+12, &ipNone, 4) == 0)
849  return false;
850  }
851 
852  return true;
853 }
854 
856 {
857 #ifdef ENABLE_I2PSAM
858  return IsNativeI2P() || (IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal()));
859 #else // Original code
860  return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
861 #endif
862 }
863 
865 {
866  if (!IsRoutable())
867  return NET_UNROUTABLE;
868 
869  if (IsIPv4())
870  return NET_IPV4;
871 
872  if (IsTor())
873  return NET_TOR;
874 
875 #ifdef ENABLE_I2PSAM
876  if (IsNativeI2P()) return NET_NATIVE_I2P;
877 #endif
878 
879  return NET_IPV6;
880 }
881 
882 std::string CNetAddr::ToStringIP() const
883 {
884 #ifdef ENABLE_I2PSAM
885  if (IsNativeI2P())
886  return GetI2PDestination();
887 #endif
888  if (IsTor())
889  return EncodeBase32(&ip[6], 10) + ".onion";
890  CService serv(*this, 0);
891  struct sockaddr_storage sockaddr;
892  socklen_t socklen = sizeof(sockaddr);
893  if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
894  char name[1025] = "";
895  if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
896  return std::string(name);
897  }
898  if (IsIPv4())
899  return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
900  else
901  return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
902  GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
903  GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
904  GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
905  GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
906 }
907 
908 std::string CNetAddr::ToString() const
909 {
910  return ToStringIP();
911 }
912 
913 bool operator==(const CNetAddr& a, const CNetAddr& b)
914 {
915 #ifdef ENABLE_I2PSAM
916  return (memcmp(a.ip, b.ip, 16) == 0 && memcmp(a.i2pDest, b.i2pDest, NATIVE_I2P_DESTINATION_SIZE) == 0);
917 #else // Use the original code
918  return (memcmp(a.ip, b.ip, 16) == 0);
919 #endif
920 }
921 
922 bool operator!=(const CNetAddr& a, const CNetAddr& b)
923 {
924 #ifdef ENABLE_I2PSAM
925  return (memcmp(a.ip, b.ip, 16) != 0 || memcmp(a.i2pDest, b.i2pDest, NATIVE_I2P_DESTINATION_SIZE) != 0);
926 #else // Use the original code
927  return (memcmp(a.ip, b.ip, 16) != 0);
928 #endif
929 }
930 
931 bool operator<(const CNetAddr& a, const CNetAddr& b)
932 {
933 #ifdef ENABLE_I2PSAM
934  return (memcmp(a.ip, b.ip, 16) < 0 || (memcmp(a.ip, b.ip, 16) == 0 && memcmp(a.i2pDest, b.i2pDest, NATIVE_I2P_DESTINATION_SIZE) < 0));
935 #else // Use the original code
936  return (memcmp(a.ip, b.ip, 16) < 0);
937 #endif
938 }
939 
940 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
941 {
942  if (!IsIPv4())
943  return false;
944  memcpy(pipv4Addr, ip+12, 4);
945  return true;
946 }
947 
948 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
949 {
950 #ifdef ENABLE_I2PSAM
951  if (IsNativeI2P()) return false;
952 #endif
953  memcpy(pipv6Addr, ip, 16);
954  return true;
955 }
956 
957 // get canonical identifier of an address' group
958 // no two connections will be attempted to addresses with the same group
959 std::vector<unsigned char> CNetAddr::GetGroup() const
960 {
961  std::vector<unsigned char> vchRet;
962  int nClass = NET_IPV6;
963  int nStartByte = 0;
964  int nBits = 16;
965 
966 #ifdef ENABLE_I2PSAM
967  if (IsNativeI2P())
968  {
969  // vchRet.push_back(NET_NATIVE_I2P);
970  // vchRet.push_back( i2pDest );
971  // ToDo: Remove this 0.8.5.6 code, and replace it with above two lines, when you've got time to test...
972  vchRet.resize(NATIVE_I2P_DESTINATION_SIZE + 1);
973  vchRet[0] = NET_NATIVE_I2P;
974  memcpy(&vchRet[1], i2pDest, NATIVE_I2P_DESTINATION_SIZE);
975  return vchRet;
976  }
977 #endif // ENABLE_I2PSAM
978 
979  // all local addresses belong to the same group
980  if (IsLocal())
981  {
982  nClass = 255;
983  nBits = 0;
984  }
985 
986  // all unroutable addresses belong to the same group
987  if (!IsRoutable())
988  {
989  nClass = NET_UNROUTABLE;
990  nBits = 0;
991  }
992  // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
993  // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
994  else if (IsIPv4() || IsRFC6145() || IsRFC6052())
995  {
996  nClass = NET_IPV4;
997  nStartByte = 12;
998  }
999  // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
1000  else if (IsRFC3964())
1001  {
1002  nClass = NET_IPV4;
1003  nStartByte = 2;
1004  }
1005  // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
1006  else if (IsRFC4380())
1007  {
1008  vchRet.push_back(NET_IPV4);
1009  vchRet.push_back(GetByte(3) ^ 0xFF);
1010  vchRet.push_back(GetByte(2) ^ 0xFF);
1011  return vchRet;
1012  }
1013  else if (IsTor())
1014  {
1015  nClass = NET_TOR;
1016  nStartByte = 6;
1017  nBits = 4;
1018  }
1019  // for he.net, use /36 groups
1020  else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
1021  nBits = 36;
1022  // for the rest of the IPv6 network, use /32 groups
1023  else
1024  nBits = 32;
1025 
1026  vchRet.push_back(nClass);
1027  while (nBits >= 8)
1028  {
1029  vchRet.push_back(GetByte(15 - nStartByte));
1030  nStartByte++;
1031  nBits -= 8;
1032  }
1033  if (nBits > 0)
1034  vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
1035 
1036  return vchRet;
1037 }
1038 
1039 uint64_t CNetAddr::GetHash() const
1040 {
1041 #ifdef ENABLE_I2PSAM
1042  uint256 hash = IsNativeI2P() ? Hash(i2pDest, i2pDest + NATIVE_I2P_DESTINATION_SIZE) : Hash(&ip[0], &ip[16]);
1043 #else // Use the original code
1044  uint256 hash = Hash(&ip[0], &ip[16]);
1045 #endif
1046  uint64_t nRet;
1047  memcpy(&nRet, &hash, sizeof(nRet));
1048  return nRet;
1049 }
1050 
1051 void CNetAddr::print() const
1052 {
1053  LogPrintf("CNetAddr(%s)\n", ToString());
1054 }
1055 
1056 // private extensions to enum Network, only returned by GetExtNetwork,
1057 // and only used in GetReachabilityFrom
1058 static const int NET_UNKNOWN = NET_MAX + 0;
1059 static const int NET_TEREDO = NET_MAX + 1;
1060 int static GetExtNetwork(const CNetAddr *addr)
1061 {
1062  if (addr == NULL)
1063  return NET_UNKNOWN;
1064  if (addr->IsRFC4380())
1065  return NET_TEREDO;
1066  return addr->GetNetwork();
1067 }
1068 
1070 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
1071 {
1072  enum Reachability {
1073  REACH_UNREACHABLE,
1074  REACH_DEFAULT,
1075  REACH_TEREDO,
1076  REACH_IPV6_WEAK,
1077  REACH_IPV4,
1078  REACH_IPV6_STRONG,
1079  REACH_PRIVATE
1080  };
1081 
1082  if (!IsRoutable())
1083  return REACH_UNREACHABLE;
1084 
1085  int ourNet = GetExtNetwork(this);
1086  int theirNet = GetExtNetwork(paddrPartner);
1087  bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
1088 
1089  switch(theirNet) {
1090  case NET_IPV4:
1091  switch(ourNet) {
1092  default: return REACH_DEFAULT;
1093  case NET_IPV4: return REACH_IPV4;
1094  }
1095  case NET_IPV6:
1096  switch(ourNet) {
1097  default: return REACH_DEFAULT;
1098  case NET_TEREDO: return REACH_TEREDO;
1099  case NET_IPV4: return REACH_IPV4;
1100  case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
1101  }
1102 #ifdef ENABLE_I2PSAM
1103  case NET_NATIVE_I2P:
1104  switch(ourNet) {
1105  default: return REACH_UNREACHABLE;
1106  case NET_NATIVE_I2P: return REACH_PRIVATE;
1107  }
1108 #endif
1109  case NET_TOR:
1110  switch(ourNet) {
1111  default: return REACH_DEFAULT;
1112  case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
1113  case NET_TOR: return REACH_PRIVATE;
1114  }
1115  case NET_TEREDO:
1116  switch(ourNet) {
1117  default: return REACH_DEFAULT;
1118  case NET_TEREDO: return REACH_TEREDO;
1119  case NET_IPV6: return REACH_IPV6_WEAK;
1120  case NET_IPV4: return REACH_IPV4;
1121  }
1122  case NET_UNKNOWN:
1123  case NET_UNROUTABLE:
1124  default:
1125  switch(ourNet) {
1126  default: return REACH_DEFAULT;
1127  case NET_TEREDO: return REACH_TEREDO;
1128  case NET_IPV6: return REACH_IPV6_WEAK;
1129  case NET_IPV4: return REACH_IPV4;
1130  case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
1131 #ifdef ENABLE_I2PSAM
1132  case NET_NATIVE_I2P: return REACH_UNREACHABLE;
1133 #endif
1134  }
1135  }
1136 }
1137 
1139 {
1140  port = 0;
1141 }
1142 
1144 {
1145  Init();
1146 }
1147 
1148 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
1149 {
1150 }
1151 
1152 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
1153 {
1154 }
1155 
1156 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
1157 {
1158 }
1159 
1160 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1161 {
1162  assert(addr.sin_family == AF_INET);
1163 }
1164 
1165 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1166 {
1167  assert(addr.sin6_family == AF_INET6);
1168 }
1169 
1170 bool CService::SetSockAddr(const struct sockaddr *paddr)
1171 {
1172  switch (paddr->sa_family) {
1173  case AF_INET:
1174  *this = CService(*(const struct sockaddr_in*)paddr);
1175  return true;
1176  case AF_INET6:
1177  *this = CService(*(const struct sockaddr_in6*)paddr);
1178  return true;
1179  default:
1180  return false;
1181  }
1182 }
1183 
1184 CService::CService(const char *pszIpPort, bool fAllowLookup)
1185 {
1186  Init();
1187  CService ip;
1188  if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1189  *this = ip;
1190 }
1191 
1192 CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
1193 {
1194  Init();
1195  CService ip;
1196  if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1197  *this = ip;
1198 }
1199 
1200 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1201 {
1202  Init();
1203  CService ip;
1204  if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1205  *this = ip;
1206 }
1207 
1208 CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
1209 {
1210  Init();
1211  CService ip;
1212  if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1213  *this = ip;
1214 }
1215 
1216 unsigned short CService::GetPort() const
1217 {
1218  return port;
1219 }
1220 
1221 bool operator==(const CService& a, const CService& b)
1222 {
1223 #ifdef ENABLE_I2PSAM
1224  return (CNetAddr)a == (CNetAddr)b && (a.port == b.port || (a.IsNativeI2P() && b.IsNativeI2P()));
1225 #else // Use the original code
1226  return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1227 #endif
1228 }
1229 
1230 bool operator!=(const CService& a, const CService& b)
1231 {
1232 #ifdef ENABLE_I2PSAM
1233  return (CNetAddr)a != (CNetAddr)b || !(a.port == b.port || (a.IsNativeI2P() && b.IsNativeI2P()));
1234 #else // Use the original code
1235  return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1236 #endif
1237 }
1238 
1239 bool operator<(const CService& a, const CService& b)
1240 {
1241 #ifdef ENABLE_I2PSAM
1242  return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && (a.port < b.port) && !(a.IsNativeI2P() && b.IsNativeI2P()));
1243 #else // Use the original code
1244  return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1245 #endif
1246 }
1247 
1248 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1249 {
1250  if (IsIPv4()) {
1251  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1252  return false;
1253  *addrlen = sizeof(struct sockaddr_in);
1254  struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1255  memset(paddrin, 0, *addrlen);
1256  if (!GetInAddr(&paddrin->sin_addr))
1257  return false;
1258  paddrin->sin_family = AF_INET;
1259  paddrin->sin_port = htons(port);
1260  return true;
1261  }
1262  if (IsIPv6()) {
1263  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1264  return false;
1265  *addrlen = sizeof(struct sockaddr_in6);
1266  struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1267  memset(paddrin6, 0, *addrlen);
1268  if (!GetIn6Addr(&paddrin6->sin6_addr))
1269  return false;
1270  paddrin6->sin6_family = AF_INET6;
1271  paddrin6->sin6_port = htons(port);
1272  return true;
1273  }
1274  return false;
1275 }
1276 
1277 std::vector<unsigned char> CService::GetKey() const
1278 {
1279  std::vector<unsigned char> vKey;
1280 #ifdef ENABLE_I2PSAM
1281  if (IsNativeI2P())
1282  {
1283  vKey.resize(NATIVE_I2P_DESTINATION_SIZE);
1284  memcpy(&vKey[0], i2pDest, NATIVE_I2P_DESTINATION_SIZE);
1285  return vKey;
1286  }
1287 #endif
1288  vKey.resize(18);
1289  memcpy(&vKey[0], ip, 16);
1290  vKey[16] = port / 0x100;
1291  vKey[17] = port & 0x0FF;
1292  return vKey;
1293 }
1294 
1295 std::string CService::ToStringPort() const
1296 {
1297  return strprintf("%u", port);
1298 }
1299 
1300 #ifdef ENABLE_I2PSAM
1301 std::string CService::ToStringI2pPort() const
1302 {
1303  if( IsNativeI2P() ) {
1304  // Convert native i2p addresses to b32.i2p addresses
1305  // ToDo: Check and/or finish this, got interupted.
1306  std::string samPort = strprintf( "%u", GetArg("-i2p.options.samport", "7656") );
1307  return "[" + B32AddressFromDestination( GetI2PDestination() ) + "]:" + samPort;
1308  }
1309  else
1310  return "Unknown address";
1311 }
1312 #endif // ENABLE_I2PSAM
1313 
1314 std::string CService::ToStringIPPort() const
1315 {
1316 #ifdef ENABLE_I2PSAM
1317  std:string PortStr = IsNativeI2P() ? GetArg("-i2p.options.samport", "7656") : ToStringPort();
1318 #else
1319  std:string PortStr = ToStringPort();
1320 #endif
1321  return ( IsIPv4() || IsTor() ) ? ToStringIP() + ":" + PortStr :
1322  "[" + ToStringIP() + "]:" + PortStr;
1323 }
1324 
1325 std::string CService::ToString() const
1326 {
1327  return ToStringIPPort();
1328 }
1329 
1330 void CService::print() const
1331 {
1332  LogPrintf("CService(%s)\n", ToString());
1333 }
1334 
1335 void CService::SetPort(unsigned short portIn)
1336 {
1337  port = portIn;
1338 }
1339 
1340 #ifdef WIN32
1341 std::string NetworkErrorString(int err)
1342 {
1343  char buf[256];
1344  buf[0] = 0;
1345  if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1346  NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1347  buf, sizeof(buf), NULL))
1348  {
1349  return strprintf("%s (%d)", buf, err);
1350  }
1351  else
1352  {
1353  return strprintf("Unknown error (%d)", err);
1354  }
1355 }
1356 #else
1357 std::string NetworkErrorString(int err)
1358 {
1359  char buf[256];
1360  const char *s = buf;
1361  buf[0] = 0;
1362  /* Too bad there are two incompatible implementations of the
1363  * thread-safe strerror. */
1364 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1365  s = strerror_r(err, buf, sizeof(buf));
1366 #else /* POSIX variant always returns message in buffer */
1367  (void) strerror_r(err, buf, sizeof(buf));
1368 #endif
1369  return strprintf("%s (%d)", s, err);
1370 }
1371 #endif
1372 
#define WSAEINPROGRESS
Definition: compat.h:56
std::string namingLookup(const std::string &name) const
Definition: i2pwrapper.cpp:113
bool IsRFC4843() const
Definition: netbase.cpp:766
unsigned short GetPort() const
Definition: netbase.cpp:1216
void SetIP(const CNetAddr &ip)
Definition: netbase.cpp:613
uint64_t GetHash() const
Definition: netbase.cpp:1039
bool operator<(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:931
#define strprintf
Definition: tinyformat.h:1011
std::string ToStringIP() const
Definition: netbase.cpp:882
void print() const
Definition: netbase.cpp:1051
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Definition: netbase.cpp:948
bool isValidI2pAddress(const std::string &I2pAddr)
Definition: i2pwrapper.cpp:289
static SAM::StreamSessionAdapter & Instance()
Definition: i2pwrapper.h:68
void Init()
Definition: netbase.cpp:1138
std::string ToStringIPPort() const
Definition: netbase.cpp:1314
#define closesocket(s)
Definition: compat.h:75
bool IsRFC6145() const
Definition: netbase.cpp:760
std::string B32AddressFromDestination(const std::string &destination)
Definition: i2pwrapper.cpp:307
void SetPort(unsigned short portIn)
Definition: netbase.cpp:1335
u_int SOCKET
Definition: compat.h:48
bool LookupNumeric(const char *pszName, CService &addr, int portDefault)
Definition: netbase.cpp:253
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout)
Definition: netbase.cpp:573
bool IsRFC4380() const
Definition: netbase.cpp:744
#define INVALID_SOCKET
Definition: compat.h:59
bool IsIPv6() const
Definition: netbase.cpp:706
#define WSAGetLastError()
Definition: compat.h:50
bool IsLocal() const
Definition: netbase.cpp:792
unsigned int GetByte(int n) const
Definition: netbase.cpp:696
bool IsRFC3927() const
Definition: netbase.cpp:723
SAM::SOCKET connect(const std::string &destination, bool silent)
Definition: i2pwrapper.cpp:101
bool HaveNameProxy()
Definition: netbase.cpp:501
bool SetNameProxy(CService addrProxy)
Definition: netbase.cpp:485
bool IsRFC4862() const
Definition: netbase.cpp:749
bool IsIPv4() const
Definition: netbase.cpp:701
#define SOCKET_ERROR
Definition: compat.h:60
bool IsRFC1918() const
Definition: netbase.cpp:715
bool isValidI2pB32(const std::string &B32Address)
Definition: i2pwrapper.cpp:303
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:913
int GetReachabilityFrom(const CNetAddr *paddrPartner=NULL) const
Calculates a metric for how reachable (*this) is from a given partner.
Definition: netbase.cpp:1070
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:52
#define LogPrintf(...)
Definition: util.h:118
bool IsRFC3964() const
Definition: netbase.cpp:733
bool IsMulticast() const
Definition: netbase.cpp:810
bool IsValid() const
Definition: netbase.cpp:816
#define LOCK(cs)
Definition: sync.h:157
bool IsRFC4193() const
Definition: netbase.cpp:755
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netbase.h:109
unsigned short port
Definition: netbase.h:112
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:506
#define NATIVE_I2P_DESTINATION_SIZE
Definition: i2pwrapper.h:13
string EncodeBase32(const unsigned char *pch, size_t len)
Definition: util.cpp:688
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout)
Definition: netbase.cpp:541
std::string ToString() const
Definition: netbase.cpp:1325
bool IsTor() const
Definition: netbase.cpp:771
uint256 Hash(const T1 pbegin, const T1 pend)
Definition: hash.h:20
#define MSG_NOSIGNAL
Definition: util.h:77
void Init()
Definition: netbase.cpp:605
bool IsRFC6052() const
Definition: netbase.cpp:738
bool IsRoutable() const
Definition: netbase.cpp:855
int nConnectTimeout
Definition: netbase.cpp:47
#define WSAEWOULDBLOCK
Definition: compat.h:53
bool GetInAddr(struct in_addr *pipv4Addr) const
Definition: netbase.cpp:940
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:77
Network
Definition: netbase.h:29
std::vector< unsigned char > GetGroup() const
Definition: netbase.cpp:959
void print() const
Definition: netbase.cpp:1330
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netbase.h:45
256-bit unsigned integer
Definition: uint256.h:532
vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)
Definition: util.cpp:752
#define WSAEINVAL
Definition: compat.h:51
bool IsRFC3849() const
Definition: netbase.cpp:728
void * memcpy(void *a, const void *b, size_t c)
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:225
unsigned char ip[16]
Definition: netbase.h:48
bool operator!=(const CNetAddr &a, const CNetAddr &b)
Definition: netbase.cpp:922
bool SetSpecial(const std::string &strName)
Returns TRUE if the address name can be looked up and resolved.
Definition: netbase.cpp:626
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:476
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:506
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: netbase.cpp:1357
std::string ToString() const
Definition: netbase.cpp:908
std::string ToStringPort() const
Definition: netbase.cpp:1295
std::string GetNetworkName(enum Network net)
Definition: netbase.cpp:63
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:207
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netbase.cpp:1170
bool GetNameProxy(CService &nameProxyOut)
Definition: netbase.cpp:493
bool SetProxy(enum Network net, CService addrProxy)
Definition: netbase.cpp:467
bool fNameLookup
Definition: netbase.cpp:48
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netbase.cpp:1248
bool LookupHostNumeric(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions)
Definition: netbase.cpp:220
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:297
std::vector< unsigned char > GetKey() const
Definition: netbase.cpp:1277
enum Network GetNetwork() const
Definition: netbase.cpp:864
CNetAddr()
Definition: netbase.cpp:658