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