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