7 #include "config/bitcoin-config.h"
25 #include <boost/algorithm/string/case_conv.hpp>
26 #include <boost/algorithm/string/predicate.hpp>
28 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
29 #define MSG_NOSIGNAL 0
40 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
41 static std::atomic<bool> interruptSocks5Recv(
false);
47 if (net ==
"tor" || net ==
"onion")
return NET_TOR;
61 void SplitHostPort(std::string in,
int &portOut, std::string &hostOut) {
62 size_t colon = in.find_last_of(
':');
64 bool fHaveColon = colon != in.npos;
65 bool fBracketed = fHaveColon && (in[0]==
'[' && in[colon-1]==
']');
66 bool fMultiColon = fHaveColon && (in.find_last_of(
':',colon-1) != in.npos);
67 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
69 if (
ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
70 in = in.substr(0, colon);
74 if (in.size()>0 && in[0] ==
'[' && in[in.size()-1] ==
']')
75 hostOut = in.substr(1, in.size()-2);
80 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
92 struct addrinfo aiHint;
93 memset(&aiHint, 0,
sizeof(
struct addrinfo));
95 aiHint.ai_socktype = SOCK_STREAM;
96 aiHint.ai_protocol = IPPROTO_TCP;
97 aiHint.ai_family = AF_UNSPEC;
99 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
101 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
103 struct addrinfo *aiRes = NULL;
104 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
108 struct addrinfo *aiTrav = aiRes;
109 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
111 if (aiTrav->ai_family == AF_INET)
113 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
114 vIP.push_back(
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
117 if (aiTrav->ai_family == AF_INET6)
119 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
120 struct sockaddr_in6* s6 = (
struct sockaddr_in6*) aiTrav->ai_addr;
121 vIP.push_back(
CNetAddr(s6->sin6_addr, s6->sin6_scope_id));
124 aiTrav = aiTrav->ai_next;
129 return (vIP.size() > 0);
132 bool LookupHost(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
134 std::string strHost(pszName);
137 if (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]"))
139 strHost = strHost.substr(1, strHost.size() - 2);
142 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
147 std::vector<CNetAddr> vIP;
155 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
159 int port = portDefault;
160 std::string hostname =
"";
163 std::vector<CNetAddr> vIP;
164 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
167 vAddr.resize(vIP.size());
168 for (
unsigned int i = 0; i < vIP.size(); i++)
173 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
175 std::vector<CService> vService;
176 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
188 if(!
Lookup(pszName, addr, portDefault,
false))
195 struct timeval timeout;
196 timeout.tv_sec = nTimeout / 1000;
197 timeout.tv_usec = (nTimeout % 1000) * 1000;
220 static IntrRecvError InterruptibleRecv(
char* data,
size_t len,
int timeout,
SOCKET& hSocket)
223 int64_t endTime = curTime + timeout;
226 const int64_t maxWait = 1000;
227 while (len > 0 && curTime < endTime) {
228 ssize_t ret = recv(hSocket, data, len, 0);
232 }
else if (ret == 0) {
237 if (!IsSelectableSocket(hSocket)) {
240 struct timeval tval =
MillisToTimeval(std::min(endTime - curTime, maxWait));
243 FD_SET(hSocket, &fdset);
244 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
252 if (interruptSocks5Recv)
268 case 0x01:
return "general failure";
269 case 0x02:
return "connection not allowed";
270 case 0x03:
return "network unreachable";
271 case 0x04:
return "host unreachable";
272 case 0x05:
return "connection refused";
273 case 0x06:
return "TTL expired";
274 case 0x07:
return "protocol error";
275 case 0x08:
return "address type not supported";
276 default:
return "unknown";
284 LogPrint(
"net",
"SOCKS5 connecting %s\n", strDest);
285 if (strDest.size() > 255) {
287 return error(
"Hostname too long");
290 std::vector<uint8_t> vSocks5Init;
291 vSocks5Init.push_back(0x05);
293 vSocks5Init.push_back(0x02);
294 vSocks5Init.push_back(0x00);
295 vSocks5Init.push_back(0x02);
297 vSocks5Init.push_back(0x01);
298 vSocks5Init.push_back(0x00);
300 ssize_t ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
301 if (ret != (ssize_t)vSocks5Init.size()) {
303 return error(
"Error sending to proxy");
306 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
308 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
311 if (pchRet1[0] != 0x05) {
313 return error(
"Proxy failed to initialize");
315 if (pchRet1[1] == 0x02 && auth) {
317 std::vector<uint8_t> vAuth;
318 vAuth.push_back(0x01);
320 return error(
"Proxy username or password too long");
321 vAuth.push_back(auth->
username.size());
323 vAuth.push_back(auth->
password.size());
325 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
326 if (ret != (ssize_t)vAuth.size()) {
328 return error(
"Error sending authentication to proxy");
332 if (( recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
334 return error(
"Error reading proxy authentication response");
336 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
338 return error(
"Proxy authentication unsuccessful");
340 }
else if (pchRet1[1] == 0x00) {
344 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
346 std::vector<uint8_t> vSocks5;
347 vSocks5.push_back(0x05);
348 vSocks5.push_back(0x01);
349 vSocks5.push_back(0x00);
350 vSocks5.push_back(0x03);
351 vSocks5.push_back(strDest.size());
352 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
353 vSocks5.push_back((port >> 8) & 0xFF);
354 vSocks5.push_back((port >> 0) & 0xFF);
355 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
356 if (ret != (ssize_t)vSocks5.size()) {
358 return error(
"Error sending to proxy");
361 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
369 return error(
"Error while reading proxy response");
372 if (pchRet2[0] != 0x05) {
374 return error(
"Proxy failed to accept request");
376 if (pchRet2[1] != 0x00) {
382 if (pchRet2[2] != 0x00) {
384 return error(
"Error: malformed proxy response");
389 case 0x01: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
390 case 0x04: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
393 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
396 return error(
"Error reading from proxy");
398 int nRecv = pchRet3[0];
399 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
402 default:
CloseSocket(hSocket);
return error(
"Error: malformed proxy response");
406 return error(
"Error reading from proxy");
408 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
410 return error(
"Error reading from proxy");
412 LogPrint(
"net",
"SOCKS5 connected %s\n", strDest);
416 bool static ConnectSocketDirectly(
const CService &addrConnect,
SOCKET& hSocketRet,
int nTimeout)
420 struct sockaddr_storage sockaddr;
421 socklen_t len =
sizeof(sockaddr);
422 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
423 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
427 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
434 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
439 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&set,
sizeof(
int));
441 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
void*)&set,
sizeof(
int));
448 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
457 FD_SET(hSocket, &fdset);
458 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
471 socklen_t nRetSize =
sizeof(nRet);
473 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
475 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
501 hSocketRet = hSocket;
506 assert(net >= 0 && net <
NET_MAX);
510 proxyInfo[net] = addrProxy;
515 assert(net >= 0 && net <
NET_MAX);
517 if (!proxyInfo[net].IsValid())
519 proxyInfoOut = proxyInfo[net];
527 nameProxy = addrProxy;
535 nameProxyOut = nameProxy;
546 for (
int i = 0; i <
NET_MAX; i++) {
547 if (addr == (
CNetAddr)proxyInfo[i].proxy)
553 static bool ConnectThroughProxy(
const proxyType &proxy,
const std::string& strDest,
int port,
SOCKET& hSocketRet,
int nTimeout,
bool *outProxyConnectionFailed)
557 if (!ConnectSocketDirectly(proxy.
proxy, hSocket, nTimeout)) {
558 if (outProxyConnectionFailed)
559 *outProxyConnectionFailed =
true;
565 static std::atomic_int counter;
567 if (!Socks5(strDest, (
unsigned short)port, &random_auth, hSocket))
570 if (!Socks5(strDest, (
unsigned short)port, 0, hSocket))
574 hSocketRet = hSocket;
581 if (outProxyConnectionFailed)
582 *outProxyConnectionFailed =
false;
585 return ConnectThroughProxy(proxy, addrDest.
ToStringIP(), addrDest.
GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
587 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
593 int port = portDefault;
595 if (outProxyConnectionFailed)
596 *outProxyConnectionFailed =
false;
603 std::vector<CService> addrResolved;
605 if (addrResolved.size() > 0) {
606 addr = addrResolved[
GetRand(addrResolved.size())];
615 return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
620 std::string strSubnet(pszName);
621 size_t slash = strSubnet.find_last_of(
'/');
622 std::vector<CNetAddr> vIP;
624 std::string strAddress = strSubnet.substr(0, slash);
625 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
628 if (slash != strSubnet.npos)
630 std::string strNetmask = strSubnet.substr(slash + 1);
640 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
641 ret =
CSubNet(network, vIP[0]);
660 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
661 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
662 buf,
sizeof(buf), NULL))
668 return strprintf(
"Unknown error (%d)", err);
679 #ifdef STRERROR_R_CHAR_P
680 s = strerror_r(err, buf,
sizeof(buf));
682 if (strerror_r(err, buf,
sizeof(buf)))
694 int ret = closesocket(hSocket);
696 int ret = close(hSocket);
707 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
709 int fFlags = fcntl(hSocket, F_GETFL, 0);
710 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
718 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
720 int fFlags = fcntl(hSocket, F_GETFL, 0);
721 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
733 interruptSocks5Recv = interrupt;
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
std::string ToStringIP() const
bool SetSpecial(const std::string &strName)
enum Network GetNetwork() const
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToString() const
unsigned short GetPort() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
bool randomize_credentials
#define WSAGetLastError()
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
bool GetNameProxy(proxyType &nameProxyOut)
std::string Socks5ErrorString(int err)
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
enum Network ParseNetwork(std::string net)
std::string GetNetworkName(enum Network net)
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
bool LookupSubNet(const char *pszName, CSubNet &ret)
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
bool SetSocketNonBlocking(SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
CService LookupNumeric(const char *pszName, int portDefault)
void InterruptSocks5(bool interrupt)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
bool SetNameProxy(const proxyType &addrProxy)
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
bool IsProxy(const CNetAddr &addr)
bool SetProxy(enum Network net, const proxyType &addrProxy)
uint64_t GetRand(uint64_t nMax)
#define LogPrint(category,...)
bool error(const char *fmt, const Args &... args)
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.