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 CService nameProxy;
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;
82 aiHint.ai_family = AF_UNSPEC;
84 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
86 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
88 struct addrinfo *aiRes = NULL;
89 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
93 struct addrinfo *aiTrav = aiRes;
94 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
96 switch (aiTrav->ai_family)
99 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
100 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
104 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
105 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
109 aiTrav = aiTrav->ai_next;
114 return (vIP.size() > 0);
117 bool LookupHost(const string& strName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
119 std::string strHost(strName);
122 if ((strHost.front() == '[') && (strHost.back() == ']'))
124 strHost = strHost.substr(1, strHost.size() - 2);
127 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
130 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
132 std::string strHost(pszName);
135 if ((strHost.front() == '[') && (strHost.back() == ']'))
137 strHost = strHost.substr(1, strHost.size() - 2);
140 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
143 bool Lookup(const char *pszName, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
147 auto port = portDefault;
148 std::string hostname = "";
149 SplitHostPort(std::string(pszName), port, hostname);
151 std::vector<CNetAddr> vIP;
152 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
155 vAddr.resize(vIP.size());
156 for (unsigned int i = 0; i < vIP.size(); i++)
157 vAddr[i] = CService(vIP[i], port);
161 bool Lookup(const char *pszName, CService& addr, uint16_t portDefault, bool fAllowLookup)
163 std::vector<CService> vService;
164 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
171 bool LookupNumeric(const char *pszName, CService& addr, uint16_t portDefault)
173 return Lookup(pszName, addr, portDefault, false);
176 bool static Socks5(string strDest, uint16_t port, SOCKET& hSocket)
178 printf("SOCKS5 connecting %s\n", strDest.c_str());
179 if (strDest.size() > 255)
181 CloseSocket(hSocket);
182 return error("Hostname too long");
184 const char pszSocks5Init[] = "\5\1\0";
185 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
188 CloseSocket(hSocket);
189 return error("Error sending to proxy");
192 if (recv(hSocket, pchRet1, 2, 0) != 2)
194 CloseSocket(hSocket);
195 return error("Error reading proxy response");
197 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
199 CloseSocket(hSocket);
200 return error("Proxy failed to initialize");
202 string strSocks5("\5\1");
203 strSocks5 += '\000'; strSocks5 += '\003';
204 strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
205 strSocks5 += strDest;
206 strSocks5 += static_cast<char>((port >> 8) & 0xFF);
207 strSocks5 += static_cast<char>((port >> 0) & 0xFF);
208 ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
209 if (ret != (ssize_t)strSocks5.size())
211 CloseSocket(hSocket);
212 return error("Error sending to proxy");
215 if (recv(hSocket, pchRet2, 4, 0) != 4)
217 CloseSocket(hSocket);
218 return error("Error reading proxy response");
220 if (pchRet2[0] != 0x05)
222 CloseSocket(hSocket);
223 return error("Proxy failed to accept request");
225 if (pchRet2[1] != 0x00)
227 CloseSocket(hSocket);
230 case 0x01: return error("Proxy error: general failure");
231 case 0x02: return error("Proxy error: connection not allowed");
232 case 0x03: return error("Proxy error: network unreachable");
233 case 0x04: return error("Proxy error: host unreachable");
234 case 0x05: return error("Proxy error: connection refused");
235 case 0x06: return error("Proxy error: TTL expired");
236 case 0x07: return error("Proxy error: protocol error");
237 case 0x08: return error("Proxy error: address type not supported");
238 default: return error("Proxy error: unknown");
241 if (pchRet2[2] != 0x00)
243 CloseSocket(hSocket);
244 return error("Error: malformed proxy response");
249 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
250 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
253 ret = recv(hSocket, pchRet3, 1, 0) != 1;
255 CloseSocket(hSocket);
256 return error("Error reading from proxy");
258 int nRecv = pchRet3[0];
259 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
262 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
266 CloseSocket(hSocket);
267 return error("Error reading from proxy");
269 if (recv(hSocket, pchRet3, 2, 0) != 2)
271 CloseSocket(hSocket);
272 return error("Error reading from proxy");
274 printf("SOCKS5 connected %s\n", strDest.c_str());
278 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
280 hSocketRet = INVALID_SOCKET;
282 struct sockaddr_storage sockaddr;
283 socklen_t len = sizeof(sockaddr);
284 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
285 printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
289 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
290 if (hSocket == INVALID_SOCKET)
294 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
298 u_long fNonblock = 1;
299 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
301 int fFlags = fcntl(hSocket, F_GETFL, 0);
302 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
305 CloseSocket(hSocket);
309 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
311 int nErr = WSAGetLastError();
312 // WSAEINVAL is here because some legacy version of winsock uses it
313 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
315 struct timeval timeout;
316 timeout.tv_sec = nTimeout / 1000;
317 timeout.tv_usec = (nTimeout % 1000) * 1000;
321 FD_SET(hSocket, &fdset);
322 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
325 printf("connection timeout\n");
326 CloseSocket(hSocket);
329 if (nRet == SOCKET_ERROR)
331 printf("select() for connection failed: %i\n",WSAGetLastError());
332 CloseSocket(hSocket);
335 socklen_t nRetSize = sizeof(nRet);
337 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
339 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
342 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
343 CloseSocket(hSocket);
348 printf("connect() failed after select(): %s\n",strerror(nRet));
349 CloseSocket(hSocket);
354 else if (WSAGetLastError() != WSAEISCONN)
359 printf("connect() failed: %i\n",WSAGetLastError());
360 CloseSocket(hSocket);
365 // this isn't even strictly necessary
366 // CNode::ConnectNode immediately turns the socket back to non-blocking
367 // but we'll turn it back to blocking just in case
370 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
372 fFlags = fcntl(hSocket, F_GETFL, 0);
373 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
376 CloseSocket(hSocket);
380 hSocketRet = hSocket;
384 bool SetProxy(enum Network net, CService addrProxy) {
385 assert(net >= 0 && net < NET_MAX);
386 if (!addrProxy.IsValid())
389 proxyInfo[net] = addrProxy;
393 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
394 assert(net >= 0 && net < NET_MAX);
396 if (!proxyInfo[net].IsValid())
398 proxyInfoOut = proxyInfo[net];
402 bool SetNameProxy(CService addrProxy) {
403 if (!addrProxy.IsValid())
406 nameProxy = addrProxy;
410 bool GetNameProxy(CService &nameProxyOut) {
412 if (!nameProxy.IsValid())
414 nameProxyOut = nameProxy;
418 bool HaveNameProxy() {
420 return nameProxy.IsValid();
423 bool IsProxy(const CNetAddr &addr) {
425 for (int i = 0; i < NET_MAX; i++) {
426 if (addr == (CNetAddr)proxyInfo[i])
432 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
437 if (!GetProxy(addrDest.GetNetwork(), proxy))
438 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
440 SOCKET hSocket = INVALID_SOCKET;
442 // first connect to proxy server
443 if (!ConnectSocketDirectly(proxy, hSocket, nTimeout))
446 // do socks negotiation
447 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
450 hSocketRet = hSocket;
454 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
457 auto port = portDefault;
458 SplitHostPort(string(pszDest), port, strDest);
460 SOCKET hSocket = INVALID_SOCKET;
463 GetNameProxy(nameProxy);
465 CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
466 if (addrResolved.IsValid()) {
468 return ConnectSocket(addr, hSocketRet, nTimeout);
470 addr = CService("0.0.0.0:0");
471 if (!HaveNameProxy())
473 // first connect to name proxy server
474 if (!ConnectSocketDirectly(nameProxy, hSocket, nTimeout))
476 // do socks negotiation
477 if (!Socks5(strDest, port, hSocket))
480 hSocketRet = hSocket;
484 void CNetAddr::Init()
486 memset(ip, 0, sizeof(ip));
489 void CNetAddr::SetIP(const CNetAddr& ipIn)
491 memcpy(ip, ipIn.ip, sizeof(ip));
494 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
495 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
497 bool CNetAddr::SetSpecial(const std::string &strName)
499 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
500 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
501 if (vchAddr.size() != 16-sizeof(pchOnionCat))
503 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
504 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
505 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
508 if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
509 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
510 if (vchAddr.size() != 16-sizeof(pchGarliCat))
512 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
513 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
514 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
525 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
527 memcpy(ip, pchIPv4, 12);
528 memcpy(ip+12, &ipv4Addr, 4);
531 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
533 memcpy(ip, &ipv6Addr, 16);
536 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
539 std::vector<CNetAddr> vIP;
540 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
544 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
547 std::vector<CNetAddr> vIP;
548 if (LookupHost(strIp, vIP, 1, fAllowLookup))
552 uint8_t CNetAddr::GetByte(int n) const
557 bool CNetAddr::IsIPv4() const
559 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
562 bool CNetAddr::IsIPv6() const
564 return (!IsIPv4() && !IsTor() && !IsI2P());
567 bool CNetAddr::IsRFC1918() const
571 (GetByte(3) == 192 && GetByte(2) == 168) ||
572 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
575 bool CNetAddr::IsRFC3927() const
577 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
580 bool CNetAddr::IsRFC3849() const
582 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
585 bool CNetAddr::IsRFC3964() const
587 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
590 bool CNetAddr::IsRFC6052() const
592 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
593 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
596 bool CNetAddr::IsRFC4380() const
598 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
601 bool CNetAddr::IsRFC4862() const
603 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
604 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
607 bool CNetAddr::IsRFC4193() const
609 return ((GetByte(15) & 0xFE) == 0xFC);
612 bool CNetAddr::IsRFC6145() const
614 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
615 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
618 bool CNetAddr::IsRFC4843() const
620 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
623 bool CNetAddr::IsTor() const
625 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
628 bool CNetAddr::IsI2P() const
630 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
633 bool CNetAddr::IsLocal() const
636 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
639 // IPv6 loopback (::1/128)
640 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
641 if (memcmp(ip, pchLocal, 16) == 0)
647 bool CNetAddr::IsMulticast() const
649 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
650 || (GetByte(15) == 0xFF);
653 bool CNetAddr::IsValid() const
655 // Cleanup 3-byte shifted addresses caused by garbage in size field
656 // of addr messages from versions before 0.2.9 checksum.
657 // Two consecutive addr messages look like this:
658 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
659 // so if the first length field is garbled, it reads the second batch
660 // of addr misaligned by 3 bytes.
661 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
664 // unspecified IPv6 address (::/128)
665 unsigned char ipNone[16] = {};
666 if (memcmp(ip, ipNone, 16) == 0)
669 // documentation IPv6 address
676 uint32_t ipNone = INADDR_NONE;
677 if (memcmp(ip+12, &ipNone, 4) == 0)
682 if (memcmp(ip+12, &ipNone, 4) == 0)
689 bool CNetAddr::IsRoutable() const
691 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
694 enum Network CNetAddr::GetNetwork() const
697 return NET_UNROUTABLE;
711 std::string CNetAddr::ToStringIP() const
714 return EncodeBase32(&ip[6], 10) + ".onion";
716 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
717 CService serv(*this, (uint16_t)0);
718 struct sockaddr_storage sockaddr;
719 socklen_t socklen = sizeof(sockaddr);
720 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
721 char name[1025] = "";
722 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
723 return std::string(name);
726 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
728 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
729 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
730 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
731 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
732 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
735 std::string CNetAddr::ToString() const
740 bool operator==(const CNetAddr& a, const CNetAddr& b)
742 return (memcmp(a.ip, b.ip, 16) == 0);
745 bool operator!=(const CNetAddr& a, const CNetAddr& b)
747 return (memcmp(a.ip, b.ip, 16) != 0);
750 bool operator<(const CNetAddr& a, const CNetAddr& b)
752 return (memcmp(a.ip, b.ip, 16) < 0);
755 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
759 memcpy(pipv4Addr, ip+12, 4);
763 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
765 memcpy(pipv6Addr, ip, 16);
769 // get canonical identifier of an address' group
770 // no two connections will be attempted to addresses with the same group
771 std::vector<unsigned char> CNetAddr::GetGroup() const
773 std::vector<unsigned char> vchRet;
774 uint8_t nClass = NET_IPV6;
778 // all local addresses belong to the same group
785 // all unroutable addresses belong to the same group
788 nClass = NET_UNROUTABLE;
791 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
792 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
793 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
798 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
799 else if (IsRFC3964())
804 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
805 else if (IsRFC4380())
807 vchRet.push_back(NET_IPV4);
808 vchRet.push_back(GetByte(3) ^ 0xFF);
809 vchRet.push_back(GetByte(2) ^ 0xFF);
824 // for he.net, use /36 groups
825 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
827 // for the rest of the IPv6 network, use /32 groups
831 vchRet.push_back(nClass);
834 vchRet.push_back(GetByte(15 - nStartByte));
839 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
844 uint64_t CNetAddr::GetHash() const
846 auto hash = Hash(&ip[0], &ip[16]);
848 memcpy(&nRet, &hash, sizeof(nRet));
852 // private extensions to enum Network, only returned by GetExtNetwork,
853 // and only used in GetReachabilityFrom
854 static const int NET_UNKNOWN = NET_MAX + 0;
855 static const int NET_TEREDO = NET_MAX + 1;
856 int static GetExtNetwork(const CNetAddr *addr)
860 if (addr->IsRFC4380())
862 return addr->GetNetwork();
865 /** Calculates a metric for how reachable (*this) is from a given partner */
866 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
879 return REACH_UNREACHABLE;
881 int ourNet = GetExtNetwork(this);
882 int theirNet = GetExtNetwork(paddrPartner);
883 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
888 default: return REACH_DEFAULT;
889 case NET_IPV4: return REACH_IPV4;
893 default: return REACH_DEFAULT;
894 case NET_TEREDO: return REACH_TEREDO;
895 case NET_IPV4: return REACH_IPV4;
896 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
900 default: return REACH_DEFAULT;
901 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
902 case NET_TOR: return REACH_PRIVATE;
906 default: return REACH_DEFAULT;
907 case NET_I2P: return REACH_PRIVATE;
911 default: return REACH_DEFAULT;
912 case NET_TEREDO: return REACH_TEREDO;
913 case NET_IPV6: return REACH_IPV6_WEAK;
914 case NET_IPV4: return REACH_IPV4;
920 default: return REACH_DEFAULT;
921 case NET_TEREDO: return REACH_TEREDO;
922 case NET_IPV6: return REACH_IPV6_WEAK;
923 case NET_IPV4: return REACH_IPV4;
924 case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
925 case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
930 void CService::Init()
940 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
944 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
948 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
952 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
954 assert(addr.sin_family == AF_INET);
957 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
959 assert(addr.sin6_family == AF_INET6);
962 bool CService::SetSockAddr(const struct sockaddr *paddr)
964 switch (paddr->sa_family) {
966 *this = CService(*(const struct sockaddr_in*)paddr);
969 *this = CService(*(const struct sockaddr_in6*)paddr);
976 CService::CService(const char *pszIpPort, bool fAllowLookup)
980 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
984 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
988 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
992 CService::CService(const std::string &strIpPort, bool fAllowLookup)
996 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1000 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1004 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1008 uint16_t CService::GetPort() const
1013 bool operator==(const CService& a, const CService& b)
1015 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1018 bool operator!=(const CService& a, const CService& b)
1020 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1023 bool operator<(const CService& a, const CService& b)
1025 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1028 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1031 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1033 *addrlen = sizeof(struct sockaddr_in);
1034 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1035 memset(paddrin, 0, *addrlen);
1036 if (!GetInAddr(&paddrin->sin_addr))
1038 paddrin->sin_family = AF_INET;
1039 paddrin->sin_port = htons(port);
1043 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1045 *addrlen = sizeof(struct sockaddr_in6);
1046 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1047 memset(paddrin6, 0, *addrlen);
1048 if (!GetIn6Addr(&paddrin6->sin6_addr))
1050 paddrin6->sin6_family = AF_INET6;
1051 paddrin6->sin6_port = htons(port);
1057 std::vector<unsigned char> CService::GetKey() const
1059 std::vector<unsigned char> vKey;
1061 memcpy(&vKey[0], ip, 16);
1062 vKey[16] = port / 0x100;
1063 vKey[17] = port & 0x0FF;
1067 std::string CService::ToStringPort() const
1069 return strprintf("%u", port);
1072 std::string CService::ToStringIPPort() const
1074 if (IsIPv4() || IsTor() || IsI2P()) {
1075 return ToStringIP() + ":" + ToStringPort();
1077 return "[" + ToStringIP() + "]:" + ToStringPort();
1081 std::string CService::ToString() const
1083 return ToStringIPPort();
1086 void CService::SetupPort(uint16_t portIn)
1091 bool CloseSocket(SOCKET& hSocket)
1093 if (hSocket == INVALID_SOCKET)
1096 int ret = closesocket(hSocket);
1098 int ret = close(hSocket);
1100 hSocket = INVALID_SOCKET;
1101 return ret != SOCKET_ERROR;