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