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