1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "config/bitcoin-config.h"
17 #include "utilstrencodings.h"
20 #ifdef HAVE_GETADDRINFO_A
21 #undef HAVE_GETADDRINFO_A
25 #ifdef HAVE_GETADDRINFO_A
31 #include <arpa/inet.h>
36 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
37 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
38 #include <boost/thread.hpp>
40 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
41 #define MSG_NOSIGNAL 0
45 static proxyType proxyInfo[NET_MAX];
46 static proxyType nameProxy;
47 static CCriticalSection cs_proxyInfos;
48 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
49 bool fNameLookup = false;
51 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
53 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
54 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
56 enum Network ParseNetwork(std::string net) {
58 if (net == "ipv4") return NET_IPV4;
59 if (net == "ipv6") return NET_IPV6;
60 if (net == "tor" || net == "onion") return NET_TOR;
61 return NET_UNROUTABLE;
64 std::string GetNetworkName(enum Network net) {
67 case NET_IPV4: return "ipv4";
68 case NET_IPV6: return "ipv6";
69 case NET_TOR: return "onion";
74 void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
75 size_t colon = in.find_last_of(':');
76 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
77 bool fHaveColon = colon != in.npos;
78 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
79 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
80 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
82 if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
83 in = in.substr(0, colon);
87 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
88 hostOut = in.substr(1, in.size()-2);
93 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
99 if (addr.SetSpecial(std::string(pszName))) {
105 #ifdef HAVE_GETADDRINFO_A
106 struct in_addr ipv4_addr;
107 #ifdef HAVE_INET_PTON
108 if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
109 vIP.push_back(CNetAddr(ipv4_addr));
113 struct in6_addr ipv6_addr;
114 if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
115 vIP.push_back(CNetAddr(ipv6_addr));
119 ipv4_addr.s_addr = inet_addr(pszName);
120 if (ipv4_addr.s_addr != INADDR_NONE) {
121 vIP.push_back(CNetAddr(ipv4_addr));
127 struct addrinfo aiHint;
128 memset(&aiHint, 0, sizeof(struct addrinfo));
129 aiHint.ai_socktype = SOCK_STREAM;
130 aiHint.ai_protocol = IPPROTO_TCP;
131 aiHint.ai_family = AF_UNSPEC;
133 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
135 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
138 struct addrinfo *aiRes = NULL;
139 #ifdef HAVE_GETADDRINFO_A
140 struct gaicb gcb, *query = &gcb;
141 memset(query, 0, sizeof(struct gaicb));
142 gcb.ar_name = pszName;
143 gcb.ar_request = &aiHint;
144 int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
149 // Should set the timeout limit to a reasonable value to avoid
150 // generating unnecessary checking call during the polling loop,
151 // while it can still response to stop request quick enough.
152 // 2 seconds looks fine in our situation.
153 struct timespec ts = { 2, 0 };
154 gai_suspend(&query, 1, &ts);
155 boost::this_thread::interruption_point();
157 nErr = gai_error(query);
159 aiRes = query->ar_result;
160 } while (nErr == EAI_INPROGRESS);
162 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
167 struct addrinfo *aiTrav = aiRes;
168 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
170 if (aiTrav->ai_family == AF_INET)
172 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
173 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
176 if (aiTrav->ai_family == AF_INET6)
178 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
179 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
182 aiTrav = aiTrav->ai_next;
187 return (vIP.size() > 0);
190 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
192 std::string strHost(pszName);
195 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
197 strHost = strHost.substr(1, strHost.size() - 2);
200 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
203 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
207 int port = portDefault;
208 std::string hostname = "";
209 SplitHostPort(std::string(pszName), port, hostname);
211 std::vector<CNetAddr> vIP;
212 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
215 vAddr.resize(vIP.size());
216 for (unsigned int i = 0; i < vIP.size(); i++)
217 vAddr[i] = CService(vIP[i], port);
221 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
223 std::vector<CService> vService;
224 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
231 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
233 return Lookup(pszName, addr, portDefault, false);
236 struct timeval MillisToTimeval(int64_t nTimeout)
238 struct timeval timeout;
239 timeout.tv_sec = nTimeout / 1000;
240 timeout.tv_usec = (nTimeout % 1000) * 1000;
245 * Read bytes from socket. This will either read the full number of bytes requested
246 * or return False on error or timeout.
247 * This function can be interrupted by boost thread interrupt.
249 * @param data Buffer to receive into
250 * @param len Length of data to receive
251 * @param timeout Timeout in milliseconds for receive operation
253 * @note This function requires that hSocket is in non-blocking mode.
255 bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
257 int64_t curTime = GetTimeMillis();
258 int64_t endTime = curTime + timeout;
259 // Maximum time to wait in one select call. It will take up until this time (in millis)
260 // to break off in case of an interruption.
261 const int64_t maxWait = 1000;
262 while (len > 0 && curTime < endTime) {
263 ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
267 } else if (ret == 0) { // Unexpected disconnection
269 } else { // Other error or blocking
270 int nErr = WSAGetLastError();
271 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
272 if (!IsSelectableSocket(hSocket)) {
275 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
278 FD_SET(hSocket, &fdset);
279 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
280 if (nRet == SOCKET_ERROR) {
287 boost::this_thread::interruption_point();
288 curTime = GetTimeMillis();
293 struct ProxyCredentials
295 std::string username;
296 std::string password;
299 /** Connect using SOCKS5 (as described in RFC1928) */
300 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
302 LogPrintf("SOCKS5 connecting %s\n", strDest);
303 if (strDest.size() > 255) {
304 CloseSocket(hSocket);
305 return error("Hostname too long");
307 // Accepted authentication methods
308 std::vector<uint8_t> vSocks5Init;
309 vSocks5Init.push_back(0x05);
311 vSocks5Init.push_back(0x02); // # METHODS
312 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
313 vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
315 vSocks5Init.push_back(0x01); // # METHODS
316 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
318 ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
319 if (ret != (ssize_t)vSocks5Init.size()) {
320 CloseSocket(hSocket);
321 return error("Error sending to proxy");
324 if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
325 CloseSocket(hSocket);
326 return error("Error reading proxy response");
328 if (pchRet1[0] != 0x05) {
329 CloseSocket(hSocket);
330 return error("Proxy failed to initialize");
332 if (pchRet1[1] == 0x02 && auth) {
333 // Perform username/password authentication (as described in RFC1929)
334 std::vector<uint8_t> vAuth;
335 vAuth.push_back(0x01);
336 if (auth->username.size() > 255 || auth->password.size() > 255)
337 return error("Proxy username or password too long");
338 vAuth.push_back(auth->username.size());
339 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
340 vAuth.push_back(auth->password.size());
341 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
342 ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
343 if (ret != (ssize_t)vAuth.size()) {
344 CloseSocket(hSocket);
345 return error("Error sending authentication to proxy");
347 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
349 if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
350 CloseSocket(hSocket);
351 return error("Error reading proxy authentication response");
353 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
354 CloseSocket(hSocket);
355 return error("Proxy authentication unsuccessful");
357 } else if (pchRet1[1] == 0x00) {
358 // Perform no authentication
360 CloseSocket(hSocket);
361 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
363 std::vector<uint8_t> vSocks5;
364 vSocks5.push_back(0x05); // VER protocol version
365 vSocks5.push_back(0x01); // CMD CONNECT
366 vSocks5.push_back(0x00); // RSV Reserved
367 vSocks5.push_back(0x03); // ATYP DOMAINNAME
368 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
369 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
370 vSocks5.push_back((port >> 8) & 0xFF);
371 vSocks5.push_back((port >> 0) & 0xFF);
372 ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
373 if (ret != (ssize_t)vSocks5.size()) {
374 CloseSocket(hSocket);
375 return error("Error sending to proxy");
378 if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
379 CloseSocket(hSocket);
380 return error("Error reading proxy response");
382 if (pchRet2[0] != 0x05) {
383 CloseSocket(hSocket);
384 return error("Proxy failed to accept request");
386 if (pchRet2[1] != 0x00) {
387 CloseSocket(hSocket);
390 case 0x01: return error("Proxy error: general failure");
391 case 0x02: return error("Proxy error: connection not allowed");
392 case 0x03: return error("Proxy error: network unreachable");
393 case 0x04: return error("Proxy error: host unreachable");
394 case 0x05: return error("Proxy error: connection refused");
395 case 0x06: return error("Proxy error: TTL expired");
396 case 0x07: return error("Proxy error: protocol error");
397 case 0x08: return error("Proxy error: address type not supported");
398 default: return error("Proxy error: unknown");
401 if (pchRet2[2] != 0x00) {
402 CloseSocket(hSocket);
403 return error("Error: malformed proxy response");
408 case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
409 case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
412 ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
414 CloseSocket(hSocket);
415 return error("Error reading from proxy");
417 int nRecv = pchRet3[0];
418 ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
421 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
424 CloseSocket(hSocket);
425 return error("Error reading from proxy");
427 if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
428 CloseSocket(hSocket);
429 return error("Error reading from proxy");
431 LogPrintf("SOCKS5 connected %s\n", strDest);
435 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
437 hSocketRet = INVALID_SOCKET;
439 struct sockaddr_storage sockaddr;
440 socklen_t len = sizeof(sockaddr);
441 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
442 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
446 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
447 if (hSocket == INVALID_SOCKET)
452 // Different way of disabling SIGPIPE on BSD
453 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
456 //Disable Nagle's algorithm
458 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
460 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
463 // Set to non-blocking
464 if (!SetSocketNonBlocking(hSocket, true))
465 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
467 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
469 int nErr = WSAGetLastError();
470 // WSAEINVAL is here because some legacy version of winsock uses it
471 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
473 struct timeval timeout = MillisToTimeval(nTimeout);
476 FD_SET(hSocket, &fdset);
477 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
480 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
481 CloseSocket(hSocket);
484 if (nRet == SOCKET_ERROR)
486 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
487 CloseSocket(hSocket);
490 socklen_t nRetSize = sizeof(nRet);
492 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
494 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
497 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
498 CloseSocket(hSocket);
503 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
504 CloseSocket(hSocket);
509 else if (WSAGetLastError() != WSAEISCONN)
514 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
515 CloseSocket(hSocket);
520 hSocketRet = hSocket;
524 bool SetProxy(enum Network net, const proxyType &addrProxy) {
525 assert(net >= 0 && net < NET_MAX);
526 if (!addrProxy.IsValid())
529 proxyInfo[net] = addrProxy;
533 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
534 assert(net >= 0 && net < NET_MAX);
536 if (!proxyInfo[net].IsValid())
538 proxyInfoOut = proxyInfo[net];
542 bool SetNameProxy(const proxyType &addrProxy) {
543 if (!addrProxy.IsValid())
546 nameProxy = addrProxy;
550 bool GetNameProxy(proxyType &nameProxyOut) {
552 if(!nameProxy.IsValid())
554 nameProxyOut = nameProxy;
558 bool HaveNameProxy() {
560 return nameProxy.IsValid();
563 bool IsProxy(const CNetAddr &addr) {
565 for (int i = 0; i < NET_MAX; i++) {
566 if (addr == (CNetAddr)proxyInfo[i].proxy)
572 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
574 SOCKET hSocket = INVALID_SOCKET;
575 // first connect to proxy server
576 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
577 if (outProxyConnectionFailed)
578 *outProxyConnectionFailed = true;
581 // do socks negotiation
582 if (proxy.randomize_credentials) {
583 ProxyCredentials random_auth;
584 random_auth.username = strprintf("%i", insecure_rand());
585 random_auth.password = strprintf("%i", insecure_rand());
586 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
589 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
593 hSocketRet = hSocket;
597 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
600 if (outProxyConnectionFailed)
601 *outProxyConnectionFailed = false;
603 if (GetProxy(addrDest.GetNetwork(), proxy))
604 return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
605 else // no proxy needed (none set for target network)
606 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
609 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
612 int port = portDefault;
614 if (outProxyConnectionFailed)
615 *outProxyConnectionFailed = false;
617 SplitHostPort(std::string(pszDest), port, strDest);
620 GetNameProxy(nameProxy);
622 CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
623 if (addrResolved.IsValid()) {
625 return ConnectSocket(addr, hSocketRet, nTimeout);
628 addr = CService("0.0.0.0:0");
630 if (!HaveNameProxy())
632 return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
635 void CNetAddr::Init()
637 memset(ip, 0, sizeof(ip));
640 void CNetAddr::SetIP(const CNetAddr& ipIn)
642 memcpy(ip, ipIn.ip, sizeof(ip));
645 void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
650 memcpy(ip, pchIPv4, 12);
651 memcpy(ip+12, ip_in, 4);
654 memcpy(ip, ip_in, 16);
657 assert(!"invalid network");
661 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
663 bool CNetAddr::SetSpecial(const std::string &strName)
665 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
666 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
667 if (vchAddr.size() != 16-sizeof(pchOnionCat))
669 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
670 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
671 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
682 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
684 SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
687 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
689 SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
692 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
695 std::vector<CNetAddr> vIP;
696 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
700 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
703 std::vector<CNetAddr> vIP;
704 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
708 unsigned int CNetAddr::GetByte(int n) const
713 bool CNetAddr::IsIPv4() const
715 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
718 bool CNetAddr::IsIPv6() const
720 return (!IsIPv4() && !IsTor());
723 bool CNetAddr::IsRFC1918() const
727 (GetByte(3) == 192 && GetByte(2) == 168) ||
728 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
731 bool CNetAddr::IsRFC2544() const
733 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
736 bool CNetAddr::IsRFC3927() const
738 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
741 bool CNetAddr::IsRFC6598() const
743 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
746 bool CNetAddr::IsRFC5737() const
748 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
749 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
750 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
753 bool CNetAddr::IsRFC3849() const
755 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
758 bool CNetAddr::IsRFC3964() const
760 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
763 bool CNetAddr::IsRFC6052() const
765 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
766 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
769 bool CNetAddr::IsRFC4380() const
771 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
774 bool CNetAddr::IsRFC4862() const
776 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
777 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
780 bool CNetAddr::IsRFC4193() const
782 return ((GetByte(15) & 0xFE) == 0xFC);
785 bool CNetAddr::IsRFC6145() const
787 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
788 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
791 bool CNetAddr::IsRFC4843() const
793 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
796 bool CNetAddr::IsTor() const
798 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
801 bool CNetAddr::IsLocal() const
804 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
807 // IPv6 loopback (::1/128)
808 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
809 if (memcmp(ip, pchLocal, 16) == 0)
815 bool CNetAddr::IsMulticast() const
817 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
818 || (GetByte(15) == 0xFF);
821 bool CNetAddr::IsValid() const
823 // Cleanup 3-byte shifted addresses caused by garbage in size field
824 // of addr messages from versions before 0.2.9 checksum.
825 // Two consecutive addr messages look like this:
826 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
827 // so if the first length field is garbled, it reads the second batch
828 // of addr misaligned by 3 bytes.
829 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
832 // unspecified IPv6 address (::/128)
833 unsigned char ipNone[16] = {};
834 if (memcmp(ip, ipNone, 16) == 0)
837 // documentation IPv6 address
844 uint32_t ipNone = INADDR_NONE;
845 if (memcmp(ip+12, &ipNone, 4) == 0)
850 if (memcmp(ip+12, &ipNone, 4) == 0)
857 bool CNetAddr::IsRoutable() const
859 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
862 enum Network CNetAddr::GetNetwork() const
865 return NET_UNROUTABLE;
876 std::string CNetAddr::ToStringIP() const
879 return EncodeBase32(&ip[6], 10) + ".onion";
880 CService serv(*this, 0);
881 struct sockaddr_storage sockaddr;
882 socklen_t socklen = sizeof(sockaddr);
883 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
884 char name[1025] = "";
885 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
886 return std::string(name);
889 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
891 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
892 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
893 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
894 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
895 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
898 std::string CNetAddr::ToString() const
903 bool operator==(const CNetAddr& a, const CNetAddr& b)
905 return (memcmp(a.ip, b.ip, 16) == 0);
908 bool operator!=(const CNetAddr& a, const CNetAddr& b)
910 return (memcmp(a.ip, b.ip, 16) != 0);
913 bool operator<(const CNetAddr& a, const CNetAddr& b)
915 return (memcmp(a.ip, b.ip, 16) < 0);
918 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
922 memcpy(pipv4Addr, ip+12, 4);
926 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
928 memcpy(pipv6Addr, ip, 16);
932 // get canonical identifier of an address' group
933 // no two connections will be attempted to addresses with the same group
934 std::vector<unsigned char> CNetAddr::GetGroup() const
936 std::vector<unsigned char> vchRet;
937 int nClass = NET_IPV6;
941 // all local addresses belong to the same group
948 // all unroutable addresses belong to the same group
951 nClass = NET_UNROUTABLE;
954 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
955 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
956 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
961 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
962 else if (IsRFC3964())
967 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
968 else if (IsRFC4380())
970 vchRet.push_back(NET_IPV4);
971 vchRet.push_back(GetByte(3) ^ 0xFF);
972 vchRet.push_back(GetByte(2) ^ 0xFF);
981 // for he.net, use /36 groups
982 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
984 // for the rest of the IPv6 network, use /32 groups
988 vchRet.push_back(nClass);
991 vchRet.push_back(GetByte(15 - nStartByte));
996 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
1001 uint64_t CNetAddr::GetHash() const
1003 uint256 hash = Hash(&ip[0], &ip[16]);
1005 memcpy(&nRet, &hash, sizeof(nRet));
1009 // private extensions to enum Network, only returned by GetExtNetwork,
1010 // and only used in GetReachabilityFrom
1011 static const int NET_UNKNOWN = NET_MAX + 0;
1012 static const int NET_TEREDO = NET_MAX + 1;
1013 int static GetExtNetwork(const CNetAddr *addr)
1017 if (addr->IsRFC4380())
1019 return addr->GetNetwork();
1022 /** Calculates a metric for how reachable (*this) is from a given partner */
1023 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
1036 return REACH_UNREACHABLE;
1038 int ourNet = GetExtNetwork(this);
1039 int theirNet = GetExtNetwork(paddrPartner);
1040 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
1045 default: return REACH_DEFAULT;
1046 case NET_IPV4: return REACH_IPV4;
1050 default: return REACH_DEFAULT;
1051 case NET_TEREDO: return REACH_TEREDO;
1052 case NET_IPV4: return REACH_IPV4;
1053 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
1057 default: return REACH_DEFAULT;
1058 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
1059 case NET_TOR: return REACH_PRIVATE;
1063 default: return REACH_DEFAULT;
1064 case NET_TEREDO: return REACH_TEREDO;
1065 case NET_IPV6: return REACH_IPV6_WEAK;
1066 case NET_IPV4: return REACH_IPV4;
1069 case NET_UNROUTABLE:
1072 default: return REACH_DEFAULT;
1073 case NET_TEREDO: return REACH_TEREDO;
1074 case NET_IPV6: return REACH_IPV6_WEAK;
1075 case NET_IPV4: return REACH_IPV4;
1076 case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
1081 void CService::Init()
1086 CService::CService()
1091 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
1095 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
1099 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
1103 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1105 assert(addr.sin_family == AF_INET);
1108 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1110 assert(addr.sin6_family == AF_INET6);
1113 bool CService::SetSockAddr(const struct sockaddr *paddr)
1115 switch (paddr->sa_family) {
1117 *this = CService(*(const struct sockaddr_in*)paddr);
1120 *this = CService(*(const struct sockaddr_in6*)paddr);
1127 CService::CService(const char *pszIpPort, bool fAllowLookup)
1131 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1135 CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
1139 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1143 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1147 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1151 CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
1155 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1159 unsigned short CService::GetPort() const
1164 bool operator==(const CService& a, const CService& b)
1166 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1169 bool operator!=(const CService& a, const CService& b)
1171 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1174 bool operator<(const CService& a, const CService& b)
1176 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1179 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1182 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1184 *addrlen = sizeof(struct sockaddr_in);
1185 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1186 memset(paddrin, 0, *addrlen);
1187 if (!GetInAddr(&paddrin->sin_addr))
1189 paddrin->sin_family = AF_INET;
1190 paddrin->sin_port = htons(port);
1194 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1196 *addrlen = sizeof(struct sockaddr_in6);
1197 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1198 memset(paddrin6, 0, *addrlen);
1199 if (!GetIn6Addr(&paddrin6->sin6_addr))
1201 paddrin6->sin6_family = AF_INET6;
1202 paddrin6->sin6_port = htons(port);
1208 std::vector<unsigned char> CService::GetKey() const
1210 std::vector<unsigned char> vKey;
1212 memcpy(&vKey[0], ip, 16);
1213 vKey[16] = port / 0x100;
1214 vKey[17] = port & 0x0FF;
1218 std::string CService::ToStringPort() const
1220 return strprintf("%u", port);
1223 std::string CService::ToStringIPPort() const
1225 if (IsIPv4() || IsTor()) {
1226 return ToStringIP() + ":" + ToStringPort();
1228 return "[" + ToStringIP() + "]:" + ToStringPort();
1232 std::string CService::ToString() const
1234 return ToStringIPPort();
1237 void CService::SetPort(unsigned short portIn)
1245 memset(netmask, 0, sizeof(netmask));
1248 CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
1250 size_t slash = strSubnet.find_last_of('/');
1251 std::vector<CNetAddr> vIP;
1254 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
1255 memset(netmask, 255, sizeof(netmask));
1257 std::string strAddress = strSubnet.substr(0, slash);
1258 if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
1261 if (slash != strSubnet.npos)
1263 std::string strNetmask = strSubnet.substr(slash + 1);
1265 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
1266 const int astartofs = network.IsIPv4() ? 12 : 0;
1267 if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
1269 if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
1272 // Clear bits [n..127]
1273 for (; n < 128; ++n)
1274 netmask[n>>3] &= ~(1<<(7-(n&7)));
1281 else // If not a valid number, try full netmask syntax
1283 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
1285 // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
1286 // we don't want pchIPv4 to be part of the mask.
1287 for(int x=astartofs; x<16; ++x)
1288 netmask[x] = vIP[0].ip[x];
1302 // Normalize network according to netmask
1303 for(int x=0; x<16; ++x)
1304 network.ip[x] &= netmask[x];
1307 bool CSubNet::Match(const CNetAddr &addr) const
1309 if (!valid || !addr.IsValid())
1311 for(int x=0; x<16; ++x)
1312 if ((addr.ip[x] & netmask[x]) != network.ip[x])
1317 std::string CSubNet::ToString() const
1319 std::string strNetmask;
1320 if (network.IsIPv4())
1321 strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
1323 strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
1324 netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
1325 netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
1326 netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
1327 netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
1328 return network.ToString() + "/" + strNetmask;
1331 bool CSubNet::IsValid() const
1336 bool operator==(const CSubNet& a, const CSubNet& b)
1338 return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1341 bool operator!=(const CSubNet& a, const CSubNet& b)
1346 bool operator<(const CSubNet& a, const CSubNet& b)
1348 return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
1352 std::string NetworkErrorString(int err)
1356 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1357 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1358 buf, sizeof(buf), NULL))
1360 return strprintf("%s (%d)", buf, err);
1364 return strprintf("Unknown error (%d)", err);
1368 std::string NetworkErrorString(int err)
1371 const char *s = buf;
1373 /* Too bad there are two incompatible implementations of the
1374 * thread-safe strerror. */
1375 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1376 s = strerror_r(err, buf, sizeof(buf));
1377 #else /* POSIX variant always returns message in buffer */
1378 if (strerror_r(err, buf, sizeof(buf)))
1381 return strprintf("%s (%d)", s, err);
1385 bool CloseSocket(SOCKET& hSocket)
1387 if (hSocket == INVALID_SOCKET)
1390 int ret = closesocket(hSocket);
1392 int ret = close(hSocket);
1394 hSocket = INVALID_SOCKET;
1395 return ret != SOCKET_ERROR;
1398 bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
1403 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
1405 int fFlags = fcntl(hSocket, F_GETFL, 0);
1406 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
1408 CloseSocket(hSocket);
1414 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
1416 int fFlags = fcntl(hSocket, F_GETFL, 0);
1417 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
1419 CloseSocket(hSocket);