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 resonable 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);
237 * Convert milliseconds to a struct timeval for select.
239 struct timeval static MillisToTimeval(int64_t nTimeout)
241 struct timeval timeout;
242 timeout.tv_sec = nTimeout / 1000;
243 timeout.tv_usec = (nTimeout % 1000) * 1000;
248 * Read bytes from socket. This will either read the full number of bytes requested
249 * or return False on error or timeout.
250 * This function can be interrupted by boost thread interrupt.
252 * @param data Buffer to receive into
253 * @param len Length of data to receive
254 * @param timeout Timeout in milliseconds for receive operation
256 * @note This function requires that hSocket is in non-blocking mode.
258 bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
260 int64_t curTime = GetTimeMillis();
261 int64_t endTime = curTime + timeout;
262 // Maximum time to wait in one select call. It will take up until this time (in millis)
263 // to break off in case of an interruption.
264 const int64_t maxWait = 1000;
265 while (len > 0 && curTime < endTime) {
266 ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
270 } else if (ret == 0) { // Unexpected disconnection
272 } else { // Other error or blocking
273 int nErr = WSAGetLastError();
274 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
275 if (!IsSelectableSocket(hSocket)) {
278 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
281 FD_SET(hSocket, &fdset);
282 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
283 if (nRet == SOCKET_ERROR) {
290 boost::this_thread::interruption_point();
291 curTime = GetTimeMillis();
296 struct ProxyCredentials
298 std::string username;
299 std::string password;
302 /** Connect using SOCKS5 (as described in RFC1928) */
303 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
305 LogPrintf("SOCKS5 connecting %s\n", strDest);
306 if (strDest.size() > 255) {
307 CloseSocket(hSocket);
308 return error("Hostname too long");
310 // Accepted authentication methods
311 std::vector<uint8_t> vSocks5Init;
312 vSocks5Init.push_back(0x05);
314 vSocks5Init.push_back(0x02); // # METHODS
315 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
316 vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
318 vSocks5Init.push_back(0x01); // # METHODS
319 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
321 ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
322 if (ret != (ssize_t)vSocks5Init.size()) {
323 CloseSocket(hSocket);
324 return error("Error sending to proxy");
327 if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
328 CloseSocket(hSocket);
329 return error("Error reading proxy response");
331 if (pchRet1[0] != 0x05) {
332 CloseSocket(hSocket);
333 return error("Proxy failed to initialize");
335 if (pchRet1[1] == 0x02 && auth) {
336 // Perform username/password authentication (as described in RFC1929)
337 std::vector<uint8_t> vAuth;
338 vAuth.push_back(0x01);
339 if (auth->username.size() > 255 || auth->password.size() > 255)
340 return error("Proxy username or password too long");
341 vAuth.push_back(auth->username.size());
342 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
343 vAuth.push_back(auth->password.size());
344 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
345 ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
346 if (ret != (ssize_t)vAuth.size()) {
347 CloseSocket(hSocket);
348 return error("Error sending authentication to proxy");
350 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
352 if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
353 CloseSocket(hSocket);
354 return error("Error reading proxy authentication response");
356 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
357 CloseSocket(hSocket);
358 return error("Proxy authentication unsuccessful");
360 } else if (pchRet1[1] == 0x00) {
361 // Perform no authentication
363 CloseSocket(hSocket);
364 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
366 std::vector<uint8_t> vSocks5;
367 vSocks5.push_back(0x05); // VER protocol version
368 vSocks5.push_back(0x01); // CMD CONNECT
369 vSocks5.push_back(0x00); // RSV Reserved
370 vSocks5.push_back(0x03); // ATYP DOMAINNAME
371 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
372 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
373 vSocks5.push_back((port >> 8) & 0xFF);
374 vSocks5.push_back((port >> 0) & 0xFF);
375 ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
376 if (ret != (ssize_t)vSocks5.size()) {
377 CloseSocket(hSocket);
378 return error("Error sending to proxy");
381 if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
382 CloseSocket(hSocket);
383 return error("Error reading proxy response");
385 if (pchRet2[0] != 0x05) {
386 CloseSocket(hSocket);
387 return error("Proxy failed to accept request");
389 if (pchRet2[1] != 0x00) {
390 CloseSocket(hSocket);
393 case 0x01: return error("Proxy error: general failure");
394 case 0x02: return error("Proxy error: connection not allowed");
395 case 0x03: return error("Proxy error: network unreachable");
396 case 0x04: return error("Proxy error: host unreachable");
397 case 0x05: return error("Proxy error: connection refused");
398 case 0x06: return error("Proxy error: TTL expired");
399 case 0x07: return error("Proxy error: protocol error");
400 case 0x08: return error("Proxy error: address type not supported");
401 default: return error("Proxy error: unknown");
404 if (pchRet2[2] != 0x00) {
405 CloseSocket(hSocket);
406 return error("Error: malformed proxy response");
411 case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
412 case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
415 ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
417 CloseSocket(hSocket);
418 return error("Error reading from proxy");
420 int nRecv = pchRet3[0];
421 ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
424 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
427 CloseSocket(hSocket);
428 return error("Error reading from proxy");
430 if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
431 CloseSocket(hSocket);
432 return error("Error reading from proxy");
434 LogPrintf("SOCKS5 connected %s\n", strDest);
438 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
440 hSocketRet = INVALID_SOCKET;
442 struct sockaddr_storage sockaddr;
443 socklen_t len = sizeof(sockaddr);
444 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
445 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
449 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
450 if (hSocket == INVALID_SOCKET)
455 // Different way of disabling SIGPIPE on BSD
456 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
459 //Disable Nagle's algorithm
461 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
463 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
466 // Set to non-blocking
467 if (!SetSocketNonBlocking(hSocket, true))
468 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
470 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
472 int nErr = WSAGetLastError();
473 // WSAEINVAL is here because some legacy version of winsock uses it
474 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
476 struct timeval timeout = MillisToTimeval(nTimeout);
479 FD_SET(hSocket, &fdset);
480 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
483 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
484 CloseSocket(hSocket);
487 if (nRet == SOCKET_ERROR)
489 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
490 CloseSocket(hSocket);
493 socklen_t nRetSize = sizeof(nRet);
495 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
497 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
500 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
501 CloseSocket(hSocket);
506 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
507 CloseSocket(hSocket);
512 else if (WSAGetLastError() != WSAEISCONN)
517 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
518 CloseSocket(hSocket);
523 hSocketRet = hSocket;
527 bool SetProxy(enum Network net, const proxyType &addrProxy) {
528 assert(net >= 0 && net < NET_MAX);
529 if (!addrProxy.IsValid())
532 proxyInfo[net] = addrProxy;
536 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
537 assert(net >= 0 && net < NET_MAX);
539 if (!proxyInfo[net].IsValid())
541 proxyInfoOut = proxyInfo[net];
545 bool SetNameProxy(const proxyType &addrProxy) {
546 if (!addrProxy.IsValid())
549 nameProxy = addrProxy;
553 bool GetNameProxy(proxyType &nameProxyOut) {
555 if(!nameProxy.IsValid())
557 nameProxyOut = nameProxy;
561 bool HaveNameProxy() {
563 return nameProxy.IsValid();
566 bool IsProxy(const CNetAddr &addr) {
568 for (int i = 0; i < NET_MAX; i++) {
569 if (addr == (CNetAddr)proxyInfo[i].proxy)
575 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
577 SOCKET hSocket = INVALID_SOCKET;
578 // first connect to proxy server
579 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
580 if (outProxyConnectionFailed)
581 *outProxyConnectionFailed = true;
584 // do socks negotiation
585 if (proxy.randomize_credentials) {
586 ProxyCredentials random_auth;
587 random_auth.username = strprintf("%i", insecure_rand());
588 random_auth.password = strprintf("%i", insecure_rand());
589 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
592 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
596 hSocketRet = hSocket;
600 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
603 if (outProxyConnectionFailed)
604 *outProxyConnectionFailed = false;
606 if (GetProxy(addrDest.GetNetwork(), proxy))
607 return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
608 else // no proxy needed (none set for target network)
609 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
612 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
615 int port = portDefault;
617 if (outProxyConnectionFailed)
618 *outProxyConnectionFailed = false;
620 SplitHostPort(std::string(pszDest), port, strDest);
623 GetNameProxy(nameProxy);
625 CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
626 if (addrResolved.IsValid()) {
628 return ConnectSocket(addr, hSocketRet, nTimeout);
631 addr = CService("0.0.0.0:0");
633 if (!HaveNameProxy())
635 return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
638 void CNetAddr::Init()
640 memset(ip, 0, sizeof(ip));
643 void CNetAddr::SetIP(const CNetAddr& ipIn)
645 memcpy(ip, ipIn.ip, sizeof(ip));
648 void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
653 memcpy(ip, pchIPv4, 12);
654 memcpy(ip+12, ip_in, 4);
657 memcpy(ip, ip_in, 16);
660 assert(!"invalid network");
664 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
666 bool CNetAddr::SetSpecial(const std::string &strName)
668 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
669 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
670 if (vchAddr.size() != 16-sizeof(pchOnionCat))
672 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
673 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
674 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
685 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
687 SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
690 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
692 SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
695 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
698 std::vector<CNetAddr> vIP;
699 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
703 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
706 std::vector<CNetAddr> vIP;
707 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
711 unsigned int CNetAddr::GetByte(int n) const
716 bool CNetAddr::IsIPv4() const
718 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
721 bool CNetAddr::IsIPv6() const
723 return (!IsIPv4() && !IsTor());
726 bool CNetAddr::IsRFC1918() const
730 (GetByte(3) == 192 && GetByte(2) == 168) ||
731 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
734 bool CNetAddr::IsRFC2544() const
736 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
739 bool CNetAddr::IsRFC3927() const
741 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
744 bool CNetAddr::IsRFC6598() const
746 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
749 bool CNetAddr::IsRFC5737() const
751 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
752 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
753 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
756 bool CNetAddr::IsRFC3849() const
758 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
761 bool CNetAddr::IsRFC3964() const
763 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
766 bool CNetAddr::IsRFC6052() const
768 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
769 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
772 bool CNetAddr::IsRFC4380() const
774 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
777 bool CNetAddr::IsRFC4862() const
779 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
780 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
783 bool CNetAddr::IsRFC4193() const
785 return ((GetByte(15) & 0xFE) == 0xFC);
788 bool CNetAddr::IsRFC6145() const
790 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
791 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
794 bool CNetAddr::IsRFC4843() const
796 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
799 bool CNetAddr::IsTor() const
801 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
804 bool CNetAddr::IsLocal() const
807 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
810 // IPv6 loopback (::1/128)
811 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
812 if (memcmp(ip, pchLocal, 16) == 0)
818 bool CNetAddr::IsMulticast() const
820 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
821 || (GetByte(15) == 0xFF);
824 bool CNetAddr::IsValid() const
826 // Cleanup 3-byte shifted addresses caused by garbage in size field
827 // of addr messages from versions before 0.2.9 checksum.
828 // Two consecutive addr messages look like this:
829 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
830 // so if the first length field is garbled, it reads the second batch
831 // of addr misaligned by 3 bytes.
832 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
835 // unspecified IPv6 address (::/128)
836 unsigned char ipNone[16] = {};
837 if (memcmp(ip, ipNone, 16) == 0)
840 // documentation IPv6 address
847 uint32_t ipNone = INADDR_NONE;
848 if (memcmp(ip+12, &ipNone, 4) == 0)
853 if (memcmp(ip+12, &ipNone, 4) == 0)
860 bool CNetAddr::IsRoutable() const
862 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
865 enum Network CNetAddr::GetNetwork() const
868 return NET_UNROUTABLE;
879 std::string CNetAddr::ToStringIP() const
882 return EncodeBase32(&ip[6], 10) + ".onion";
883 CService serv(*this, 0);
884 struct sockaddr_storage sockaddr;
885 socklen_t socklen = sizeof(sockaddr);
886 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
887 char name[1025] = "";
888 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
889 return std::string(name);
892 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
894 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
895 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
896 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
897 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
898 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
901 std::string CNetAddr::ToString() const
906 bool operator==(const CNetAddr& a, const CNetAddr& b)
908 return (memcmp(a.ip, b.ip, 16) == 0);
911 bool operator!=(const CNetAddr& a, const CNetAddr& b)
913 return (memcmp(a.ip, b.ip, 16) != 0);
916 bool operator<(const CNetAddr& a, const CNetAddr& b)
918 return (memcmp(a.ip, b.ip, 16) < 0);
921 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
925 memcpy(pipv4Addr, ip+12, 4);
929 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
931 memcpy(pipv6Addr, ip, 16);
935 // get canonical identifier of an address' group
936 // no two connections will be attempted to addresses with the same group
937 std::vector<unsigned char> CNetAddr::GetGroup() const
939 std::vector<unsigned char> vchRet;
940 int nClass = NET_IPV6;
944 // all local addresses belong to the same group
951 // all unroutable addresses belong to the same group
954 nClass = NET_UNROUTABLE;
957 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
958 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
959 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
964 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
965 else if (IsRFC3964())
970 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
971 else if (IsRFC4380())
973 vchRet.push_back(NET_IPV4);
974 vchRet.push_back(GetByte(3) ^ 0xFF);
975 vchRet.push_back(GetByte(2) ^ 0xFF);
984 // for he.net, use /36 groups
985 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
987 // for the rest of the IPv6 network, use /32 groups
991 vchRet.push_back(nClass);
994 vchRet.push_back(GetByte(15 - nStartByte));
999 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
1004 uint64_t CNetAddr::GetHash() const
1006 uint256 hash = Hash(&ip[0], &ip[16]);
1008 memcpy(&nRet, &hash, sizeof(nRet));
1012 // private extensions to enum Network, only returned by GetExtNetwork,
1013 // and only used in GetReachabilityFrom
1014 static const int NET_UNKNOWN = NET_MAX + 0;
1015 static const int NET_TEREDO = NET_MAX + 1;
1016 int static GetExtNetwork(const CNetAddr *addr)
1020 if (addr->IsRFC4380())
1022 return addr->GetNetwork();
1025 /** Calculates a metric for how reachable (*this) is from a given partner */
1026 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
1039 return REACH_UNREACHABLE;
1041 int ourNet = GetExtNetwork(this);
1042 int theirNet = GetExtNetwork(paddrPartner);
1043 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
1048 default: return REACH_DEFAULT;
1049 case NET_IPV4: return REACH_IPV4;
1053 default: return REACH_DEFAULT;
1054 case NET_TEREDO: return REACH_TEREDO;
1055 case NET_IPV4: return REACH_IPV4;
1056 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
1060 default: return REACH_DEFAULT;
1061 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
1062 case NET_TOR: return REACH_PRIVATE;
1066 default: return REACH_DEFAULT;
1067 case NET_TEREDO: return REACH_TEREDO;
1068 case NET_IPV6: return REACH_IPV6_WEAK;
1069 case NET_IPV4: return REACH_IPV4;
1072 case NET_UNROUTABLE:
1075 default: return REACH_DEFAULT;
1076 case NET_TEREDO: return REACH_TEREDO;
1077 case NET_IPV6: return REACH_IPV6_WEAK;
1078 case NET_IPV4: return REACH_IPV4;
1079 case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
1084 void CService::Init()
1089 CService::CService()
1094 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
1098 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
1102 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
1106 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1108 assert(addr.sin_family == AF_INET);
1111 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1113 assert(addr.sin6_family == AF_INET6);
1116 bool CService::SetSockAddr(const struct sockaddr *paddr)
1118 switch (paddr->sa_family) {
1120 *this = CService(*(const struct sockaddr_in*)paddr);
1123 *this = CService(*(const struct sockaddr_in6*)paddr);
1130 CService::CService(const char *pszIpPort, bool fAllowLookup)
1134 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1138 CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
1142 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1146 CService::CService(const std::string &strIpPort, bool fAllowLookup)
1150 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1154 CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
1158 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1162 unsigned short CService::GetPort() const
1167 bool operator==(const CService& a, const CService& b)
1169 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1172 bool operator!=(const CService& a, const CService& b)
1174 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1177 bool operator<(const CService& a, const CService& b)
1179 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1182 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1185 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1187 *addrlen = sizeof(struct sockaddr_in);
1188 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1189 memset(paddrin, 0, *addrlen);
1190 if (!GetInAddr(&paddrin->sin_addr))
1192 paddrin->sin_family = AF_INET;
1193 paddrin->sin_port = htons(port);
1197 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1199 *addrlen = sizeof(struct sockaddr_in6);
1200 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1201 memset(paddrin6, 0, *addrlen);
1202 if (!GetIn6Addr(&paddrin6->sin6_addr))
1204 paddrin6->sin6_family = AF_INET6;
1205 paddrin6->sin6_port = htons(port);
1211 std::vector<unsigned char> CService::GetKey() const
1213 std::vector<unsigned char> vKey;
1215 memcpy(&vKey[0], ip, 16);
1216 vKey[16] = port / 0x100;
1217 vKey[17] = port & 0x0FF;
1221 std::string CService::ToStringPort() const
1223 return strprintf("%u", port);
1226 std::string CService::ToStringIPPort() const
1228 if (IsIPv4() || IsTor()) {
1229 return ToStringIP() + ":" + ToStringPort();
1231 return "[" + ToStringIP() + "]:" + ToStringPort();
1235 std::string CService::ToString() const
1237 return ToStringIPPort();
1240 void CService::SetPort(unsigned short portIn)
1248 memset(netmask, 0, sizeof(netmask));
1251 CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
1253 size_t slash = strSubnet.find_last_of('/');
1254 std::vector<CNetAddr> vIP;
1257 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
1258 memset(netmask, 255, sizeof(netmask));
1260 std::string strAddress = strSubnet.substr(0, slash);
1261 if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
1264 if (slash != strSubnet.npos)
1266 std::string strNetmask = strSubnet.substr(slash + 1);
1268 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
1269 const int astartofs = network.IsIPv4() ? 12 : 0;
1270 if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
1272 if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
1275 // Clear bits [n..127]
1276 for (; n < 128; ++n)
1277 netmask[n>>3] &= ~(1<<(7-(n&7)));
1284 else // If not a valid number, try full netmask syntax
1286 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
1288 // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
1289 // we don't want pchIPv4 to be part of the mask.
1290 for(int x=astartofs; x<16; ++x)
1291 netmask[x] = vIP[0].ip[x];
1305 // Normalize network according to netmask
1306 for(int x=0; x<16; ++x)
1307 network.ip[x] &= netmask[x];
1310 bool CSubNet::Match(const CNetAddr &addr) const
1312 if (!valid || !addr.IsValid())
1314 for(int x=0; x<16; ++x)
1315 if ((addr.ip[x] & netmask[x]) != network.ip[x])
1320 std::string CSubNet::ToString() const
1322 std::string strNetmask;
1323 if (network.IsIPv4())
1324 strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
1326 strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
1327 netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
1328 netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
1329 netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
1330 netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
1331 return network.ToString() + "/" + strNetmask;
1334 bool CSubNet::IsValid() const
1339 bool operator==(const CSubNet& a, const CSubNet& b)
1341 return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1344 bool operator!=(const CSubNet& a, const CSubNet& b)
1350 std::string NetworkErrorString(int err)
1354 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1355 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1356 buf, sizeof(buf), NULL))
1358 return strprintf("%s (%d)", buf, err);
1362 return strprintf("Unknown error (%d)", err);
1366 std::string NetworkErrorString(int err)
1369 const char *s = buf;
1371 /* Too bad there are two incompatible implementations of the
1372 * thread-safe strerror. */
1373 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1374 s = strerror_r(err, buf, sizeof(buf));
1375 #else /* POSIX variant always returns message in buffer */
1376 if (strerror_r(err, buf, sizeof(buf)))
1379 return strprintf("%s (%d)", s, err);
1383 bool CloseSocket(SOCKET& hSocket)
1385 if (hSocket == INVALID_SOCKET)
1388 int ret = closesocket(hSocket);
1390 int ret = close(hSocket);
1392 hSocket = INVALID_SOCKET;
1393 return ret != SOCKET_ERROR;
1396 bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
1401 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
1403 int fFlags = fcntl(hSocket, F_GETFL, 0);
1404 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
1406 CloseSocket(hSocket);
1412 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
1414 int fFlags = fcntl(hSocket, F_GETFL, 0);
1415 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
1417 CloseSocket(hSocket);