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;
28 static proxyType proxyInfo[NET_MAX];
29 static proxyType nameproxyInfo;
30 static CCriticalSection cs_proxyInfos;
31 int nConnectTimeout = 5000;
32 bool fNameLookup = false;
34 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
36 enum Network ParseNetwork(std::string net) {
37 transform(net.begin(), net.end(), net.begin(), ::tolower);
38 if (net == "ipv4") return NET_IPV4;
39 if (net == "ipv6") return NET_IPV6;
40 if (net == "tor" || net == "onion") return NET_TOR;
41 if (net == "i2p") return NET_I2P;
42 return NET_UNROUTABLE;
45 void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut) {
46 size_t colon = in.find_last_of(':');
47 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
48 bool fHaveColon = colon != in.npos;
49 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
50 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
51 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
53 int n = strtol(in.c_str() + colon + 1, &endp, 10);
54 if (endp && *endp == 0 && n >= 0) {
55 in = in.substr(0, colon);
56 if (n > 0 && n < 0x10000)
60 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
61 hostOut = in.substr(1, in.size()-2);
66 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
72 if (addr.SetSpecial(std::string(pszName))) {
78 struct addrinfo aiHint;
79 memset(&aiHint, 0, sizeof(struct addrinfo));
81 aiHint.ai_socktype = SOCK_STREAM;
82 aiHint.ai_protocol = IPPROTO_TCP;
84 aiHint.ai_family = AF_UNSPEC;
86 aiHint.ai_family = AF_INET;
89 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
91 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
93 struct addrinfo *aiRes = NULL;
94 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
98 struct addrinfo *aiTrav = aiRes;
99 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
101 switch (aiTrav->ai_family)
104 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
105 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
110 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
111 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
116 aiTrav = aiTrav->ai_next;
121 return (vIP.size() > 0);
124 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
126 std::string strHost(pszName);
129 if ((strHost.compare(0,1, "[") == 0) && (strHost.compare(strHost.length()-1,1, "]") == 0))
131 strHost = strHost.substr(1, strHost.size() - 2);
134 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
137 bool Lookup(const char *pszName, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
141 uint16_t port = portDefault;
142 std::string hostname = "";
143 SplitHostPort(std::string(pszName), port, hostname);
145 std::vector<CNetAddr> vIP;
146 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
149 vAddr.resize(vIP.size());
150 for (unsigned int i = 0; i < vIP.size(); i++)
151 vAddr[i] = CService(vIP[i], port);
155 bool Lookup(const char *pszName, CService& addr, uint16_t portDefault, bool fAllowLookup)
157 std::vector<CService> vService;
158 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
165 bool LookupNumeric(const char *pszName, CService& addr, uint16_t portDefault)
167 return Lookup(pszName, addr, portDefault, false);
170 bool static Socks4(const CService &addrDest, SOCKET& hSocket)
172 printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
173 if (!addrDest.IsIPv4())
175 CloseSocket(hSocket);
176 return error("Proxy destination is not IPv4");
178 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
179 struct sockaddr_in addr;
180 socklen_t len = sizeof(addr);
181 if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
183 CloseSocket(hSocket);
184 return error("Cannot get proxy destination address");
186 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
187 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
188 char* pszSocks4 = pszSocks4IP;
189 int nSize = sizeof(pszSocks4IP);
191 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
194 CloseSocket(hSocket);
195 return error("Error sending to proxy");
198 if (recv(hSocket, pchRet, 8, 0) != 8)
200 CloseSocket(hSocket);
201 return error("Error reading proxy response");
203 if (pchRet[1] != 0x5a)
205 CloseSocket(hSocket);
206 if (pchRet[1] != 0x5b)
207 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
210 printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
214 bool static Socks5(string strDest, uint16_t port, SOCKET& hSocket)
216 printf("SOCKS5 connecting %s\n", strDest.c_str());
217 if (strDest.size() > 255)
219 CloseSocket(hSocket);
220 return error("Hostname too long");
222 const char pszSocks5Init[] = "\5\1\0";
223 ssize_t ret = send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
226 CloseSocket(hSocket);
227 return error("Error sending to proxy");
230 if (recv(hSocket, pchRet1, 2, 0) != 2)
232 CloseSocket(hSocket);
233 return error("Error reading proxy response");
235 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
237 CloseSocket(hSocket);
238 return error("Proxy failed to initialize");
240 string strSocks5("\5\1");
241 strSocks5 += '\000'; strSocks5 += '\003';
242 strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
243 strSocks5 += strDest;
244 strSocks5 += static_cast<char>((port >> 8) & 0xFF);
245 strSocks5 += static_cast<char>((port >> 0) & 0xFF);
246 ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
247 if (ret != (ssize_t)strSocks5.size())
249 CloseSocket(hSocket);
250 return error("Error sending to proxy");
253 if (recv(hSocket, pchRet2, 4, 0) != 4)
255 CloseSocket(hSocket);
256 return error("Error reading proxy response");
258 if (pchRet2[0] != 0x05)
260 CloseSocket(hSocket);
261 return error("Proxy failed to accept request");
263 if (pchRet2[1] != 0x00)
265 CloseSocket(hSocket);
268 case 0x01: return error("Proxy error: general failure");
269 case 0x02: return error("Proxy error: connection not allowed");
270 case 0x03: return error("Proxy error: network unreachable");
271 case 0x04: return error("Proxy error: host unreachable");
272 case 0x05: return error("Proxy error: connection refused");
273 case 0x06: return error("Proxy error: TTL expired");
274 case 0x07: return error("Proxy error: protocol error");
275 case 0x08: return error("Proxy error: address type not supported");
276 default: return error("Proxy error: unknown");
279 if (pchRet2[2] != 0x00)
281 CloseSocket(hSocket);
282 return error("Error: malformed proxy response");
287 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
288 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
291 ret = recv(hSocket, pchRet3, 1, 0) != 1;
293 CloseSocket(hSocket);
294 return error("Error reading from proxy");
296 int nRecv = pchRet3[0];
297 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
300 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
304 CloseSocket(hSocket);
305 return error("Error reading from proxy");
307 if (recv(hSocket, pchRet3, 2, 0) != 2)
309 CloseSocket(hSocket);
310 return error("Error reading from proxy");
312 printf("SOCKS5 connected %s\n", strDest.c_str());
316 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
318 hSocketRet = INVALID_SOCKET;
321 struct sockaddr_storage sockaddr;
323 struct sockaddr sockaddr;
325 socklen_t len = sizeof(sockaddr);
326 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
327 printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
331 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
332 if (hSocket == INVALID_SOCKET)
336 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
340 u_long fNonblock = 1;
341 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
343 int fFlags = fcntl(hSocket, F_GETFL, 0);
344 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
347 CloseSocket(hSocket);
351 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
353 int nErr = WSAGetLastError();
354 // WSAEINVAL is here because some legacy version of winsock uses it
355 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
357 struct timeval timeout;
358 timeout.tv_sec = nTimeout / 1000;
359 timeout.tv_usec = (nTimeout % 1000) * 1000;
363 FD_SET(hSocket, &fdset);
364 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
367 printf("connection timeout\n");
368 CloseSocket(hSocket);
371 if (nRet == SOCKET_ERROR)
373 printf("select() for connection failed: %i\n",WSAGetLastError());
374 CloseSocket(hSocket);
377 socklen_t nRetSize = sizeof(nRet);
379 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
381 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
384 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
385 CloseSocket(hSocket);
390 printf("connect() failed after select(): %s\n",strerror(nRet));
391 CloseSocket(hSocket);
396 else if (WSAGetLastError() != WSAEISCONN)
401 printf("connect() failed: %i\n",WSAGetLastError());
402 CloseSocket(hSocket);
407 // this isn't even strictly necessary
408 // CNode::ConnectNode immediately turns the socket back to non-blocking
409 // but we'll turn it back to blocking just in case
412 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
414 fFlags = fcntl(hSocket, F_GETFL, 0);
415 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
418 CloseSocket(hSocket);
422 hSocketRet = hSocket;
426 bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
427 assert(net >= 0 && net < NET_MAX);
428 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
430 if (nSocksVersion != 0 && !addrProxy.IsValid())
433 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
437 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
438 assert(net >= 0 && net < NET_MAX);
440 if (!proxyInfo[net].second)
442 proxyInfoOut = proxyInfo[net];
446 bool SetNameProxy(CService addrProxy, int nSocksVersion) {
447 if (nSocksVersion != 0 && nSocksVersion != 5)
449 if (nSocksVersion != 0 && !addrProxy.IsValid())
452 nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
456 bool GetNameProxy(proxyType &nameproxyInfoOut) {
458 if (!nameproxyInfo.second)
460 nameproxyInfoOut = nameproxyInfo;
464 bool HaveNameProxy() {
466 return nameproxyInfo.second != 0;
469 bool IsProxy(const CNetAddr &addr) {
471 for (int i = 0; i < NET_MAX; i++) {
472 if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
478 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
483 if (!GetProxy(addrDest.GetNetwork(), proxy))
484 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
486 SOCKET hSocket = INVALID_SOCKET;
488 // first connect to proxy server
489 if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
492 // do socks negotiation
493 switch (proxy.second) {
495 if (!Socks4(addrDest, hSocket))
499 if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
503 CloseSocket(hSocket);
507 hSocketRet = hSocket;
511 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, uint16_t portDefault, int nTimeout)
514 uint16_t port = portDefault;
515 SplitHostPort(string(pszDest), port, strDest);
517 SOCKET hSocket = INVALID_SOCKET;
520 GetNameProxy(nameproxy);
522 CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
523 if (addrResolved.IsValid()) {
525 return ConnectSocket(addr, hSocketRet, nTimeout);
527 addr = CService("0.0.0.0:0");
528 if (!nameproxy.second)
530 if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
533 switch(nameproxy.second) {
536 CloseSocket(hSocket);
539 if (!Socks5(strDest, port, hSocket))
544 hSocketRet = hSocket;
548 void CNetAddr::Init()
550 memset(ip, 0, sizeof(ip));
553 void CNetAddr::SetIP(const CNetAddr& ipIn)
555 memcpy(ip, ipIn.ip, sizeof(ip));
558 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
559 static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
561 bool CNetAddr::SetSpecial(const std::string &strName)
563 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
564 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
565 if (vchAddr.size() != 16-sizeof(pchOnionCat))
567 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
568 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
569 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
572 if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
573 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
574 if (vchAddr.size() != 16-sizeof(pchGarliCat))
576 memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
577 for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
578 ip[i + sizeof(pchGarliCat)] = vchAddr[i];
589 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
591 memcpy(ip, pchIPv4, 12);
592 memcpy(ip+12, &ipv4Addr, 4);
596 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
598 memcpy(ip, &ipv6Addr, 16);
602 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
605 std::vector<CNetAddr> vIP;
606 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
610 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
613 std::vector<CNetAddr> vIP;
614 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
618 uint8_t CNetAddr::GetByte(int n) const
623 bool CNetAddr::IsIPv4() const
625 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
628 bool CNetAddr::IsIPv6() const
630 return (!IsIPv4() && !IsTor() && !IsI2P());
633 bool CNetAddr::IsRFC1918() const
637 (GetByte(3) == 192 && GetByte(2) == 168) ||
638 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
641 bool CNetAddr::IsRFC3927() const
643 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
646 bool CNetAddr::IsRFC3849() const
648 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
651 bool CNetAddr::IsRFC3964() const
653 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
656 bool CNetAddr::IsRFC6052() const
658 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
659 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
662 bool CNetAddr::IsRFC4380() const
664 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
667 bool CNetAddr::IsRFC4862() const
669 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
670 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
673 bool CNetAddr::IsRFC4193() const
675 return ((GetByte(15) & 0xFE) == 0xFC);
678 bool CNetAddr::IsRFC6145() const
680 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
681 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
684 bool CNetAddr::IsRFC4843() const
686 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
689 bool CNetAddr::IsTor() const
691 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
694 bool CNetAddr::IsI2P() const
696 return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
699 bool CNetAddr::IsLocal() const
702 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
705 // IPv6 loopback (::1/128)
706 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
707 if (memcmp(ip, pchLocal, 16) == 0)
713 bool CNetAddr::IsMulticast() const
715 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
716 || (GetByte(15) == 0xFF);
719 bool CNetAddr::IsValid() const
721 // Cleanup 3-byte shifted addresses caused by garbage in size field
722 // of addr messages from versions before 0.2.9 checksum.
723 // Two consecutive addr messages look like this:
724 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
725 // so if the first length field is garbled, it reads the second batch
726 // of addr misaligned by 3 bytes.
727 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
730 // unspecified IPv6 address (::/128)
731 unsigned char ipNone[16] = {};
732 if (memcmp(ip, ipNone, 16) == 0)
735 // documentation IPv6 address
742 uint32_t ipNone = INADDR_NONE;
743 if (memcmp(ip+12, &ipNone, 4) == 0)
748 if (memcmp(ip+12, &ipNone, 4) == 0)
755 bool CNetAddr::IsRoutable() const
757 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
760 enum Network CNetAddr::GetNetwork() const
763 return NET_UNROUTABLE;
777 std::string CNetAddr::ToStringIP() const
780 return EncodeBase32(&ip[6], 10) + ".onion";
782 return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
783 CService serv(*this, (uint16_t)0);
785 struct sockaddr_storage sockaddr;
787 struct sockaddr sockaddr;
789 socklen_t socklen = sizeof(sockaddr);
790 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
791 char name[1025] = "";
792 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
793 return std::string(name);
796 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
798 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
799 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
800 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
801 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
802 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
805 std::string CNetAddr::ToString() const
810 bool operator==(const CNetAddr& a, const CNetAddr& b)
812 return (memcmp(a.ip, b.ip, 16) == 0);
815 bool operator!=(const CNetAddr& a, const CNetAddr& b)
817 return (memcmp(a.ip, b.ip, 16) != 0);
820 bool operator<(const CNetAddr& a, const CNetAddr& b)
822 return (memcmp(a.ip, b.ip, 16) < 0);
825 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
829 memcpy(pipv4Addr, ip+12, 4);
834 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
836 memcpy(pipv6Addr, ip, 16);
841 // get canonical identifier of an address' group
842 // no two connections will be attempted to addresses with the same group
843 std::vector<unsigned char> CNetAddr::GetGroup() const
845 std::vector<unsigned char> vchRet;
846 uint8_t nClass = NET_IPV6;
850 // all local addresses belong to the same group
857 // all unroutable addresses belong to the same group
860 nClass = NET_UNROUTABLE;
863 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
864 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
865 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
870 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
871 else if (IsRFC3964())
876 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
877 else if (IsRFC4380())
879 vchRet.push_back(NET_IPV4);
880 vchRet.push_back(GetByte(3) ^ 0xFF);
881 vchRet.push_back(GetByte(2) ^ 0xFF);
896 // for he.net, use /36 groups
897 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
899 // for the rest of the IPv6 network, use /32 groups
903 vchRet.push_back(nClass);
906 vchRet.push_back(GetByte(15 - nStartByte));
911 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
916 uint64_t CNetAddr::GetHash() const
918 uint256 hash = Hash(&ip[0], &ip[16]);
920 memcpy(&nRet, &hash, sizeof(nRet));
924 // private extensions to enum Network, only returned by GetExtNetwork,
925 // and only used in GetReachabilityFrom
926 static const int NET_UNKNOWN = NET_MAX + 0;
927 static const int NET_TEREDO = NET_MAX + 1;
928 int static GetExtNetwork(const CNetAddr *addr)
932 if (addr->IsRFC4380())
934 return addr->GetNetwork();
937 /** Calculates a metric for how reachable (*this) is from a given partner */
938 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
951 return REACH_UNREACHABLE;
953 int ourNet = GetExtNetwork(this);
954 int theirNet = GetExtNetwork(paddrPartner);
955 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
960 default: return REACH_DEFAULT;
961 case NET_IPV4: return REACH_IPV4;
965 default: return REACH_DEFAULT;
966 case NET_TEREDO: return REACH_TEREDO;
967 case NET_IPV4: return REACH_IPV4;
968 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
972 default: return REACH_DEFAULT;
973 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
974 case NET_TOR: return REACH_PRIVATE;
978 default: return REACH_DEFAULT;
979 case NET_I2P: return REACH_PRIVATE;
983 default: return REACH_DEFAULT;
984 case NET_TEREDO: return REACH_TEREDO;
985 case NET_IPV6: return REACH_IPV6_WEAK;
986 case NET_IPV4: return REACH_IPV4;
992 default: return REACH_DEFAULT;
993 case NET_TEREDO: return REACH_TEREDO;
994 case NET_IPV6: return REACH_IPV6_WEAK;
995 case NET_IPV4: return REACH_IPV4;
996 case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
997 case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
1002 void CService::Init()
1007 CService::CService()
1012 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
1016 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
1021 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
1026 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1028 assert(addr.sin_family == AF_INET);
1032 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1034 assert(addr.sin6_family == AF_INET6);
1038 bool CService::SetSockAddr(const struct sockaddr *paddr)
1040 switch (paddr->sa_family) {
1042 *this = CService(*(const struct sockaddr_in*)paddr);
1046 *this = CService(*(const struct sockaddr_in6*)paddr);
1054 CService::CService(const char *pszIpPort, bool fAllowLookup)
1058 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1062 CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
1066 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1070 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1074 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1078 CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
1082 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1086 unsigned short CService::GetPort() const
1091 bool operator==(const CService& a, const CService& b)
1093 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1096 bool operator!=(const CService& a, const CService& b)
1098 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1101 bool operator<(const CService& a, const CService& b)
1103 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1106 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1109 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1111 *addrlen = sizeof(struct sockaddr_in);
1112 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1113 memset(paddrin, 0, *addrlen);
1114 if (!GetInAddr(&paddrin->sin_addr))
1116 paddrin->sin_family = AF_INET;
1117 paddrin->sin_port = htons(port);
1122 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1124 *addrlen = sizeof(struct sockaddr_in6);
1125 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1126 memset(paddrin6, 0, *addrlen);
1127 if (!GetIn6Addr(&paddrin6->sin6_addr))
1129 paddrin6->sin6_family = AF_INET6;
1130 paddrin6->sin6_port = htons(port);
1137 std::vector<unsigned char> CService::GetKey() const
1139 std::vector<unsigned char> vKey;
1141 memcpy(&vKey[0], ip, 16);
1142 vKey[16] = port / 0x100;
1143 vKey[17] = port & 0x0FF;
1147 std::string CService::ToStringPort() const
1149 return strprintf("%u", port);
1152 std::string CService::ToStringIPPort() const
1154 if (IsIPv4() || IsTor() || IsI2P()) {
1155 return ToStringIP() + ":" + ToStringPort();
1157 return "[" + ToStringIP() + "]:" + ToStringPort();
1161 std::string CService::ToString() const
1163 return ToStringIPPort();
1166 void CService::SetPort(unsigned short portIn)
1171 bool CloseSocket(SOCKET& hSocket)
1173 if (hSocket == INVALID_SOCKET)
1176 int ret = closesocket(hSocket);
1178 int ret = close(hSocket);
1180 hSocket = INVALID_SOCKET;
1181 return ret != SOCKET_ERROR;