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.
15 #include <sys/fcntl.h>
21 typedef SSIZE_T ssize_t;
24 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
29 static proxyType proxyInfo[NET_MAX];
30 static proxyType nameproxyInfo;
31 static CCriticalSection cs_proxyInfos;
32 int nConnectTimeout = 5000;
33 bool fNameLookup = false;
35 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
37 enum Network ParseNetwork(std::string net) {
39 if (net == "ipv4") return NET_IPV4;
40 if (net == "ipv6") return NET_IPV6;
41 if (net == "tor" || net == "onion") return NET_TOR;
42 if (net == "i2p") return NET_I2P;
43 return NET_UNROUTABLE;
46 void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut) {
47 auto colon = in.find_last_of(':');
48 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
49 bool fHaveColon = colon != in.npos;
50 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
51 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
52 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
54 int n = strtol(in.c_str() + colon + 1, &endp, 10);
55 if (endp && *endp == 0 && n >= 0) {
56 in = in.substr(0, colon);
57 if (n > 0 && n < 0x10000)
61 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
62 hostOut = in.substr(1, in.size()-2);
67 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
73 if (addr.SetSpecial(std::string(pszName))) {
79 struct addrinfo aiHint;
80 memset(&aiHint, 0, sizeof(struct addrinfo));
82 aiHint.ai_socktype = SOCK_STREAM;
83 aiHint.ai_protocol = IPPROTO_TCP;
85 aiHint.ai_family = AF_UNSPEC;
87 aiHint.ai_family = AF_INET;
90 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
92 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
94 struct addrinfo *aiRes = NULL;
95 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
99 struct addrinfo *aiTrav = aiRes;
100 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
102 switch (aiTrav->ai_family)
105 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
106 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
111 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
112 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
117 aiTrav = aiTrav->ai_next;
122 return (vIP.size() > 0);
125 bool LookupHost(const string strName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
127 std::string strHost(strName);
130 if ((strHost.compare(0,1, "[") == 0) && (strHost.compare(strHost.length()-1,1, "]") == 0))
132 strHost = strHost.substr(1, strHost.size() - 2);
135 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
138 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
140 std::string strHost(pszName);
143 if ((strHost.compare(0,1, "[") == 0) && (strHost.compare(strHost.length()-1,1, "]") == 0))
145 strHost = strHost.substr(1, strHost.size() - 2);
148 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
151 bool Lookup(const char *pszName, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
155 auto port = portDefault;
156 std::string hostname = "";
157 SplitHostPort(std::string(pszName), port, hostname);
159 std::vector<CNetAddr> vIP;
160 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
163 vAddr.resize(vIP.size());
164 for (unsigned int i = 0; i < vIP.size(); i++)
165 vAddr[i] = CService(vIP[i], port);
169 bool Lookup(const char *pszName, CService& addr, uint16_t portDefault, bool fAllowLookup)
171 std::vector<CService> vService;
172 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
179 bool LookupNumeric(const char *pszName, CService& addr, uint16_t portDefault)
181 return Lookup(pszName, addr, portDefault, false);
184 bool static Socks4(const CService &addrDest, SOCKET& hSocket)
186 printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
187 if (!addrDest.IsIPv4())
189 CloseSocket(hSocket);
190 return error("Proxy destination is not IPv4");
192 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
193 struct sockaddr_in addr;
194 socklen_t len = sizeof(addr);
195 if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
197 CloseSocket(hSocket);
198 return error("Cannot get proxy destination address");
200 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
201 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
202 char* pszSocks4 = pszSocks4IP;
203 int nSize = sizeof(pszSocks4IP);
205 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
208 CloseSocket(hSocket);
209 return error("Error sending to proxy");
212 if (recv(hSocket, pchRet, 8, 0) != 8)
214 CloseSocket(hSocket);
215 return error("Error reading proxy response");
217 if (pchRet[1] != 0x5a)
219 CloseSocket(hSocket);
220 if (pchRet[1] != 0x5b)
221 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
224 printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
228 bool static Socks5(string strDest, uint16_t port, SOCKET& hSocket)
230 printf("SOCKS5 connecting %s\n", strDest.c_str());
231 if (strDest.size() > 255)
233 CloseSocket(hSocket);
234 return error("Hostname too long");
236 const char pszSocks5Init[] = "\5\1\0";
237 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
240 CloseSocket(hSocket);
241 return error("Error sending to proxy");
244 if (recv(hSocket, pchRet1, 2, 0) != 2)
246 CloseSocket(hSocket);
247 return error("Error reading proxy response");
249 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
251 CloseSocket(hSocket);
252 return error("Proxy failed to initialize");
254 string strSocks5("\5\1");
255 strSocks5 += '\000'; strSocks5 += '\003';
256 strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
257 strSocks5 += strDest;
258 strSocks5 += static_cast<char>((port >> 8) & 0xFF);
259 strSocks5 += static_cast<char>((port >> 0) & 0xFF);
260 ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
261 if (ret != (ssize_t)strSocks5.size())
263 CloseSocket(hSocket);
264 return error("Error sending to proxy");
267 if (recv(hSocket, pchRet2, 4, 0) != 4)
269 CloseSocket(hSocket);
270 return error("Error reading proxy response");
272 if (pchRet2[0] != 0x05)
274 CloseSocket(hSocket);
275 return error("Proxy failed to accept request");
277 if (pchRet2[1] != 0x00)
279 CloseSocket(hSocket);
282 case 0x01: return error("Proxy error: general failure");
283 case 0x02: return error("Proxy error: connection not allowed");
284 case 0x03: return error("Proxy error: network unreachable");
285 case 0x04: return error("Proxy error: host unreachable");
286 case 0x05: return error("Proxy error: connection refused");
287 case 0x06: return error("Proxy error: TTL expired");
288 case 0x07: return error("Proxy error: protocol error");
289 case 0x08: return error("Proxy error: address type not supported");
290 default: return error("Proxy error: unknown");
293 if (pchRet2[2] != 0x00)
295 CloseSocket(hSocket);
296 return error("Error: malformed proxy response");
301 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
302 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
305 ret = recv(hSocket, pchRet3, 1, 0) != 1;
307 CloseSocket(hSocket);
308 return error("Error reading from proxy");
310 int nRecv = pchRet3[0];
311 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
314 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
318 CloseSocket(hSocket);
319 return error("Error reading from proxy");
321 if (recv(hSocket, pchRet3, 2, 0) != 2)
323 CloseSocket(hSocket);
324 return error("Error reading from proxy");
326 printf("SOCKS5 connected %s\n", strDest.c_str());
330 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
332 hSocketRet = INVALID_SOCKET;
335 struct sockaddr_storage sockaddr;
337 struct sockaddr sockaddr;
339 socklen_t len = sizeof(sockaddr);
340 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
341 printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
345 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
346 if (hSocket == INVALID_SOCKET)
350 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
354 u_long fNonblock = 1;
355 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
357 int fFlags = fcntl(hSocket, F_GETFL, 0);
358 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
361 CloseSocket(hSocket);
365 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
367 int nErr = WSAGetLastError();
368 // WSAEINVAL is here because some legacy version of winsock uses it
369 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
371 struct timeval timeout;
372 timeout.tv_sec = nTimeout / 1000;
373 timeout.tv_usec = (nTimeout % 1000) * 1000;
377 FD_SET(hSocket, &fdset);
378 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
381 printf("connection timeout\n");
382 CloseSocket(hSocket);
385 if (nRet == SOCKET_ERROR)
387 printf("select() for connection failed: %i\n",WSAGetLastError());
388 CloseSocket(hSocket);
391 socklen_t nRetSize = sizeof(nRet);
393 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
395 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
398 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
399 CloseSocket(hSocket);
404 printf("connect() failed after select(): %s\n",strerror(nRet));
405 CloseSocket(hSocket);
410 else if (WSAGetLastError() != WSAEISCONN)
415 printf("connect() failed: %i\n",WSAGetLastError());
416 CloseSocket(hSocket);
421 // this isn't even strictly necessary
422 // CNode::ConnectNode immediately turns the socket back to non-blocking
423 // but we'll turn it back to blocking just in case
426 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
428 fFlags = fcntl(hSocket, F_GETFL, 0);
429 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
432 CloseSocket(hSocket);
436 hSocketRet = hSocket;
440 bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
441 assert(net >= 0 && net < NET_MAX);
442 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
444 if (nSocksVersion != 0 && !addrProxy.IsValid())
447 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
451 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
452 assert(net >= 0 && net < NET_MAX);
454 if (!proxyInfo[net].second)
456 proxyInfoOut = proxyInfo[net];
460 bool SetNameProxy(CService addrProxy, int nSocksVersion) {
461 if (nSocksVersion != 0 && nSocksVersion != 5)
463 if (nSocksVersion != 0 && !addrProxy.IsValid())
466 nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
470 bool GetNameProxy(proxyType &nameproxyInfoOut) {
472 if (!nameproxyInfo.second)
474 nameproxyInfoOut = nameproxyInfo;
478 bool HaveNameProxy() {
480 return nameproxyInfo.second != 0;
483 bool IsProxy(const CNetAddr &addr) {
485 for (int i = 0; i < NET_MAX; i++) {
486 if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
492 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
497 if (!GetProxy(addrDest.GetNetwork(), proxy))
498 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
500 SOCKET hSocket = INVALID_SOCKET;
502 // first connect to proxy server
503 if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
506 // do socks negotiation
507 switch (proxy.second) {
509 if (!Socks4(addrDest, hSocket))
513 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
517 CloseSocket(hSocket);
521 hSocketRet = hSocket;
525 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
528 auto port = portDefault;
529 SplitHostPort(string(pszDest), port, strDest);
531 SOCKET hSocket = INVALID_SOCKET;
534 GetNameProxy(nameproxy);
536 CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
537 if (addrResolved.IsValid()) {
539 return ConnectSocket(addr, hSocketRet, nTimeout);
541 addr = CService("0.0.0.0:0");
542 if (!nameproxy.second)
544 if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
547 switch(nameproxy.second) {
550 CloseSocket(hSocket);
553 if (!Socks5(strDest, port, hSocket))
558 hSocketRet = hSocket;
562 void CNetAddr::Init()
564 memset(ip, 0, sizeof(ip));
567 void CNetAddr::SetIP(const CNetAddr& ipIn)
569 memcpy(ip, ipIn.ip, sizeof(ip));
572 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
573 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
575 bool CNetAddr::SetSpecial(const std::string &strName)
577 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
578 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
579 if (vchAddr.size() != 16-sizeof(pchOnionCat))
581 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
582 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
583 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
586 if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
587 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
588 if (vchAddr.size() != 16-sizeof(pchGarliCat))
590 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
591 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
592 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
603 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
605 memcpy(ip, pchIPv4, 12);
606 memcpy(ip+12, &ipv4Addr, 4);
610 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
612 memcpy(ip, &ipv6Addr, 16);
616 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
619 std::vector<CNetAddr> vIP;
620 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
624 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
627 std::vector<CNetAddr> vIP;
628 if (LookupHost(strIp, vIP, 1, fAllowLookup))
632 uint8_t CNetAddr::GetByte(int n) const
637 bool CNetAddr::IsIPv4() const
639 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
642 bool CNetAddr::IsIPv6() const
644 return (!IsIPv4() && !IsTor() && !IsI2P());
647 bool CNetAddr::IsRFC1918() const
651 (GetByte(3) == 192 && GetByte(2) == 168) ||
652 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
655 bool CNetAddr::IsRFC3927() const
657 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
660 bool CNetAddr::IsRFC3849() const
662 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
665 bool CNetAddr::IsRFC3964() const
667 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
670 bool CNetAddr::IsRFC6052() const
672 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
673 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
676 bool CNetAddr::IsRFC4380() const
678 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
681 bool CNetAddr::IsRFC4862() const
683 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
684 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
687 bool CNetAddr::IsRFC4193() const
689 return ((GetByte(15) & 0xFE) == 0xFC);
692 bool CNetAddr::IsRFC6145() const
694 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
695 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
698 bool CNetAddr::IsRFC4843() const
700 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
703 bool CNetAddr::IsTor() const
705 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
708 bool CNetAddr::IsI2P() const
710 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
713 bool CNetAddr::IsLocal() const
716 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
719 // IPv6 loopback (::1/128)
720 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
721 if (memcmp(ip, pchLocal, 16) == 0)
727 bool CNetAddr::IsMulticast() const
729 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
730 || (GetByte(15) == 0xFF);
733 bool CNetAddr::IsValid() const
735 // Cleanup 3-byte shifted addresses caused by garbage in size field
736 // of addr messages from versions before 0.2.9 checksum.
737 // Two consecutive addr messages look like this:
738 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
739 // so if the first length field is garbled, it reads the second batch
740 // of addr misaligned by 3 bytes.
741 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
744 // unspecified IPv6 address (::/128)
745 unsigned char ipNone[16] = {};
746 if (memcmp(ip, ipNone, 16) == 0)
749 // documentation IPv6 address
756 uint32_t ipNone = INADDR_NONE;
757 if (memcmp(ip+12, &ipNone, 4) == 0)
762 if (memcmp(ip+12, &ipNone, 4) == 0)
769 bool CNetAddr::IsRoutable() const
771 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
774 enum Network CNetAddr::GetNetwork() const
777 return NET_UNROUTABLE;
791 std::string CNetAddr::ToStringIP() const
794 return EncodeBase32(&ip[6], 10) + ".onion";
796 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
797 CService serv(*this, (uint16_t)0);
799 struct sockaddr_storage sockaddr;
801 struct sockaddr sockaddr;
803 socklen_t socklen = sizeof(sockaddr);
804 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
805 char name[1025] = "";
806 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
807 return std::string(name);
810 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
812 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
813 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
814 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
815 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
816 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
819 std::string CNetAddr::ToString() const
824 bool operator==(const CNetAddr& a, const CNetAddr& b)
826 return (memcmp(a.ip, b.ip, 16) == 0);
829 bool operator!=(const CNetAddr& a, const CNetAddr& b)
831 return (memcmp(a.ip, b.ip, 16) != 0);
834 bool operator<(const CNetAddr& a, const CNetAddr& b)
836 return (memcmp(a.ip, b.ip, 16) < 0);
839 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
843 memcpy(pipv4Addr, ip+12, 4);
848 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
850 memcpy(pipv6Addr, ip, 16);
855 // get canonical identifier of an address' group
856 // no two connections will be attempted to addresses with the same group
857 std::vector<unsigned char> CNetAddr::GetGroup() const
859 std::vector<unsigned char> vchRet;
860 uint8_t nClass = NET_IPV6;
864 // all local addresses belong to the same group
871 // all unroutable addresses belong to the same group
874 nClass = NET_UNROUTABLE;
877 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
878 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
879 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
884 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
885 else if (IsRFC3964())
890 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
891 else if (IsRFC4380())
893 vchRet.push_back(NET_IPV4);
894 vchRet.push_back(GetByte(3) ^ 0xFF);
895 vchRet.push_back(GetByte(2) ^ 0xFF);
910 // for he.net, use /36 groups
911 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
913 // for the rest of the IPv6 network, use /32 groups
917 vchRet.push_back(nClass);
920 vchRet.push_back(GetByte(15 - nStartByte));
925 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
930 uint64_t CNetAddr::GetHash() const
932 auto hash = Hash(&ip[0], &ip[16]);
934 memcpy(&nRet, &hash, sizeof(nRet));
938 // private extensions to enum Network, only returned by GetExtNetwork,
939 // and only used in GetReachabilityFrom
940 static const int NET_UNKNOWN = NET_MAX + 0;
941 static const int NET_TEREDO = NET_MAX + 1;
942 int static GetExtNetwork(const CNetAddr *addr)
946 if (addr->IsRFC4380())
948 return addr->GetNetwork();
951 /** Calculates a metric for how reachable (*this) is from a given partner */
952 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
965 return REACH_UNREACHABLE;
967 int ourNet = GetExtNetwork(this);
968 int theirNet = GetExtNetwork(paddrPartner);
969 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
974 default: return REACH_DEFAULT;
975 case NET_IPV4: return REACH_IPV4;
979 default: return REACH_DEFAULT;
980 case NET_TEREDO: return REACH_TEREDO;
981 case NET_IPV4: return REACH_IPV4;
982 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
986 default: return REACH_DEFAULT;
987 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
988 case NET_TOR: return REACH_PRIVATE;
992 default: return REACH_DEFAULT;
993 case NET_I2P: return REACH_PRIVATE;
997 default: return REACH_DEFAULT;
998 case NET_TEREDO: return REACH_TEREDO;
999 case NET_IPV6: return REACH_IPV6_WEAK;
1000 case NET_IPV4: return REACH_IPV4;
1003 case NET_UNROUTABLE:
1006 default: return REACH_DEFAULT;
1007 case NET_TEREDO: return REACH_TEREDO;
1008 case NET_IPV6: return REACH_IPV6_WEAK;
1009 case NET_IPV4: return REACH_IPV4;
1010 case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
1011 case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
1016 void CService::Init()
1021 CService::CService()
1026 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
1030 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
1035 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
1040 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1042 assert(addr.sin_family == AF_INET);
1046 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1048 assert(addr.sin6_family == AF_INET6);
1052 bool CService::SetSockAddr(const struct sockaddr *paddr)
1054 switch (paddr->sa_family) {
1056 *this = CService(*(const struct sockaddr_in*)paddr);
1060 *this = CService(*(const struct sockaddr_in6*)paddr);
1068 CService::CService(const char *pszIpPort, bool fAllowLookup)
1072 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1076 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
1080 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1084 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1088 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1092 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1096 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1100 uint16_t CService::GetPort() const
1105 bool operator==(const CService& a, const CService& b)
1107 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1110 bool operator!=(const CService& a, const CService& b)
1112 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1115 bool operator<(const CService& a, const CService& b)
1117 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1120 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1123 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1125 *addrlen = sizeof(struct sockaddr_in);
1126 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1127 memset(paddrin, 0, *addrlen);
1128 if (!GetInAddr(&paddrin->sin_addr))
1130 paddrin->sin_family = AF_INET;
1131 paddrin->sin_port = htons(port);
1136 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1138 *addrlen = sizeof(struct sockaddr_in6);
1139 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1140 memset(paddrin6, 0, *addrlen);
1141 if (!GetIn6Addr(&paddrin6->sin6_addr))
1143 paddrin6->sin6_family = AF_INET6;
1144 paddrin6->sin6_port = htons(port);
1151 std::vector<unsigned char> CService::GetKey() const
1153 std::vector<unsigned char> vKey;
1155 memcpy(&vKey[0], ip, 16);
1156 vKey[16] = port / 0x100;
1157 vKey[17] = port & 0x0FF;
1161 std::string CService::ToStringPort() const
1163 return strprintf("%u", port);
1166 std::string CService::ToStringIPPort() const
1168 if (IsIPv4() || IsTor() || IsI2P()) {
1169 return ToStringIP() + ":" + ToStringPort();
1171 return "[" + ToStringIP() + "]:" + ToStringPort();
1175 std::string CService::ToString() const
1177 return ToStringIPPort();
1180 void CService::SetPort(uint16_t portIn)
1185 bool CloseSocket(SOCKET& hSocket)
1187 if (hSocket == INVALID_SOCKET)
1190 int ret = closesocket(hSocket);
1192 int ret = close(hSocket);
1194 hSocket = INVALID_SOCKET;
1195 return ret != SOCKET_ERROR;