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;
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 Socks5(string strDest, uint16_t port, SOCKET& hSocket)
184 printf("SOCKS5 connecting %s\n", strDest.c_str());
185 if (strDest.size() > 255)
187 CloseSocket(hSocket);
188 return error("Hostname too long");
190 const char pszSocks5Init[] = "\5\1\0";
191 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
194 CloseSocket(hSocket);
195 return error("Error sending to proxy");
198 if (recv(hSocket, pchRet1, 2, 0) != 2)
200 CloseSocket(hSocket);
201 return error("Error reading proxy response");
203 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
205 CloseSocket(hSocket);
206 return error("Proxy failed to initialize");
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())
217 CloseSocket(hSocket);
218 return error("Error sending to proxy");
221 if (recv(hSocket, pchRet2, 4, 0) != 4)
223 CloseSocket(hSocket);
224 return error("Error reading proxy response");
226 if (pchRet2[0] != 0x05)
228 CloseSocket(hSocket);
229 return error("Proxy failed to accept request");
231 if (pchRet2[1] != 0x00)
233 CloseSocket(hSocket);
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");
247 if (pchRet2[2] != 0x00)
249 CloseSocket(hSocket);
250 return error("Error: malformed proxy response");
255 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
256 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
259 ret = recv(hSocket, pchRet3, 1, 0) != 1;
261 CloseSocket(hSocket);
262 return error("Error reading from proxy");
264 int nRecv = pchRet3[0];
265 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
268 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
272 CloseSocket(hSocket);
273 return error("Error reading from proxy");
275 if (recv(hSocket, pchRet3, 2, 0) != 2)
277 CloseSocket(hSocket);
278 return error("Error reading from proxy");
280 printf("SOCKS5 connected %s\n", strDest.c_str());
284 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
286 hSocketRet = INVALID_SOCKET;
289 struct sockaddr_storage sockaddr;
291 struct sockaddr sockaddr;
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());
299 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
300 if (hSocket == INVALID_SOCKET)
304 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
308 u_long fNonblock = 1;
309 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
311 int fFlags = fcntl(hSocket, F_GETFL, 0);
312 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
315 CloseSocket(hSocket);
319 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
321 int nErr = WSAGetLastError();
322 // WSAEINVAL is here because some legacy version of winsock uses it
323 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
325 struct timeval timeout;
326 timeout.tv_sec = nTimeout / 1000;
327 timeout.tv_usec = (nTimeout % 1000) * 1000;
331 FD_SET(hSocket, &fdset);
332 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
335 printf("connection timeout\n");
336 CloseSocket(hSocket);
339 if (nRet == SOCKET_ERROR)
341 printf("select() for connection failed: %i\n",WSAGetLastError());
342 CloseSocket(hSocket);
345 socklen_t nRetSize = sizeof(nRet);
347 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
349 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
352 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
353 CloseSocket(hSocket);
358 printf("connect() failed after select(): %s\n",strerror(nRet));
359 CloseSocket(hSocket);
364 else if (WSAGetLastError() != WSAEISCONN)
369 printf("connect() failed: %i\n",WSAGetLastError());
370 CloseSocket(hSocket);
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
380 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
382 fFlags = fcntl(hSocket, F_GETFL, 0);
383 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
386 CloseSocket(hSocket);
390 hSocketRet = hSocket;
394 bool SetProxy(enum Network net, CService addrProxy) {
395 assert(net >= 0 && net < NET_MAX);
396 if (!addrProxy.IsValid())
399 proxyInfo[net] = addrProxy;
403 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
404 assert(net >= 0 && net < NET_MAX);
406 if (!proxyInfo[net].IsValid())
408 proxyInfoOut = proxyInfo[net];
412 bool SetNameProxy(CService addrProxy) {
413 if (!addrProxy.IsValid())
416 nameProxy = addrProxy;
420 bool GetNameProxy(CService &nameProxyOut) {
422 if (!nameProxy.IsValid())
424 nameProxyOut = nameProxy;
428 bool HaveNameProxy() {
430 return nameProxy.IsValid();
433 bool IsProxy(const CNetAddr &addr) {
435 for (int i = 0; i < NET_MAX; i++) {
436 if (addr == (CNetAddr)proxyInfo[i])
442 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
447 if (!GetProxy(addrDest.GetNetwork(), proxy))
448 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
450 SOCKET hSocket = INVALID_SOCKET;
452 // first connect to proxy server
453 if (!ConnectSocketDirectly(proxy, hSocket, nTimeout))
456 // do socks negotiation
457 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
460 hSocketRet = hSocket;
464 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
467 auto port = portDefault;
468 SplitHostPort(string(pszDest), port, strDest);
470 SOCKET hSocket = INVALID_SOCKET;
473 GetNameProxy(nameProxy);
475 CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
476 if (addrResolved.IsValid()) {
478 return ConnectSocket(addr, hSocketRet, nTimeout);
480 addr = CService("0.0.0.0:0");
483 // first connect to name proxy server
484 if (!ConnectSocketDirectly(nameProxy, hSocket, nTimeout))
486 // do socks negotiation
487 if (!Socks5(strDest, port, hSocket))
490 hSocketRet = hSocket;
494 void CNetAddr::Init()
496 memset(ip, 0, sizeof(ip));
499 void CNetAddr::SetIP(const CNetAddr& ipIn)
501 memcpy(ip, ipIn.ip, sizeof(ip));
504 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
505 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
507 bool CNetAddr::SetSpecial(const std::string &strName)
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))
513 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
514 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
515 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
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))
522 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
523 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
524 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
535 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
537 memcpy(ip, pchIPv4, 12);
538 memcpy(ip+12, &ipv4Addr, 4);
542 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
544 memcpy(ip, &ipv6Addr, 16);
548 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
551 std::vector<CNetAddr> vIP;
552 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
556 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
559 std::vector<CNetAddr> vIP;
560 if (LookupHost(strIp, vIP, 1, fAllowLookup))
564 uint8_t CNetAddr::GetByte(int n) const
569 bool CNetAddr::IsIPv4() const
571 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
574 bool CNetAddr::IsIPv6() const
576 return (!IsIPv4() && !IsTor() && !IsI2P());
579 bool CNetAddr::IsRFC1918() const
583 (GetByte(3) == 192 && GetByte(2) == 168) ||
584 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
587 bool CNetAddr::IsRFC3927() const
589 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
592 bool CNetAddr::IsRFC3849() const
594 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
597 bool CNetAddr::IsRFC3964() const
599 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
602 bool CNetAddr::IsRFC6052() const
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);
608 bool CNetAddr::IsRFC4380() const
610 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
613 bool CNetAddr::IsRFC4862() const
615 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
616 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
619 bool CNetAddr::IsRFC4193() const
621 return ((GetByte(15) & 0xFE) == 0xFC);
624 bool CNetAddr::IsRFC6145() const
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);
630 bool CNetAddr::IsRFC4843() const
632 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
635 bool CNetAddr::IsTor() const
637 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
640 bool CNetAddr::IsI2P() const
642 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
645 bool CNetAddr::IsLocal() const
648 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
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)
659 bool CNetAddr::IsMulticast() const
661 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
662 || (GetByte(15) == 0xFF);
665 bool CNetAddr::IsValid() const
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)
676 // unspecified IPv6 address (::/128)
677 unsigned char ipNone[16] = {};
678 if (memcmp(ip, ipNone, 16) == 0)
681 // documentation IPv6 address
688 uint32_t ipNone = INADDR_NONE;
689 if (memcmp(ip+12, &ipNone, 4) == 0)
694 if (memcmp(ip+12, &ipNone, 4) == 0)
701 bool CNetAddr::IsRoutable() const
703 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
706 enum Network CNetAddr::GetNetwork() const
709 return NET_UNROUTABLE;
723 std::string CNetAddr::ToStringIP() const
726 return EncodeBase32(&ip[6], 10) + ".onion";
728 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
729 CService serv(*this, (uint16_t)0);
731 struct sockaddr_storage sockaddr;
733 struct sockaddr sockaddr;
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);
742 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
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));
751 std::string CNetAddr::ToString() const
756 bool operator==(const CNetAddr& a, const CNetAddr& b)
758 return (memcmp(a.ip, b.ip, 16) == 0);
761 bool operator!=(const CNetAddr& a, const CNetAddr& b)
763 return (memcmp(a.ip, b.ip, 16) != 0);
766 bool operator<(const CNetAddr& a, const CNetAddr& b)
768 return (memcmp(a.ip, b.ip, 16) < 0);
771 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
775 memcpy(pipv4Addr, ip+12, 4);
780 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
782 memcpy(pipv6Addr, ip, 16);
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
791 std::vector<unsigned char> vchRet;
792 uint8_t nClass = NET_IPV6;
796 // all local addresses belong to the same group
803 // all unroutable addresses belong to the same group
806 nClass = NET_UNROUTABLE;
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())
816 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
817 else if (IsRFC3964())
822 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
823 else if (IsRFC4380())
825 vchRet.push_back(NET_IPV4);
826 vchRet.push_back(GetByte(3) ^ 0xFF);
827 vchRet.push_back(GetByte(2) ^ 0xFF);
842 // for he.net, use /36 groups
843 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
845 // for the rest of the IPv6 network, use /32 groups
849 vchRet.push_back(nClass);
852 vchRet.push_back(GetByte(15 - nStartByte));
857 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
862 uint64_t CNetAddr::GetHash() const
864 auto hash = Hash(&ip[0], &ip[16]);
866 memcpy(&nRet, &hash, sizeof(nRet));
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)
878 if (addr->IsRFC4380())
880 return addr->GetNetwork();
883 /** Calculates a metric for how reachable (*this) is from a given partner */
884 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
897 return REACH_UNREACHABLE;
899 int ourNet = GetExtNetwork(this);
900 int theirNet = GetExtNetwork(paddrPartner);
901 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
906 default: return REACH_DEFAULT;
907 case NET_IPV4: return REACH_IPV4;
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
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;
924 default: return REACH_DEFAULT;
925 case NET_I2P: return REACH_PRIVATE;
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;
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
948 void CService::Init()
958 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
962 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
967 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
972 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
974 assert(addr.sin_family == AF_INET);
978 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
980 assert(addr.sin6_family == AF_INET6);
984 bool CService::SetSockAddr(const struct sockaddr *paddr)
986 switch (paddr->sa_family) {
988 *this = CService(*(const struct sockaddr_in*)paddr);
992 *this = CService(*(const struct sockaddr_in6*)paddr);
1000 CService::CService(const char *pszIpPort, bool fAllowLookup)
1004 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1008 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
1012 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1016 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1020 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1024 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1028 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1032 uint16_t CService::GetPort() const
1037 bool operator==(const CService& a, const CService& b)
1039 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1042 bool operator!=(const CService& a, const CService& b)
1044 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1047 bool operator<(const CService& a, const CService& b)
1049 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1052 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1055 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
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))
1062 paddrin->sin_family = AF_INET;
1063 paddrin->sin_port = htons(port);
1068 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
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))
1075 paddrin6->sin6_family = AF_INET6;
1076 paddrin6->sin6_port = htons(port);
1083 std::vector<unsigned char> CService::GetKey() const
1085 std::vector<unsigned char> vKey;
1087 memcpy(&vKey[0], ip, 16);
1088 vKey[16] = port / 0x100;
1089 vKey[17] = port & 0x0FF;
1093 std::string CService::ToStringPort() const
1095 return strprintf("%u", port);
1098 std::string CService::ToStringIPPort() const
1100 if (IsIPv4() || IsTor() || IsI2P()) {
1101 return ToStringIP() + ":" + ToStringPort();
1103 return "[" + ToStringIP() + "]:" + ToStringPort();
1107 std::string CService::ToString() const
1109 return ToStringIPPort();
1112 void CService::SetupPort(uint16_t portIn)
1117 bool CloseSocket(SOCKET& hSocket)
1119 if (hSocket == INVALID_SOCKET)
1122 int ret = closesocket(hSocket);
1124 int ret = close(hSocket);
1126 hSocket = INVALID_SOCKET;
1127 return ret != SOCKET_ERROR;