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"
19 #ifdef HAVE_GETADDRINFO_A
25 #include <arpa/inet.h>
30 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
31 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
32 #include <boost/thread.hpp>
34 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
35 #define MSG_NOSIGNAL 0
39 static proxyType proxyInfo
[NET_MAX
];
40 static proxyType nameProxy
;
41 static CCriticalSection cs_proxyInfos
;
42 int nConnectTimeout
= DEFAULT_CONNECT_TIMEOUT
;
43 bool fNameLookup
= false;
45 static const unsigned char pchIPv4
[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
47 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
48 static const int SOCKS5_RECV_TIMEOUT
= 20 * 1000;
50 enum Network
ParseNetwork(std::string net
) {
52 if (net
== "ipv4") return NET_IPV4
;
53 if (net
== "ipv6") return NET_IPV6
;
54 if (net
== "tor" || net
== "onion") return NET_TOR
;
55 return NET_UNROUTABLE
;
58 std::string
GetNetworkName(enum Network net
) {
61 case NET_IPV4
: return "ipv4";
62 case NET_IPV6
: return "ipv6";
63 case NET_TOR
: return "onion";
68 void SplitHostPort(std::string in
, int &portOut
, std::string
&hostOut
) {
69 size_t colon
= in
.find_last_of(':');
70 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
71 bool fHaveColon
= colon
!= in
.npos
;
72 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
73 bool fMultiColon
= fHaveColon
&& (in
.find_last_of(':',colon
-1) != in
.npos
);
74 if (fHaveColon
&& (colon
==0 || fBracketed
|| !fMultiColon
)) {
76 if (ParseInt32(in
.substr(colon
+ 1), &n
) && n
> 0 && n
< 0x10000) {
77 in
= in
.substr(0, colon
);
81 if (in
.size()>0 && in
[0] == '[' && in
[in
.size()-1] == ']')
82 hostOut
= in
.substr(1, in
.size()-2);
87 bool static LookupIntern(const char *pszName
, std::vector
<CNetAddr
>& vIP
, unsigned int nMaxSolutions
, bool fAllowLookup
)
93 if (addr
.SetSpecial(std::string(pszName
))) {
99 #ifdef HAVE_GETADDRINFO_A
100 struct in_addr ipv4_addr
;
101 #ifdef HAVE_INET_PTON
102 if (inet_pton(AF_INET
, pszName
, &ipv4_addr
) > 0) {
103 vIP
.push_back(CNetAddr(ipv4_addr
));
107 struct in6_addr ipv6_addr
;
108 if (inet_pton(AF_INET6
, pszName
, &ipv6_addr
) > 0) {
109 vIP
.push_back(CNetAddr(ipv6_addr
));
113 ipv4_addr
.s_addr
= inet_addr(pszName
);
114 if (ipv4_addr
.s_addr
!= INADDR_NONE
) {
115 vIP
.push_back(CNetAddr(ipv4_addr
));
121 struct addrinfo aiHint
;
122 memset(&aiHint
, 0, sizeof(struct addrinfo
));
123 aiHint
.ai_socktype
= SOCK_STREAM
;
124 aiHint
.ai_protocol
= IPPROTO_TCP
;
125 aiHint
.ai_family
= AF_UNSPEC
;
127 aiHint
.ai_flags
= fAllowLookup
? 0 : AI_NUMERICHOST
;
129 aiHint
.ai_flags
= fAllowLookup
? AI_ADDRCONFIG
: AI_NUMERICHOST
;
132 struct addrinfo
*aiRes
= NULL
;
133 #ifdef HAVE_GETADDRINFO_A
134 struct gaicb gcb
, *query
= &gcb
;
135 memset(query
, 0, sizeof(struct gaicb
));
136 gcb
.ar_name
= pszName
;
137 gcb
.ar_request
= &aiHint
;
138 int nErr
= getaddrinfo_a(GAI_NOWAIT
, &query
, 1, NULL
);
143 // Should set the timeout limit to a resonable value to avoid
144 // generating unnecessary checking call during the polling loop,
145 // while it can still response to stop request quick enough.
146 // 2 seconds looks fine in our situation.
147 struct timespec ts
= { 2, 0 };
148 gai_suspend(&query
, 1, &ts
);
149 boost::this_thread::interruption_point();
151 nErr
= gai_error(query
);
153 aiRes
= query
->ar_result
;
154 } while (nErr
== EAI_INPROGRESS
);
156 int nErr
= getaddrinfo(pszName
, NULL
, &aiHint
, &aiRes
);
161 struct addrinfo
*aiTrav
= aiRes
;
162 while (aiTrav
!= NULL
&& (nMaxSolutions
== 0 || vIP
.size() < nMaxSolutions
))
164 if (aiTrav
->ai_family
== AF_INET
)
166 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in
));
167 vIP
.push_back(CNetAddr(((struct sockaddr_in
*)(aiTrav
->ai_addr
))->sin_addr
));
170 if (aiTrav
->ai_family
== AF_INET6
)
172 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in6
));
173 vIP
.push_back(CNetAddr(((struct sockaddr_in6
*)(aiTrav
->ai_addr
))->sin6_addr
));
176 aiTrav
= aiTrav
->ai_next
;
181 return (vIP
.size() > 0);
184 bool LookupHost(const char *pszName
, std::vector
<CNetAddr
>& vIP
, unsigned int nMaxSolutions
, bool fAllowLookup
)
186 std::string
strHost(pszName
);
189 if (boost::algorithm::starts_with(strHost
, "[") && boost::algorithm::ends_with(strHost
, "]"))
191 strHost
= strHost
.substr(1, strHost
.size() - 2);
194 return LookupIntern(strHost
.c_str(), vIP
, nMaxSolutions
, fAllowLookup
);
197 bool Lookup(const char *pszName
, std::vector
<CService
>& vAddr
, int portDefault
, bool fAllowLookup
, unsigned int nMaxSolutions
)
201 int port
= portDefault
;
202 std::string hostname
= "";
203 SplitHostPort(std::string(pszName
), port
, hostname
);
205 std::vector
<CNetAddr
> vIP
;
206 bool fRet
= LookupIntern(hostname
.c_str(), vIP
, nMaxSolutions
, fAllowLookup
);
209 vAddr
.resize(vIP
.size());
210 for (unsigned int i
= 0; i
< vIP
.size(); i
++)
211 vAddr
[i
] = CService(vIP
[i
], port
);
215 bool Lookup(const char *pszName
, CService
& addr
, int portDefault
, bool fAllowLookup
)
217 std::vector
<CService
> vService
;
218 bool fRet
= Lookup(pszName
, vService
, portDefault
, fAllowLookup
, 1);
225 bool LookupNumeric(const char *pszName
, CService
& addr
, int portDefault
)
227 return Lookup(pszName
, addr
, portDefault
, false);
231 * Convert milliseconds to a struct timeval for select.
233 struct timeval
static MillisToTimeval(int64_t nTimeout
)
235 struct timeval timeout
;
236 timeout
.tv_sec
= nTimeout
/ 1000;
237 timeout
.tv_usec
= (nTimeout
% 1000) * 1000;
242 * Read bytes from socket. This will either read the full number of bytes requested
243 * or return False on error or timeout.
244 * This function can be interrupted by boost thread interrupt.
246 * @param data Buffer to receive into
247 * @param len Length of data to receive
248 * @param timeout Timeout in milliseconds for receive operation
250 * @note This function requires that hSocket is in non-blocking mode.
252 bool static InterruptibleRecv(char* data
, size_t len
, int timeout
, SOCKET
& hSocket
)
254 int64_t curTime
= GetTimeMillis();
255 int64_t endTime
= curTime
+ timeout
;
256 // Maximum time to wait in one select call. It will take up until this time (in millis)
257 // to break off in case of an interruption.
258 const int64_t maxWait
= 1000;
259 while (len
> 0 && curTime
< endTime
) {
260 ssize_t ret
= recv(hSocket
, data
, len
, 0); // Optimistically try the recv first
264 } else if (ret
== 0) { // Unexpected disconnection
266 } else { // Other error or blocking
267 int nErr
= WSAGetLastError();
268 if (nErr
== WSAEINPROGRESS
|| nErr
== WSAEWOULDBLOCK
|| nErr
== WSAEINVAL
) {
269 if (!IsSelectableSocket(hSocket
)) {
272 struct timeval tval
= MillisToTimeval(std::min(endTime
- curTime
, maxWait
));
275 FD_SET(hSocket
, &fdset
);
276 int nRet
= select(hSocket
+ 1, &fdset
, NULL
, NULL
, &tval
);
277 if (nRet
== SOCKET_ERROR
) {
284 boost::this_thread::interruption_point();
285 curTime
= GetTimeMillis();
290 struct ProxyCredentials
292 std::string username
;
293 std::string password
;
296 /** Connect using SOCKS5 (as described in RFC1928) */
297 static bool Socks5(const std::string
& strDest
, int port
, const ProxyCredentials
*auth
, SOCKET
& hSocket
)
299 LogPrintf("SOCKS5 connecting %s\n", strDest
);
300 if (strDest
.size() > 255) {
301 CloseSocket(hSocket
);
302 return error("Hostname too long");
304 // Accepted authentication methods
305 std::vector
<uint8_t> vSocks5Init
;
306 vSocks5Init
.push_back(0x05);
308 vSocks5Init
.push_back(0x02); // # METHODS
309 vSocks5Init
.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
310 vSocks5Init
.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
312 vSocks5Init
.push_back(0x01); // # METHODS
313 vSocks5Init
.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
315 ssize_t ret
= send(hSocket
, (const char*)begin_ptr(vSocks5Init
), vSocks5Init
.size(), MSG_NOSIGNAL
);
316 if (ret
!= (ssize_t
)vSocks5Init
.size()) {
317 CloseSocket(hSocket
);
318 return error("Error sending to proxy");
321 if (!InterruptibleRecv(pchRet1
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) {
322 CloseSocket(hSocket
);
323 return error("Error reading proxy response");
325 if (pchRet1
[0] != 0x05) {
326 CloseSocket(hSocket
);
327 return error("Proxy failed to initialize");
329 if (pchRet1
[1] == 0x02 && auth
) {
330 // Perform username/password authentication (as described in RFC1929)
331 std::vector
<uint8_t> vAuth
;
332 vAuth
.push_back(0x01);
333 if (auth
->username
.size() > 255 || auth
->password
.size() > 255)
334 return error("Proxy username or password too long");
335 vAuth
.push_back(auth
->username
.size());
336 vAuth
.insert(vAuth
.end(), auth
->username
.begin(), auth
->username
.end());
337 vAuth
.push_back(auth
->password
.size());
338 vAuth
.insert(vAuth
.end(), auth
->password
.begin(), auth
->password
.end());
339 ret
= send(hSocket
, (const char*)begin_ptr(vAuth
), vAuth
.size(), MSG_NOSIGNAL
);
340 if (ret
!= (ssize_t
)vAuth
.size()) {
341 CloseSocket(hSocket
);
342 return error("Error sending authentication to proxy");
344 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth
->username
, auth
->password
);
346 if (!InterruptibleRecv(pchRetA
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) {
347 CloseSocket(hSocket
);
348 return error("Error reading proxy authentication response");
350 if (pchRetA
[0] != 0x01 || pchRetA
[1] != 0x00) {
351 CloseSocket(hSocket
);
352 return error("Proxy authentication unsuccessful");
354 } else if (pchRet1
[1] == 0x00) {
355 // Perform no authentication
357 CloseSocket(hSocket
);
358 return error("Proxy requested wrong authentication method %02x", pchRet1
[1]);
360 std::vector
<uint8_t> vSocks5
;
361 vSocks5
.push_back(0x05); // VER protocol version
362 vSocks5
.push_back(0x01); // CMD CONNECT
363 vSocks5
.push_back(0x00); // RSV Reserved
364 vSocks5
.push_back(0x03); // ATYP DOMAINNAME
365 vSocks5
.push_back(strDest
.size()); // Length<=255 is checked at beginning of function
366 vSocks5
.insert(vSocks5
.end(), strDest
.begin(), strDest
.end());
367 vSocks5
.push_back((port
>> 8) & 0xFF);
368 vSocks5
.push_back((port
>> 0) & 0xFF);
369 ret
= send(hSocket
, (const char*)begin_ptr(vSocks5
), vSocks5
.size(), MSG_NOSIGNAL
);
370 if (ret
!= (ssize_t
)vSocks5
.size()) {
371 CloseSocket(hSocket
);
372 return error("Error sending to proxy");
375 if (!InterruptibleRecv(pchRet2
, 4, SOCKS5_RECV_TIMEOUT
, hSocket
)) {
376 CloseSocket(hSocket
);
377 return error("Error reading proxy response");
379 if (pchRet2
[0] != 0x05) {
380 CloseSocket(hSocket
);
381 return error("Proxy failed to accept request");
383 if (pchRet2
[1] != 0x00) {
384 CloseSocket(hSocket
);
387 case 0x01: return error("Proxy error: general failure");
388 case 0x02: return error("Proxy error: connection not allowed");
389 case 0x03: return error("Proxy error: network unreachable");
390 case 0x04: return error("Proxy error: host unreachable");
391 case 0x05: return error("Proxy error: connection refused");
392 case 0x06: return error("Proxy error: TTL expired");
393 case 0x07: return error("Proxy error: protocol error");
394 case 0x08: return error("Proxy error: address type not supported");
395 default: return error("Proxy error: unknown");
398 if (pchRet2
[2] != 0x00) {
399 CloseSocket(hSocket
);
400 return error("Error: malformed proxy response");
405 case 0x01: ret
= InterruptibleRecv(pchRet3
, 4, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
406 case 0x04: ret
= InterruptibleRecv(pchRet3
, 16, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
409 ret
= InterruptibleRecv(pchRet3
, 1, SOCKS5_RECV_TIMEOUT
, hSocket
);
411 CloseSocket(hSocket
);
412 return error("Error reading from proxy");
414 int nRecv
= pchRet3
[0];
415 ret
= InterruptibleRecv(pchRet3
, nRecv
, SOCKS5_RECV_TIMEOUT
, hSocket
);
418 default: CloseSocket(hSocket
); return error("Error: malformed proxy response");
421 CloseSocket(hSocket
);
422 return error("Error reading from proxy");
424 if (!InterruptibleRecv(pchRet3
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) {
425 CloseSocket(hSocket
);
426 return error("Error reading from proxy");
428 LogPrintf("SOCKS5 connected %s\n", strDest
);
432 bool static ConnectSocketDirectly(const CService
&addrConnect
, SOCKET
& hSocketRet
, int nTimeout
)
434 hSocketRet
= INVALID_SOCKET
;
436 struct sockaddr_storage sockaddr
;
437 socklen_t len
= sizeof(sockaddr
);
438 if (!addrConnect
.GetSockAddr((struct sockaddr
*)&sockaddr
, &len
)) {
439 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect
.ToString());
443 SOCKET hSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
444 if (hSocket
== INVALID_SOCKET
)
449 // Different way of disabling SIGPIPE on BSD
450 setsockopt(hSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&set
, sizeof(int));
453 // Set to non-blocking
454 if (!SetSocketNonBlocking(hSocket
, true))
455 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
457 if (connect(hSocket
, (struct sockaddr
*)&sockaddr
, len
) == SOCKET_ERROR
)
459 int nErr
= WSAGetLastError();
460 // WSAEINVAL is here because some legacy version of winsock uses it
461 if (nErr
== WSAEINPROGRESS
|| nErr
== WSAEWOULDBLOCK
|| nErr
== WSAEINVAL
)
463 struct timeval timeout
= MillisToTimeval(nTimeout
);
466 FD_SET(hSocket
, &fdset
);
467 int nRet
= select(hSocket
+ 1, NULL
, &fdset
, NULL
, &timeout
);
470 LogPrint("net", "connection to %s timeout\n", addrConnect
.ToString());
471 CloseSocket(hSocket
);
474 if (nRet
== SOCKET_ERROR
)
476 LogPrintf("select() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
477 CloseSocket(hSocket
);
480 socklen_t nRetSize
= sizeof(nRet
);
482 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, (char*)(&nRet
), &nRetSize
) == SOCKET_ERROR
)
484 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, &nRet
, &nRetSize
) == SOCKET_ERROR
)
487 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
488 CloseSocket(hSocket
);
493 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect
.ToString(), NetworkErrorString(nRet
));
494 CloseSocket(hSocket
);
499 else if (WSAGetLastError() != WSAEISCONN
)
504 LogPrintf("connect() to %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
505 CloseSocket(hSocket
);
510 hSocketRet
= hSocket
;
514 bool SetProxy(enum Network net
, const proxyType
&addrProxy
) {
515 assert(net
>= 0 && net
< NET_MAX
);
516 if (!addrProxy
.IsValid())
519 proxyInfo
[net
] = addrProxy
;
523 bool GetProxy(enum Network net
, proxyType
&proxyInfoOut
) {
524 assert(net
>= 0 && net
< NET_MAX
);
526 if (!proxyInfo
[net
].IsValid())
528 proxyInfoOut
= proxyInfo
[net
];
532 bool SetNameProxy(const proxyType
&addrProxy
) {
533 if (!addrProxy
.IsValid())
536 nameProxy
= addrProxy
;
540 bool GetNameProxy(proxyType
&nameProxyOut
) {
542 if(!nameProxy
.IsValid())
544 nameProxyOut
= nameProxy
;
548 bool HaveNameProxy() {
550 return nameProxy
.IsValid();
553 bool IsProxy(const CNetAddr
&addr
) {
555 for (int i
= 0; i
< NET_MAX
; i
++) {
556 if (addr
== (CNetAddr
)proxyInfo
[i
].proxy
)
562 static bool ConnectThroughProxy(const proxyType
&proxy
, const std::string
& strDest
, int port
, SOCKET
& hSocketRet
, int nTimeout
, bool *outProxyConnectionFailed
)
564 SOCKET hSocket
= INVALID_SOCKET
;
565 // first connect to proxy server
566 if (!ConnectSocketDirectly(proxy
.proxy
, hSocket
, nTimeout
)) {
567 if (outProxyConnectionFailed
)
568 *outProxyConnectionFailed
= true;
571 // do socks negotiation
572 if (proxy
.randomize_credentials
) {
573 ProxyCredentials random_auth
;
574 random_auth
.username
= strprintf("%i", insecure_rand());
575 random_auth
.password
= strprintf("%i", insecure_rand());
576 if (!Socks5(strDest
, (unsigned short)port
, &random_auth
, hSocket
))
579 if (!Socks5(strDest
, (unsigned short)port
, 0, hSocket
))
583 hSocketRet
= hSocket
;
587 bool ConnectSocket(const CService
&addrDest
, SOCKET
& hSocketRet
, int nTimeout
, bool *outProxyConnectionFailed
)
590 if (outProxyConnectionFailed
)
591 *outProxyConnectionFailed
= false;
593 if (GetProxy(addrDest
.GetNetwork(), proxy
))
594 return ConnectThroughProxy(proxy
, addrDest
.ToStringIP(), addrDest
.GetPort(), hSocketRet
, nTimeout
, outProxyConnectionFailed
);
595 else // no proxy needed (none set for target network)
596 return ConnectSocketDirectly(addrDest
, hSocketRet
, nTimeout
);
599 bool ConnectSocketByName(CService
&addr
, SOCKET
& hSocketRet
, const char *pszDest
, int portDefault
, int nTimeout
, bool *outProxyConnectionFailed
)
602 int port
= portDefault
;
604 if (outProxyConnectionFailed
)
605 *outProxyConnectionFailed
= false;
607 SplitHostPort(std::string(pszDest
), port
, strDest
);
610 GetNameProxy(nameProxy
);
612 CService
addrResolved(CNetAddr(strDest
, fNameLookup
&& !HaveNameProxy()), port
);
613 if (addrResolved
.IsValid()) {
615 return ConnectSocket(addr
, hSocketRet
, nTimeout
);
618 addr
= CService("0.0.0.0:0");
620 if (!HaveNameProxy())
622 return ConnectThroughProxy(nameProxy
, strDest
, port
, hSocketRet
, nTimeout
, outProxyConnectionFailed
);
625 void CNetAddr::Init()
627 memset(ip
, 0, sizeof(ip
));
630 void CNetAddr::SetIP(const CNetAddr
& ipIn
)
632 memcpy(ip
, ipIn
.ip
, sizeof(ip
));
635 void CNetAddr::SetRaw(Network network
, const uint8_t *ip_in
)
640 memcpy(ip
, pchIPv4
, 12);
641 memcpy(ip
+12, ip_in
, 4);
644 memcpy(ip
, ip_in
, 16);
647 assert(!"invalid network");
651 static const unsigned char pchOnionCat
[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
653 bool CNetAddr::SetSpecial(const std::string
&strName
)
655 if (strName
.size()>6 && strName
.substr(strName
.size() - 6, 6) == ".onion") {
656 std::vector
<unsigned char> vchAddr
= DecodeBase32(strName
.substr(0, strName
.size() - 6).c_str());
657 if (vchAddr
.size() != 16-sizeof(pchOnionCat
))
659 memcpy(ip
, pchOnionCat
, sizeof(pchOnionCat
));
660 for (unsigned int i
=0; i
<16-sizeof(pchOnionCat
); i
++)
661 ip
[i
+ sizeof(pchOnionCat
)] = vchAddr
[i
];
672 CNetAddr::CNetAddr(const struct in_addr
& ipv4Addr
)
674 SetRaw(NET_IPV4
, (const uint8_t*)&ipv4Addr
);
677 CNetAddr::CNetAddr(const struct in6_addr
& ipv6Addr
)
679 SetRaw(NET_IPV6
, (const uint8_t*)&ipv6Addr
);
682 CNetAddr::CNetAddr(const char *pszIp
, bool fAllowLookup
)
685 std::vector
<CNetAddr
> vIP
;
686 if (LookupHost(pszIp
, vIP
, 1, fAllowLookup
))
690 CNetAddr::CNetAddr(const std::string
&strIp
, bool fAllowLookup
)
693 std::vector
<CNetAddr
> vIP
;
694 if (LookupHost(strIp
.c_str(), vIP
, 1, fAllowLookup
))
698 unsigned int CNetAddr::GetByte(int n
) const
703 bool CNetAddr::IsIPv4() const
705 return (memcmp(ip
, pchIPv4
, sizeof(pchIPv4
)) == 0);
708 bool CNetAddr::IsIPv6() const
710 return (!IsIPv4() && !IsTor());
713 bool CNetAddr::IsRFC1918() const
717 (GetByte(3) == 192 && GetByte(2) == 168) ||
718 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
721 bool CNetAddr::IsRFC2544() const
723 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
726 bool CNetAddr::IsRFC3927() const
728 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
731 bool CNetAddr::IsRFC6598() const
733 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
736 bool CNetAddr::IsRFC5737() const
738 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
739 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
740 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
743 bool CNetAddr::IsRFC3849() const
745 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
748 bool CNetAddr::IsRFC3964() const
750 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
753 bool CNetAddr::IsRFC6052() const
755 static const unsigned char pchRFC6052
[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
756 return (memcmp(ip
, pchRFC6052
, sizeof(pchRFC6052
)) == 0);
759 bool CNetAddr::IsRFC4380() const
761 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
764 bool CNetAddr::IsRFC4862() const
766 static const unsigned char pchRFC4862
[] = {0xFE,0x80,0,0,0,0,0,0};
767 return (memcmp(ip
, pchRFC4862
, sizeof(pchRFC4862
)) == 0);
770 bool CNetAddr::IsRFC4193() const
772 return ((GetByte(15) & 0xFE) == 0xFC);
775 bool CNetAddr::IsRFC6145() const
777 static const unsigned char pchRFC6145
[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
778 return (memcmp(ip
, pchRFC6145
, sizeof(pchRFC6145
)) == 0);
781 bool CNetAddr::IsRFC4843() const
783 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
786 bool CNetAddr::IsTor() const
788 return (memcmp(ip
, pchOnionCat
, sizeof(pchOnionCat
)) == 0);
791 bool CNetAddr::IsLocal() const
794 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
797 // IPv6 loopback (::1/128)
798 static const unsigned char pchLocal
[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
799 if (memcmp(ip
, pchLocal
, 16) == 0)
805 bool CNetAddr::IsMulticast() const
807 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
808 || (GetByte(15) == 0xFF);
811 bool CNetAddr::IsValid() const
813 // Cleanup 3-byte shifted addresses caused by garbage in size field
814 // of addr messages from versions before 0.2.9 checksum.
815 // Two consecutive addr messages look like this:
816 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
817 // so if the first length field is garbled, it reads the second batch
818 // of addr misaligned by 3 bytes.
819 if (memcmp(ip
, pchIPv4
+3, sizeof(pchIPv4
)-3) == 0)
822 // unspecified IPv6 address (::/128)
823 unsigned char ipNone
[16] = {};
824 if (memcmp(ip
, ipNone
, 16) == 0)
827 // documentation IPv6 address
834 uint32_t ipNone
= INADDR_NONE
;
835 if (memcmp(ip
+12, &ipNone
, 4) == 0)
840 if (memcmp(ip
+12, &ipNone
, 4) == 0)
847 bool CNetAddr::IsRoutable() const
849 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
852 enum Network
CNetAddr::GetNetwork() const
855 return NET_UNROUTABLE
;
866 std::string
CNetAddr::ToStringIP() const
869 return EncodeBase32(&ip
[6], 10) + ".onion";
870 CService
serv(*this, 0);
871 struct sockaddr_storage sockaddr
;
872 socklen_t socklen
= sizeof(sockaddr
);
873 if (serv
.GetSockAddr((struct sockaddr
*)&sockaddr
, &socklen
)) {
874 char name
[1025] = "";
875 if (!getnameinfo((const struct sockaddr
*)&sockaddr
, socklen
, name
, sizeof(name
), NULL
, 0, NI_NUMERICHOST
))
876 return std::string(name
);
879 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
881 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
882 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
883 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
884 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
885 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
888 std::string
CNetAddr::ToString() const
893 bool operator==(const CNetAddr
& a
, const CNetAddr
& b
)
895 return (memcmp(a
.ip
, b
.ip
, 16) == 0);
898 bool operator!=(const CNetAddr
& a
, const CNetAddr
& b
)
900 return (memcmp(a
.ip
, b
.ip
, 16) != 0);
903 bool operator<(const CNetAddr
& a
, const CNetAddr
& b
)
905 return (memcmp(a
.ip
, b
.ip
, 16) < 0);
908 bool CNetAddr::GetInAddr(struct in_addr
* pipv4Addr
) const
912 memcpy(pipv4Addr
, ip
+12, 4);
916 bool CNetAddr::GetIn6Addr(struct in6_addr
* pipv6Addr
) const
918 memcpy(pipv6Addr
, ip
, 16);
922 // get canonical identifier of an address' group
923 // no two connections will be attempted to addresses with the same group
924 std::vector
<unsigned char> CNetAddr::GetGroup() const
926 std::vector
<unsigned char> vchRet
;
927 int nClass
= NET_IPV6
;
931 // all local addresses belong to the same group
938 // all unroutable addresses belong to the same group
941 nClass
= NET_UNROUTABLE
;
944 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
945 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
946 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
951 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
952 else if (IsRFC3964())
957 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
958 else if (IsRFC4380())
960 vchRet
.push_back(NET_IPV4
);
961 vchRet
.push_back(GetByte(3) ^ 0xFF);
962 vchRet
.push_back(GetByte(2) ^ 0xFF);
971 // for he.net, use /36 groups
972 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
974 // for the rest of the IPv6 network, use /32 groups
978 vchRet
.push_back(nClass
);
981 vchRet
.push_back(GetByte(15 - nStartByte
));
986 vchRet
.push_back(GetByte(15 - nStartByte
) | ((1 << (8 - nBits
)) - 1));
991 uint64_t CNetAddr::GetHash() const
993 uint256 hash
= Hash(&ip
[0], &ip
[16]);
995 memcpy(&nRet
, &hash
, sizeof(nRet
));
999 // private extensions to enum Network, only returned by GetExtNetwork,
1000 // and only used in GetReachabilityFrom
1001 static const int NET_UNKNOWN
= NET_MAX
+ 0;
1002 static const int NET_TEREDO
= NET_MAX
+ 1;
1003 int static GetExtNetwork(const CNetAddr
*addr
)
1007 if (addr
->IsRFC4380())
1009 return addr
->GetNetwork();
1012 /** Calculates a metric for how reachable (*this) is from a given partner */
1013 int CNetAddr::GetReachabilityFrom(const CNetAddr
*paddrPartner
) const
1026 return REACH_UNREACHABLE
;
1028 int ourNet
= GetExtNetwork(this);
1029 int theirNet
= GetExtNetwork(paddrPartner
);
1030 bool fTunnel
= IsRFC3964() || IsRFC6052() || IsRFC6145();
1035 default: return REACH_DEFAULT
;
1036 case NET_IPV4
: return REACH_IPV4
;
1040 default: return REACH_DEFAULT
;
1041 case NET_TEREDO
: return REACH_TEREDO
;
1042 case NET_IPV4
: return REACH_IPV4
;
1043 case NET_IPV6
: return fTunnel
? REACH_IPV6_WEAK
: REACH_IPV6_STRONG
; // only prefer giving our IPv6 address if it's not tunnelled
1047 default: return REACH_DEFAULT
;
1048 case NET_IPV4
: return REACH_IPV4
; // Tor users can connect to IPv4 as well
1049 case NET_TOR
: return REACH_PRIVATE
;
1053 default: return REACH_DEFAULT
;
1054 case NET_TEREDO
: return REACH_TEREDO
;
1055 case NET_IPV6
: return REACH_IPV6_WEAK
;
1056 case NET_IPV4
: return REACH_IPV4
;
1059 case NET_UNROUTABLE
:
1062 default: return REACH_DEFAULT
;
1063 case NET_TEREDO
: return REACH_TEREDO
;
1064 case NET_IPV6
: return REACH_IPV6_WEAK
;
1065 case NET_IPV4
: return REACH_IPV4
;
1066 case NET_TOR
: return REACH_PRIVATE
; // either from Tor, or don't care about our address
1071 void CService::Init()
1076 CService::CService()
1081 CService::CService(const CNetAddr
& cip
, unsigned short portIn
) : CNetAddr(cip
), port(portIn
)
1085 CService::CService(const struct in_addr
& ipv4Addr
, unsigned short portIn
) : CNetAddr(ipv4Addr
), port(portIn
)
1089 CService::CService(const struct in6_addr
& ipv6Addr
, unsigned short portIn
) : CNetAddr(ipv6Addr
), port(portIn
)
1093 CService::CService(const struct sockaddr_in
& addr
) : CNetAddr(addr
.sin_addr
), port(ntohs(addr
.sin_port
))
1095 assert(addr
.sin_family
== AF_INET
);
1098 CService::CService(const struct sockaddr_in6
&addr
) : CNetAddr(addr
.sin6_addr
), port(ntohs(addr
.sin6_port
))
1100 assert(addr
.sin6_family
== AF_INET6
);
1103 bool CService::SetSockAddr(const struct sockaddr
*paddr
)
1105 switch (paddr
->sa_family
) {
1107 *this = CService(*(const struct sockaddr_in
*)paddr
);
1110 *this = CService(*(const struct sockaddr_in6
*)paddr
);
1117 CService::CService(const char *pszIpPort
, bool fAllowLookup
)
1121 if (Lookup(pszIpPort
, ip
, 0, fAllowLookup
))
1125 CService::CService(const char *pszIpPort
, int portDefault
, bool fAllowLookup
)
1129 if (Lookup(pszIpPort
, ip
, portDefault
, fAllowLookup
))
1133 CService::CService(const std::string
&strIpPort
, bool fAllowLookup
)
1137 if (Lookup(strIpPort
.c_str(), ip
, 0, fAllowLookup
))
1141 CService::CService(const std::string
&strIpPort
, int portDefault
, bool fAllowLookup
)
1145 if (Lookup(strIpPort
.c_str(), ip
, portDefault
, fAllowLookup
))
1149 unsigned short CService::GetPort() const
1154 bool operator==(const CService
& a
, const CService
& b
)
1156 return (CNetAddr
)a
== (CNetAddr
)b
&& a
.port
== b
.port
;
1159 bool operator!=(const CService
& a
, const CService
& b
)
1161 return (CNetAddr
)a
!= (CNetAddr
)b
|| a
.port
!= b
.port
;
1164 bool operator<(const CService
& a
, const CService
& b
)
1166 return (CNetAddr
)a
< (CNetAddr
)b
|| ((CNetAddr
)a
== (CNetAddr
)b
&& a
.port
< b
.port
);
1169 bool CService::GetSockAddr(struct sockaddr
* paddr
, socklen_t
*addrlen
) const
1172 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in
))
1174 *addrlen
= sizeof(struct sockaddr_in
);
1175 struct sockaddr_in
*paddrin
= (struct sockaddr_in
*)paddr
;
1176 memset(paddrin
, 0, *addrlen
);
1177 if (!GetInAddr(&paddrin
->sin_addr
))
1179 paddrin
->sin_family
= AF_INET
;
1180 paddrin
->sin_port
= htons(port
);
1184 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in6
))
1186 *addrlen
= sizeof(struct sockaddr_in6
);
1187 struct sockaddr_in6
*paddrin6
= (struct sockaddr_in6
*)paddr
;
1188 memset(paddrin6
, 0, *addrlen
);
1189 if (!GetIn6Addr(&paddrin6
->sin6_addr
))
1191 paddrin6
->sin6_family
= AF_INET6
;
1192 paddrin6
->sin6_port
= htons(port
);
1198 std::vector
<unsigned char> CService::GetKey() const
1200 std::vector
<unsigned char> vKey
;
1202 memcpy(&vKey
[0], ip
, 16);
1203 vKey
[16] = port
/ 0x100;
1204 vKey
[17] = port
& 0x0FF;
1208 std::string
CService::ToStringPort() const
1210 return strprintf("%u", port
);
1213 std::string
CService::ToStringIPPort() const
1215 if (IsIPv4() || IsTor()) {
1216 return ToStringIP() + ":" + ToStringPort();
1218 return "[" + ToStringIP() + "]:" + ToStringPort();
1222 std::string
CService::ToString() const
1224 return ToStringIPPort();
1227 void CService::SetPort(unsigned short portIn
)
1235 memset(netmask
, 0, sizeof(netmask
));
1238 CSubNet::CSubNet(const std::string
&strSubnet
, bool fAllowLookup
)
1240 size_t slash
= strSubnet
.find_last_of('/');
1241 std::vector
<CNetAddr
> vIP
;
1244 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
1245 memset(netmask
, 255, sizeof(netmask
));
1247 std::string strAddress
= strSubnet
.substr(0, slash
);
1248 if (LookupHost(strAddress
.c_str(), vIP
, 1, fAllowLookup
))
1251 if (slash
!= strSubnet
.npos
)
1253 std::string strNetmask
= strSubnet
.substr(slash
+ 1);
1255 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
1256 const int astartofs
= network
.IsIPv4() ? 12 : 0;
1257 if (ParseInt32(strNetmask
, &n
)) // If valid number, assume /24 symtex
1259 if(n
>= 0 && n
<= (128 - astartofs
*8)) // Only valid if in range of bits of address
1262 // Clear bits [n..127]
1263 for (; n
< 128; ++n
)
1264 netmask
[n
>>3] &= ~(1<<(7-(n
&7)));
1271 else // If not a valid number, try full netmask syntax
1273 if (LookupHost(strNetmask
.c_str(), vIP
, 1, false)) // Never allow lookup for netmask
1275 // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
1276 // we don't want pchIPv4 to be part of the mask.
1277 for(int x
=astartofs
; x
<16; ++x
)
1278 netmask
[x
] = vIP
[0].ip
[x
];
1292 // Normalize network according to netmask
1293 for(int x
=0; x
<16; ++x
)
1294 network
.ip
[x
] &= netmask
[x
];
1297 CSubNet::CSubNet(const CNetAddr
&addr
):
1298 valid(addr
.IsValid())
1300 memset(netmask
, 255, sizeof(netmask
));
1304 bool CSubNet::Match(const CNetAddr
&addr
) const
1306 if (!valid
|| !addr
.IsValid())
1308 for(int x
=0; x
<16; ++x
)
1309 if ((addr
.ip
[x
] & netmask
[x
]) != network
.ip
[x
])
1314 std::string
CSubNet::ToString() const
1316 std::string strNetmask
;
1317 if (network
.IsIPv4())
1318 strNetmask
= strprintf("%u.%u.%u.%u", netmask
[12], netmask
[13], netmask
[14], netmask
[15]);
1320 strNetmask
= strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
1321 netmask
[0] << 8 | netmask
[1], netmask
[2] << 8 | netmask
[3],
1322 netmask
[4] << 8 | netmask
[5], netmask
[6] << 8 | netmask
[7],
1323 netmask
[8] << 8 | netmask
[9], netmask
[10] << 8 | netmask
[11],
1324 netmask
[12] << 8 | netmask
[13], netmask
[14] << 8 | netmask
[15]);
1325 return network
.ToString() + "/" + strNetmask
;
1328 bool CSubNet::IsValid() const
1333 bool operator==(const CSubNet
& a
, const CSubNet
& b
)
1335 return a
.valid
== b
.valid
&& a
.network
== b
.network
&& !memcmp(a
.netmask
, b
.netmask
, 16);
1338 bool operator!=(const CSubNet
& a
, const CSubNet
& b
)
1343 bool operator<(const CSubNet
& a
, const CSubNet
& b
)
1345 return (a
.network
< b
.network
|| (a
.network
== b
.network
&& memcmp(a
.netmask
, b
.netmask
, 16) < 0));
1349 std::string
NetworkErrorString(int err
)
1353 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_MAX_WIDTH_MASK
,
1354 NULL
, err
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1355 buf
, sizeof(buf
), NULL
))
1357 return strprintf("%s (%d)", buf
, err
);
1361 return strprintf("Unknown error (%d)", err
);
1365 std::string
NetworkErrorString(int err
)
1368 const char *s
= buf
;
1370 /* Too bad there are two incompatible implementations of the
1371 * thread-safe strerror. */
1372 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1373 s
= strerror_r(err
, buf
, sizeof(buf
));
1374 #else /* POSIX variant always returns message in buffer */
1375 if (strerror_r(err
, buf
, sizeof(buf
)))
1378 return strprintf("%s (%d)", s
, err
);
1382 bool CloseSocket(SOCKET
& hSocket
)
1384 if (hSocket
== INVALID_SOCKET
)
1387 int ret
= closesocket(hSocket
);
1389 int ret
= close(hSocket
);
1391 hSocket
= INVALID_SOCKET
;
1392 return ret
!= SOCKET_ERROR
;
1395 bool SetSocketNonBlocking(SOCKET
& hSocket
, bool fNonBlocking
)
1400 if (ioctlsocket(hSocket
, FIONBIO
, &nOne
) == SOCKET_ERROR
) {
1402 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
1403 if (fcntl(hSocket
, F_SETFL
, fFlags
| O_NONBLOCK
) == SOCKET_ERROR
) {
1405 CloseSocket(hSocket
);
1411 if (ioctlsocket(hSocket
, FIONBIO
, &nZero
) == SOCKET_ERROR
) {
1413 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
1414 if (fcntl(hSocket
, F_SETFL
, fFlags
& ~O_NONBLOCK
) == SOCKET_ERROR
) {
1416 CloseSocket(hSocket
);