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;
27 static proxyType proxyInfo[NET_MAX];
28 static proxyType nameproxyInfo;
29 static CCriticalSection cs_proxyInfos;
30 int nConnectTimeout = 5000;
31 bool fNameLookup = false;
33 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
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;
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)) {
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)
59 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
60 hostOut = in.substr(1, in.size()-2);
65 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
71 if (addr.SetSpecial(std::string(pszName))) {
77 struct addrinfo aiHint;
78 memset(&aiHint, 0, sizeof(struct addrinfo));
80 aiHint.ai_socktype = SOCK_STREAM;
81 aiHint.ai_protocol = IPPROTO_TCP;
83 aiHint.ai_family = AF_UNSPEC;
85 aiHint.ai_family = AF_INET;
88 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
90 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
92 struct addrinfo *aiRes = NULL;
93 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
97 struct addrinfo *aiTrav = aiRes;
98 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
100 switch (aiTrav->ai_family)
103 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
104 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
109 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
110 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
115 aiTrav = aiTrav->ai_next;
120 return (vIP.size() > 0);
123 bool LookupHost(const string& strName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
125 std::string strHost(strName);
128 if ((strHost.front() == '[') && (strHost.back() == ']'))
130 strHost = strHost.substr(1, strHost.size() - 2);
133 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
136 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
138 std::string strHost(pszName);
141 if ((strHost.front() == '[') && (strHost.back() == ']'))
143 strHost = strHost.substr(1, strHost.size() - 2);
146 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
149 bool Lookup(const char *pszName, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
153 auto port = portDefault;
154 std::string hostname = "";
155 SplitHostPort(std::string(pszName), port, hostname);
157 std::vector<CNetAddr> vIP;
158 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
161 vAddr.resize(vIP.size());
162 for (unsigned int i = 0; i < vIP.size(); i++)
163 vAddr[i] = CService(vIP[i], port);
167 bool Lookup(const char *pszName, CService& addr, uint16_t portDefault, bool fAllowLookup)
169 std::vector<CService> vService;
170 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
177 bool LookupNumeric(const char *pszName, CService& addr, uint16_t portDefault)
179 return Lookup(pszName, addr, portDefault, false);
182 bool static Socks4(const CService &addrDest, SOCKET& hSocket)
184 printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
185 if (!addrDest.IsIPv4())
187 CloseSocket(hSocket);
188 return error("Proxy destination is not IPv4");
190 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
191 struct sockaddr_in addr;
192 socklen_t len = sizeof(addr);
193 if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
195 CloseSocket(hSocket);
196 return error("Cannot get proxy destination address");
198 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
199 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
200 char* pszSocks4 = pszSocks4IP;
201 int nSize = sizeof(pszSocks4IP);
203 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
206 CloseSocket(hSocket);
207 return error("Error sending to proxy");
210 if (recv(hSocket, pchRet, 8, 0) != 8)
212 CloseSocket(hSocket);
213 return error("Error reading proxy response");
215 if (pchRet[1] != 0x5a)
217 CloseSocket(hSocket);
218 if (pchRet[1] != 0x5b)
219 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
222 printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
226 bool static Socks5(string strDest, uint16_t port, SOCKET& hSocket)
228 printf("SOCKS5 connecting %s\n", strDest.c_str());
229 if (strDest.size() > 255)
231 CloseSocket(hSocket);
232 return error("Hostname too long");
234 const char pszSocks5Init[] = "\5\1\0";
235 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
238 CloseSocket(hSocket);
239 return error("Error sending to proxy");
242 if (recv(hSocket, pchRet1, 2, 0) != 2)
244 CloseSocket(hSocket);
245 return error("Error reading proxy response");
247 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
249 CloseSocket(hSocket);
250 return error("Proxy failed to initialize");
252 string strSocks5("\5\1");
253 strSocks5 += '\000'; strSocks5 += '\003';
254 strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
255 strSocks5 += strDest;
256 strSocks5 += static_cast<char>((port >> 8) & 0xFF);
257 strSocks5 += static_cast<char>((port >> 0) & 0xFF);
258 ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
259 if (ret != (ssize_t)strSocks5.size())
261 CloseSocket(hSocket);
262 return error("Error sending to proxy");
265 if (recv(hSocket, pchRet2, 4, 0) != 4)
267 CloseSocket(hSocket);
268 return error("Error reading proxy response");
270 if (pchRet2[0] != 0x05)
272 CloseSocket(hSocket);
273 return error("Proxy failed to accept request");
275 if (pchRet2[1] != 0x00)
277 CloseSocket(hSocket);
280 case 0x01: return error("Proxy error: general failure");
281 case 0x02: return error("Proxy error: connection not allowed");
282 case 0x03: return error("Proxy error: network unreachable");
283 case 0x04: return error("Proxy error: host unreachable");
284 case 0x05: return error("Proxy error: connection refused");
285 case 0x06: return error("Proxy error: TTL expired");
286 case 0x07: return error("Proxy error: protocol error");
287 case 0x08: return error("Proxy error: address type not supported");
288 default: return error("Proxy error: unknown");
291 if (pchRet2[2] != 0x00)
293 CloseSocket(hSocket);
294 return error("Error: malformed proxy response");
299 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
300 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
303 ret = recv(hSocket, pchRet3, 1, 0) != 1;
305 CloseSocket(hSocket);
306 return error("Error reading from proxy");
308 int nRecv = pchRet3[0];
309 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
312 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
316 CloseSocket(hSocket);
317 return error("Error reading from proxy");
319 if (recv(hSocket, pchRet3, 2, 0) != 2)
321 CloseSocket(hSocket);
322 return error("Error reading from proxy");
324 printf("SOCKS5 connected %s\n", strDest.c_str());
328 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
330 hSocketRet = INVALID_SOCKET;
333 struct sockaddr_storage sockaddr;
335 struct sockaddr sockaddr;
337 socklen_t len = sizeof(sockaddr);
338 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
339 printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
343 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
344 if (hSocket == INVALID_SOCKET)
348 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
352 u_long fNonblock = 1;
353 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
355 int fFlags = fcntl(hSocket, F_GETFL, 0);
356 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
359 CloseSocket(hSocket);
363 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
365 int nErr = WSAGetLastError();
366 // WSAEINVAL is here because some legacy version of winsock uses it
367 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
369 struct timeval timeout;
370 timeout.tv_sec = nTimeout / 1000;
371 timeout.tv_usec = (nTimeout % 1000) * 1000;
375 FD_SET(hSocket, &fdset);
376 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
379 printf("connection timeout\n");
380 CloseSocket(hSocket);
383 if (nRet == SOCKET_ERROR)
385 printf("select() for connection failed: %i\n",WSAGetLastError());
386 CloseSocket(hSocket);
389 socklen_t nRetSize = sizeof(nRet);
391 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
393 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
396 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
397 CloseSocket(hSocket);
402 printf("connect() failed after select(): %s\n",strerror(nRet));
403 CloseSocket(hSocket);
408 else if (WSAGetLastError() != WSAEISCONN)
413 printf("connect() failed: %i\n",WSAGetLastError());
414 CloseSocket(hSocket);
419 // this isn't even strictly necessary
420 // CNode::ConnectNode immediately turns the socket back to non-blocking
421 // but we'll turn it back to blocking just in case
424 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
426 fFlags = fcntl(hSocket, F_GETFL, 0);
427 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
430 CloseSocket(hSocket);
434 hSocketRet = hSocket;
438 bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
439 assert(net >= 0 && net < NET_MAX);
440 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
442 if (nSocksVersion != 0 && !addrProxy.IsValid())
445 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
449 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
450 assert(net >= 0 && net < NET_MAX);
452 if (!proxyInfo[net].second)
454 proxyInfoOut = proxyInfo[net];
458 bool SetNameProxy(CService addrProxy, int nSocksVersion) {
459 if (nSocksVersion != 0 && nSocksVersion != 5)
461 if (nSocksVersion != 0 && !addrProxy.IsValid())
464 nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
468 bool GetNameProxy(proxyType &nameproxyInfoOut) {
470 if (!nameproxyInfo.second)
472 nameproxyInfoOut = nameproxyInfo;
476 bool HaveNameProxy() {
478 return nameproxyInfo.second != 0;
481 bool IsProxy(const CNetAddr &addr) {
483 for (int i = 0; i < NET_MAX; i++) {
484 if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
490 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
495 if (!GetProxy(addrDest.GetNetwork(), proxy))
496 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
498 SOCKET hSocket = INVALID_SOCKET;
500 // first connect to proxy server
501 if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
504 // do socks negotiation
505 switch (proxy.second) {
507 if (!Socks4(addrDest, hSocket))
511 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
515 CloseSocket(hSocket);
519 hSocketRet = hSocket;
523 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
526 auto port = portDefault;
527 SplitHostPort(string(pszDest), port, strDest);
529 SOCKET hSocket = INVALID_SOCKET;
532 GetNameProxy(nameproxy);
534 CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
535 if (addrResolved.IsValid()) {
537 return ConnectSocket(addr, hSocketRet, nTimeout);
539 addr = CService("0.0.0.0:0");
540 if (!nameproxy.second)
542 if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
545 switch(nameproxy.second) {
548 CloseSocket(hSocket);
551 if (!Socks5(strDest, port, hSocket))
556 hSocketRet = hSocket;
560 void CNetAddr::Init()
562 memset(ip, 0, sizeof(ip));
565 void CNetAddr::SetIP(const CNetAddr& ipIn)
567 memcpy(ip, ipIn.ip, sizeof(ip));
570 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
571 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
573 bool CNetAddr::SetSpecial(const std::string &strName)
575 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
576 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
577 if (vchAddr.size() != 16-sizeof(pchOnionCat))
579 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
580 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
581 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
584 if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
585 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
586 if (vchAddr.size() != 16-sizeof(pchGarliCat))
588 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
589 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
590 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
601 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
603 memcpy(ip, pchIPv4, 12);
604 memcpy(ip+12, &ipv4Addr, 4);
608 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
610 memcpy(ip, &ipv6Addr, 16);
614 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
617 std::vector<CNetAddr> vIP;
618 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
622 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
625 std::vector<CNetAddr> vIP;
626 if (LookupHost(strIp, vIP, 1, fAllowLookup))
630 uint8_t CNetAddr::GetByte(int n) const
635 bool CNetAddr::IsIPv4() const
637 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
640 bool CNetAddr::IsIPv6() const
642 return (!IsIPv4() && !IsTor() && !IsI2P());
645 bool CNetAddr::IsRFC1918() const
649 (GetByte(3) == 192 && GetByte(2) == 168) ||
650 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
653 bool CNetAddr::IsRFC3927() const
655 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
658 bool CNetAddr::IsRFC3849() const
660 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
663 bool CNetAddr::IsRFC3964() const
665 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
668 bool CNetAddr::IsRFC6052() const
670 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
671 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
674 bool CNetAddr::IsRFC4380() const
676 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
679 bool CNetAddr::IsRFC4862() const
681 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
682 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
685 bool CNetAddr::IsRFC4193() const
687 return ((GetByte(15) & 0xFE) == 0xFC);
690 bool CNetAddr::IsRFC6145() const
692 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
693 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
696 bool CNetAddr::IsRFC4843() const
698 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
701 bool CNetAddr::IsTor() const
703 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
706 bool CNetAddr::IsI2P() const
708 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
711 bool CNetAddr::IsLocal() const
714 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
717 // IPv6 loopback (::1/128)
718 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
719 if (memcmp(ip, pchLocal, 16) == 0)
725 bool CNetAddr::IsMulticast() const
727 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
728 || (GetByte(15) == 0xFF);
731 bool CNetAddr::IsValid() const
733 // Cleanup 3-byte shifted addresses caused by garbage in size field
734 // of addr messages from versions before 0.2.9 checksum.
735 // Two consecutive addr messages look like this:
736 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
737 // so if the first length field is garbled, it reads the second batch
738 // of addr misaligned by 3 bytes.
739 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
742 // unspecified IPv6 address (::/128)
743 unsigned char ipNone[16] = {};
744 if (memcmp(ip, ipNone, 16) == 0)
747 // documentation IPv6 address
754 uint32_t ipNone = INADDR_NONE;
755 if (memcmp(ip+12, &ipNone, 4) == 0)
760 if (memcmp(ip+12, &ipNone, 4) == 0)
767 bool CNetAddr::IsRoutable() const
769 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
772 enum Network CNetAddr::GetNetwork() const
775 return NET_UNROUTABLE;
789 std::string CNetAddr::ToStringIP() const
792 return EncodeBase32(&ip[6], 10) + ".onion";
794 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
795 CService serv(*this, (uint16_t)0);
797 struct sockaddr_storage sockaddr;
799 struct sockaddr sockaddr;
801 socklen_t socklen = sizeof(sockaddr);
802 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
803 char name[1025] = "";
804 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
805 return std::string(name);
808 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
810 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
811 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
812 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
813 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
814 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
817 std::string CNetAddr::ToString() const
822 bool operator==(const CNetAddr& a, const CNetAddr& b)
824 return (memcmp(a.ip, b.ip, 16) == 0);
827 bool operator!=(const CNetAddr& a, const CNetAddr& b)
829 return (memcmp(a.ip, b.ip, 16) != 0);
832 bool operator<(const CNetAddr& a, const CNetAddr& b)
834 return (memcmp(a.ip, b.ip, 16) < 0);
837 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
841 memcpy(pipv4Addr, ip+12, 4);
846 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
848 memcpy(pipv6Addr, ip, 16);
853 // get canonical identifier of an address' group
854 // no two connections will be attempted to addresses with the same group
855 std::vector<unsigned char> CNetAddr::GetGroup() const
857 std::vector<unsigned char> vchRet;
858 uint8_t nClass = NET_IPV6;
862 // all local addresses belong to the same group
869 // all unroutable addresses belong to the same group
872 nClass = NET_UNROUTABLE;
875 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
876 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
877 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
882 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
883 else if (IsRFC3964())
888 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
889 else if (IsRFC4380())
891 vchRet.push_back(NET_IPV4);
892 vchRet.push_back(GetByte(3) ^ 0xFF);
893 vchRet.push_back(GetByte(2) ^ 0xFF);
908 // for he.net, use /36 groups
909 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
911 // for the rest of the IPv6 network, use /32 groups
915 vchRet.push_back(nClass);
918 vchRet.push_back(GetByte(15 - nStartByte));
923 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
928 uint64_t CNetAddr::GetHash() const
930 auto hash = Hash(&ip[0], &ip[16]);
932 memcpy(&nRet, &hash, sizeof(nRet));
936 // private extensions to enum Network, only returned by GetExtNetwork,
937 // and only used in GetReachabilityFrom
938 static const int NET_UNKNOWN = NET_MAX + 0;
939 static const int NET_TEREDO = NET_MAX + 1;
940 int static GetExtNetwork(const CNetAddr *addr)
944 if (addr->IsRFC4380())
946 return addr->GetNetwork();
949 /** Calculates a metric for how reachable (*this) is from a given partner */
950 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
963 return REACH_UNREACHABLE;
965 int ourNet = GetExtNetwork(this);
966 int theirNet = GetExtNetwork(paddrPartner);
967 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
972 default: return REACH_DEFAULT;
973 case NET_IPV4: return REACH_IPV4;
977 default: return REACH_DEFAULT;
978 case NET_TEREDO: return REACH_TEREDO;
979 case NET_IPV4: return REACH_IPV4;
980 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
984 default: return REACH_DEFAULT;
985 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
986 case NET_TOR: return REACH_PRIVATE;
990 default: return REACH_DEFAULT;
991 case NET_I2P: return REACH_PRIVATE;
995 default: return REACH_DEFAULT;
996 case NET_TEREDO: return REACH_TEREDO;
997 case NET_IPV6: return REACH_IPV6_WEAK;
998 case NET_IPV4: return REACH_IPV4;
1001 case NET_UNROUTABLE:
1004 default: return REACH_DEFAULT;
1005 case NET_TEREDO: return REACH_TEREDO;
1006 case NET_IPV6: return REACH_IPV6_WEAK;
1007 case NET_IPV4: return REACH_IPV4;
1008 case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
1009 case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
1014 void CService::Init()
1019 CService::CService()
1024 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
1028 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
1033 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
1038 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1040 assert(addr.sin_family == AF_INET);
1044 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1046 assert(addr.sin6_family == AF_INET6);
1050 bool CService::SetSockAddr(const struct sockaddr *paddr)
1052 switch (paddr->sa_family) {
1054 *this = CService(*(const struct sockaddr_in*)paddr);
1058 *this = CService(*(const struct sockaddr_in6*)paddr);
1066 CService::CService(const char *pszIpPort, bool fAllowLookup)
1070 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1074 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
1078 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1082 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1086 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1090 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1094 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1098 uint16_t CService::GetPort() const
1103 bool operator==(const CService& a, const CService& b)
1105 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1108 bool operator!=(const CService& a, const CService& b)
1110 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1113 bool operator<(const CService& a, const CService& b)
1115 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1118 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1121 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1123 *addrlen = sizeof(struct sockaddr_in);
1124 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1125 memset(paddrin, 0, *addrlen);
1126 if (!GetInAddr(&paddrin->sin_addr))
1128 paddrin->sin_family = AF_INET;
1129 paddrin->sin_port = htons(port);
1134 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1136 *addrlen = sizeof(struct sockaddr_in6);
1137 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1138 memset(paddrin6, 0, *addrlen);
1139 if (!GetIn6Addr(&paddrin6->sin6_addr))
1141 paddrin6->sin6_family = AF_INET6;
1142 paddrin6->sin6_port = htons(port);
1149 std::vector<unsigned char> CService::GetKey() const
1151 std::vector<unsigned char> vKey;
1153 memcpy(&vKey[0], ip, 16);
1154 vKey[16] = port / 0x100;
1155 vKey[17] = port & 0x0FF;
1159 std::string CService::ToStringPort() const
1161 return strprintf("%u", port);
1164 std::string CService::ToStringIPPort() const
1166 if (IsIPv4() || IsTor() || IsI2P()) {
1167 return ToStringIP() + ":" + ToStringPort();
1169 return "[" + ToStringIP() + "]:" + ToStringPort();
1173 std::string CService::ToString() const
1175 return ToStringIPPort();
1178 void CService::SetupPort(uint16_t portIn)
1183 bool CloseSocket(SOCKET& hSocket)
1185 if (hSocket == INVALID_SOCKET)
1188 int ret = closesocket(hSocket);
1190 int ret = close(hSocket);
1192 hSocket = INVALID_SOCKET;
1193 return ret != SOCKET_ERROR;