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