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()
25 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
30 static proxyType proxyInfo[NET_MAX];
31 static proxyType nameproxyInfo;
32 static CCriticalSection cs_proxyInfos;
33 int nConnectTimeout = 5000;
34 bool fNameLookup = false;
36 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
38 enum Network ParseNetwork(std::string net) {
40 if (net == "ipv4") return NET_IPV4;
41 if (net == "ipv6") return NET_IPV6;
42 if (net == "tor" || net == "onion") return NET_TOR;
43 if (net == "i2p") return NET_I2P;
44 return NET_UNROUTABLE;
47 void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut) {
48 size_t colon = in.find_last_of(':');
49 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
50 bool fHaveColon = colon != in.npos;
51 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
52 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
53 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
55 int n = strtol(in.c_str() + colon + 1, &endp, 10);
56 if (endp && *endp == 0 && n >= 0) {
57 in = in.substr(0, colon);
58 if (n > 0 && n < 0x10000)
62 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
63 hostOut = in.substr(1, in.size()-2);
68 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
74 if (addr.SetSpecial(std::string(pszName))) {
80 struct addrinfo aiHint;
81 memset(&aiHint, 0, sizeof(struct addrinfo));
83 aiHint.ai_socktype = SOCK_STREAM;
84 aiHint.ai_protocol = IPPROTO_TCP;
86 aiHint.ai_family = AF_UNSPEC;
88 aiHint.ai_family = AF_INET;
91 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
93 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
95 struct addrinfo *aiRes = NULL;
96 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
100 struct addrinfo *aiTrav = aiRes;
101 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
103 switch (aiTrav->ai_family)
106 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
107 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
112 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
113 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
118 aiTrav = aiTrav->ai_next;
123 return (vIP.size() > 0);
126 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
128 std::string strHost(pszName);
131 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
133 strHost = strHost.substr(1, strHost.size() - 2);
136 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
139 bool Lookup(const char *pszName, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
143 uint16_t port = portDefault;
144 std::string hostname = "";
145 SplitHostPort(std::string(pszName), port, hostname);
147 std::vector<CNetAddr> vIP;
148 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
151 vAddr.resize(vIP.size());
152 for (unsigned int i = 0; i < vIP.size(); i++)
153 vAddr[i] = CService(vIP[i], port);
157 bool Lookup(const char *pszName, CService& addr, uint16_t portDefault, bool fAllowLookup)
159 std::vector<CService> vService;
160 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
167 bool LookupNumeric(const char *pszName, CService& addr, uint16_t portDefault)
169 return Lookup(pszName, addr, portDefault, false);
172 bool static Socks4(const CService &addrDest, SOCKET& hSocket)
174 printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
175 if (!addrDest.IsIPv4())
177 CloseSocket(hSocket);
178 return error("Proxy destination is not IPv4");
180 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
181 struct sockaddr_in addr;
182 socklen_t len = sizeof(addr);
183 if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
185 CloseSocket(hSocket);
186 return error("Cannot get proxy destination address");
188 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
189 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
190 char* pszSocks4 = pszSocks4IP;
191 int nSize = sizeof(pszSocks4IP);
193 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
196 CloseSocket(hSocket);
197 return error("Error sending to proxy");
200 if (recv(hSocket, pchRet, 8, 0) != 8)
202 CloseSocket(hSocket);
203 return error("Error reading proxy response");
205 if (pchRet[1] != 0x5a)
207 CloseSocket(hSocket);
208 if (pchRet[1] != 0x5b)
209 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
212 printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
216 bool static Socks5(string strDest, uint16_t port, SOCKET& hSocket)
218 printf("SOCKS5 connecting %s\n", strDest.c_str());
219 if (strDest.size() > 255)
221 CloseSocket(hSocket);
222 return error("Hostname too long");
224 const char pszSocks5Init[] = "\5\1\0";
225 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
228 CloseSocket(hSocket);
229 return error("Error sending to proxy");
232 if (recv(hSocket, pchRet1, 2, 0) != 2)
234 CloseSocket(hSocket);
235 return error("Error reading proxy response");
237 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
239 CloseSocket(hSocket);
240 return error("Proxy failed to initialize");
242 string strSocks5("\5\1");
243 strSocks5 += '\000'; strSocks5 += '\003';
244 strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
245 strSocks5 += strDest;
246 strSocks5 += static_cast<char>((port >> 8) & 0xFF);
247 strSocks5 += static_cast<char>((port >> 0) & 0xFF);
248 ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
249 if (ret != (ssize_t)strSocks5.size())
251 CloseSocket(hSocket);
252 return error("Error sending to proxy");
255 if (recv(hSocket, pchRet2, 4, 0) != 4)
257 CloseSocket(hSocket);
258 return error("Error reading proxy response");
260 if (pchRet2[0] != 0x05)
262 CloseSocket(hSocket);
263 return error("Proxy failed to accept request");
265 if (pchRet2[1] != 0x00)
267 CloseSocket(hSocket);
270 case 0x01: return error("Proxy error: general failure");
271 case 0x02: return error("Proxy error: connection not allowed");
272 case 0x03: return error("Proxy error: network unreachable");
273 case 0x04: return error("Proxy error: host unreachable");
274 case 0x05: return error("Proxy error: connection refused");
275 case 0x06: return error("Proxy error: TTL expired");
276 case 0x07: return error("Proxy error: protocol error");
277 case 0x08: return error("Proxy error: address type not supported");
278 default: return error("Proxy error: unknown");
281 if (pchRet2[2] != 0x00)
283 CloseSocket(hSocket);
284 return error("Error: malformed proxy response");
289 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
290 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
293 ret = recv(hSocket, pchRet3, 1, 0) != 1;
295 CloseSocket(hSocket);
296 return error("Error reading from proxy");
298 int nRecv = pchRet3[0];
299 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
302 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
306 CloseSocket(hSocket);
307 return error("Error reading from proxy");
309 if (recv(hSocket, pchRet3, 2, 0) != 2)
311 CloseSocket(hSocket);
312 return error("Error reading from proxy");
314 printf("SOCKS5 connected %s\n", strDest.c_str());
318 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
320 hSocketRet = INVALID_SOCKET;
323 struct sockaddr_storage sockaddr;
325 struct sockaddr sockaddr;
327 socklen_t len = sizeof(sockaddr);
328 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
329 printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
333 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
334 if (hSocket == INVALID_SOCKET)
338 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
342 u_long fNonblock = 1;
343 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
345 int fFlags = fcntl(hSocket, F_GETFL, 0);
346 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
349 CloseSocket(hSocket);
353 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
355 int nErr = WSAGetLastError();
356 // WSAEINVAL is here because some legacy version of winsock uses it
357 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
359 struct timeval timeout;
360 timeout.tv_sec = nTimeout / 1000;
361 timeout.tv_usec = (nTimeout % 1000) * 1000;
365 FD_SET(hSocket, &fdset);
366 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
369 printf("connection timeout\n");
370 CloseSocket(hSocket);
373 if (nRet == SOCKET_ERROR)
375 printf("select() for connection failed: %i\n",WSAGetLastError());
376 CloseSocket(hSocket);
379 socklen_t nRetSize = sizeof(nRet);
381 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
383 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
386 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
387 CloseSocket(hSocket);
392 printf("connect() failed after select(): %s\n",strerror(nRet));
393 CloseSocket(hSocket);
398 else if (WSAGetLastError() != WSAEISCONN)
403 printf("connect() failed: %i\n",WSAGetLastError());
404 CloseSocket(hSocket);
409 // this isn't even strictly necessary
410 // CNode::ConnectNode immediately turns the socket back to non-blocking
411 // but we'll turn it back to blocking just in case
414 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
416 fFlags = fcntl(hSocket, F_GETFL, 0);
417 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
420 CloseSocket(hSocket);
424 hSocketRet = hSocket;
428 bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
429 assert(net >= 0 && net < NET_MAX);
430 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
432 if (nSocksVersion != 0 && !addrProxy.IsValid())
435 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
439 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
440 assert(net >= 0 && net < NET_MAX);
442 if (!proxyInfo[net].second)
444 proxyInfoOut = proxyInfo[net];
448 bool SetNameProxy(CService addrProxy, int nSocksVersion) {
449 if (nSocksVersion != 0 && nSocksVersion != 5)
451 if (nSocksVersion != 0 && !addrProxy.IsValid())
454 nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
458 bool GetNameProxy(proxyType &nameproxyInfoOut) {
460 if (!nameproxyInfo.second)
462 nameproxyInfoOut = nameproxyInfo;
466 bool HaveNameProxy() {
468 return nameproxyInfo.second != 0;
471 bool IsProxy(const CNetAddr &addr) {
473 for (int i = 0; i < NET_MAX; i++) {
474 if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
480 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
485 if (!GetProxy(addrDest.GetNetwork(), proxy))
486 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
488 SOCKET hSocket = INVALID_SOCKET;
490 // first connect to proxy server
491 if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
494 // do socks negotiation
495 switch (proxy.second) {
497 if (!Socks4(addrDest, hSocket))
501 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
505 CloseSocket(hSocket);
509 hSocketRet = hSocket;
513 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
516 uint16_t port = portDefault;
517 SplitHostPort(string(pszDest), port, strDest);
519 SOCKET hSocket = INVALID_SOCKET;
522 GetNameProxy(nameproxy);
524 CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
525 if (addrResolved.IsValid()) {
527 return ConnectSocket(addr, hSocketRet, nTimeout);
529 addr = CService("0.0.0.0:0");
530 if (!nameproxy.second)
532 if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
535 switch(nameproxy.second) {
538 CloseSocket(hSocket);
541 if (!Socks5(strDest, port, hSocket))
546 hSocketRet = hSocket;
550 void CNetAddr::Init()
552 memset(ip, 0, sizeof(ip));
555 void CNetAddr::SetIP(const CNetAddr& ipIn)
557 memcpy(ip, ipIn.ip, sizeof(ip));
560 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
561 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
563 bool CNetAddr::SetSpecial(const std::string &strName)
565 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
566 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
567 if (vchAddr.size() != 16-sizeof(pchOnionCat))
569 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
570 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
571 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
574 if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
575 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
576 if (vchAddr.size() != 16-sizeof(pchGarliCat))
578 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
579 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
580 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
591 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
593 memcpy(ip, pchIPv4, 12);
594 memcpy(ip+12, &ipv4Addr, 4);
598 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
600 memcpy(ip, &ipv6Addr, 16);
604 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
607 std::vector<CNetAddr> vIP;
608 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
612 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
615 std::vector<CNetAddr> vIP;
616 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
620 uint8_t CNetAddr::GetByte(int n) const
625 bool CNetAddr::IsIPv4() const
627 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
630 bool CNetAddr::IsIPv6() const
632 return (!IsIPv4() && !IsTor() && !IsI2P());
635 bool CNetAddr::IsRFC1918() const
639 (GetByte(3) == 192 && GetByte(2) == 168) ||
640 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
643 bool CNetAddr::IsRFC3927() const
645 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
648 bool CNetAddr::IsRFC3849() const
650 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
653 bool CNetAddr::IsRFC3964() const
655 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
658 bool CNetAddr::IsRFC6052() const
660 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
661 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
664 bool CNetAddr::IsRFC4380() const
666 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
669 bool CNetAddr::IsRFC4862() const
671 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
672 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
675 bool CNetAddr::IsRFC4193() const
677 return ((GetByte(15) & 0xFE) == 0xFC);
680 bool CNetAddr::IsRFC6145() const
682 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
683 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
686 bool CNetAddr::IsRFC4843() const
688 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
691 bool CNetAddr::IsTor() const
693 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
696 bool CNetAddr::IsI2P() const
698 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
701 bool CNetAddr::IsLocal() const
704 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
707 // IPv6 loopback (::1/128)
708 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
709 if (memcmp(ip, pchLocal, 16) == 0)
715 bool CNetAddr::IsMulticast() const
717 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
718 || (GetByte(15) == 0xFF);
721 bool CNetAddr::IsValid() const
723 // Cleanup 3-byte shifted addresses caused by garbage in size field
724 // of addr messages from versions before 0.2.9 checksum.
725 // Two consecutive addr messages look like this:
726 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
727 // so if the first length field is garbled, it reads the second batch
728 // of addr misaligned by 3 bytes.
729 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
732 // unspecified IPv6 address (::/128)
733 unsigned char ipNone[16] = {};
734 if (memcmp(ip, ipNone, 16) == 0)
737 // documentation IPv6 address
744 uint32_t ipNone = INADDR_NONE;
745 if (memcmp(ip+12, &ipNone, 4) == 0)
750 if (memcmp(ip+12, &ipNone, 4) == 0)
757 bool CNetAddr::IsRoutable() const
759 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
762 enum Network CNetAddr::GetNetwork() const
765 return NET_UNROUTABLE;
779 std::string CNetAddr::ToStringIP() const
782 return EncodeBase32(&ip[6], 10) + ".onion";
784 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
785 CService serv(*this, (uint16_t)0);
787 struct sockaddr_storage sockaddr;
789 struct sockaddr sockaddr;
791 socklen_t socklen = sizeof(sockaddr);
792 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
793 char name[1025] = "";
794 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
795 return std::string(name);
798 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
800 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
801 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
802 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
803 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
804 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
807 std::string CNetAddr::ToString() const
812 bool operator==(const CNetAddr& a, const CNetAddr& b)
814 return (memcmp(a.ip, b.ip, 16) == 0);
817 bool operator!=(const CNetAddr& a, const CNetAddr& b)
819 return (memcmp(a.ip, b.ip, 16) != 0);
822 bool operator<(const CNetAddr& a, const CNetAddr& b)
824 return (memcmp(a.ip, b.ip, 16) < 0);
827 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
831 memcpy(pipv4Addr, ip+12, 4);
836 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
838 memcpy(pipv6Addr, ip, 16);
843 // get canonical identifier of an address' group
844 // no two connections will be attempted to addresses with the same group
845 std::vector<unsigned char> CNetAddr::GetGroup() const
847 std::vector<unsigned char> vchRet;
848 uint8_t nClass = NET_IPV6;
852 // all local addresses belong to the same group
859 // all unroutable addresses belong to the same group
862 nClass = NET_UNROUTABLE;
865 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
866 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
867 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
872 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
873 else if (IsRFC3964())
878 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
879 else if (IsRFC4380())
881 vchRet.push_back(NET_IPV4);
882 vchRet.push_back(GetByte(3) ^ 0xFF);
883 vchRet.push_back(GetByte(2) ^ 0xFF);
898 // for he.net, use /36 groups
899 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
901 // for the rest of the IPv6 network, use /32 groups
905 vchRet.push_back(nClass);
908 vchRet.push_back(GetByte(15 - nStartByte));
913 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
918 uint64_t CNetAddr::GetHash() const
920 uint256 hash = Hash(&ip[0], &ip[16]);
922 memcpy(&nRet, &hash, sizeof(nRet));
926 // private extensions to enum Network, only returned by GetExtNetwork,
927 // and only used in GetReachabilityFrom
928 static const int NET_UNKNOWN = NET_MAX + 0;
929 static const int NET_TEREDO = NET_MAX + 1;
930 int static GetExtNetwork(const CNetAddr *addr)
934 if (addr->IsRFC4380())
936 return addr->GetNetwork();
939 /** Calculates a metric for how reachable (*this) is from a given partner */
940 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
953 return REACH_UNREACHABLE;
955 int ourNet = GetExtNetwork(this);
956 int theirNet = GetExtNetwork(paddrPartner);
957 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
962 default: return REACH_DEFAULT;
963 case NET_IPV4: return REACH_IPV4;
967 default: return REACH_DEFAULT;
968 case NET_TEREDO: return REACH_TEREDO;
969 case NET_IPV4: return REACH_IPV4;
970 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
974 default: return REACH_DEFAULT;
975 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
976 case NET_TOR: return REACH_PRIVATE;
980 default: return REACH_DEFAULT;
981 case NET_I2P: return REACH_PRIVATE;
985 default: return REACH_DEFAULT;
986 case NET_TEREDO: return REACH_TEREDO;
987 case NET_IPV6: return REACH_IPV6_WEAK;
988 case NET_IPV4: return REACH_IPV4;
994 default: return REACH_DEFAULT;
995 case NET_TEREDO: return REACH_TEREDO;
996 case NET_IPV6: return REACH_IPV6_WEAK;
997 case NET_IPV4: return REACH_IPV4;
998 case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
999 case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
1004 void CService::Init()
1009 CService::CService()
1014 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
1018 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
1023 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
1028 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1030 assert(addr.sin_family == AF_INET);
1034 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1036 assert(addr.sin6_family == AF_INET6);
1040 bool CService::SetSockAddr(const struct sockaddr *paddr)
1042 switch (paddr->sa_family) {
1044 *this = CService(*(const struct sockaddr_in*)paddr);
1048 *this = CService(*(const struct sockaddr_in6*)paddr);
1056 CService::CService(const char *pszIpPort, bool fAllowLookup)
1060 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1064 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
1068 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1072 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1076 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1080 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1084 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1088 unsigned short CService::GetPort() const
1093 bool operator==(const CService& a, const CService& b)
1095 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1098 bool operator!=(const CService& a, const CService& b)
1100 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1103 bool operator<(const CService& a, const CService& b)
1105 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1108 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1111 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1113 *addrlen = sizeof(struct sockaddr_in);
1114 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1115 memset(paddrin, 0, *addrlen);
1116 if (!GetInAddr(&paddrin->sin_addr))
1118 paddrin->sin_family = AF_INET;
1119 paddrin->sin_port = htons(port);
1124 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1126 *addrlen = sizeof(struct sockaddr_in6);
1127 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1128 memset(paddrin6, 0, *addrlen);
1129 if (!GetIn6Addr(&paddrin6->sin6_addr))
1131 paddrin6->sin6_family = AF_INET6;
1132 paddrin6->sin6_port = htons(port);
1139 std::vector<unsigned char> CService::GetKey() const
1141 std::vector<unsigned char> vKey;
1143 memcpy(&vKey[0], ip, 16);
1144 vKey[16] = port / 0x100;
1145 vKey[17] = port & 0x0FF;
1149 std::string CService::ToStringPort() const
1151 return strprintf("%u", port);
1154 std::string CService::ToStringIPPort() const
1156 if (IsIPv4() || IsTor() || IsI2P()) {
1157 return ToStringIP() + ":" + ToStringPort();
1159 return "[" + ToStringIP() + "]:" + ToStringPort();
1163 std::string CService::ToString() const
1165 return ToStringIPPort();
1168 void CService::SetPort(unsigned short portIn)
1173 bool CloseSocket(SOCKET& hSocket)
1175 if (hSocket == INVALID_SOCKET)
1178 int ret = closesocket(hSocket);
1180 int ret = close(hSocket);
1182 hSocket = INVALID_SOCKET;
1183 return ret != SOCKET_ERROR;