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