24 #if !defined(MSG_NOSIGNAL) 25 #define MSG_NOSIGNAL 0 36 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
37 static std::atomic<bool> interruptSocks5Recv(
false);
45 LogPrintf(
"Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
61 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
73 struct addrinfo aiHint;
74 memset(&aiHint, 0,
sizeof(
struct addrinfo));
76 aiHint.ai_socktype = SOCK_STREAM;
77 aiHint.ai_protocol = IPPROTO_TCP;
78 aiHint.ai_family = AF_UNSPEC;
80 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
82 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
84 struct addrinfo *aiRes =
nullptr;
85 int nErr = getaddrinfo(pszName,
nullptr, &aiHint, &aiRes);
89 struct addrinfo *aiTrav = aiRes;
90 while (aiTrav !=
nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
93 if (aiTrav->ai_family == AF_INET)
95 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
96 resolved =
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
99 if (aiTrav->ai_family == AF_INET6)
101 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
102 struct sockaddr_in6* s6 = (
struct sockaddr_in6*) aiTrav->ai_addr;
103 resolved =
CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
107 vIP.push_back(resolved);
110 aiTrav = aiTrav->ai_next;
115 return (vIP.size() > 0);
118 bool LookupHost(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
120 std::string strHost(pszName);
123 if (strHost.front() ==
'[' && strHost.back() ==
']') {
124 strHost = strHost.substr(1, strHost.size() - 2);
127 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
132 std::vector<CNetAddr> vIP;
140 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
144 int port = portDefault;
145 std::string hostname;
148 std::vector<CNetAddr> vIP;
149 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
152 vAddr.resize(vIP.size());
153 for (
unsigned int i = 0; i < vIP.size(); i++)
158 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
160 std::vector<CService> vService;
161 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
173 if(!
Lookup(pszName, addr, portDefault,
false))
180 struct timeval timeout;
181 timeout.tv_sec = nTimeout / 1000;
182 timeout.tv_usec = (nTimeout % 1000) * 1000;
247 static IntrRecvError InterruptibleRecv(uint8_t* data,
size_t len,
int timeout,
const SOCKET& hSocket)
250 int64_t endTime = curTime + timeout;
253 const int64_t maxWait = 1000;
254 while (len > 0 && curTime < endTime) {
255 ssize_t
ret = recv(hSocket, (
char*)data, len, 0);
259 }
else if (
ret == 0) {
264 if (!IsSelectableSocket(hSocket)) {
267 struct timeval tval =
MillisToTimeval(std::min(endTime - curTime, maxWait));
270 FD_SET(hSocket, &fdset);
271 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
279 if (interruptSocks5Recv)
294 static std::string Socks5ErrorString(uint8_t err)
298 return "general failure";
300 return "connection not allowed";
302 return "network unreachable";
304 return "host unreachable";
306 return "connection refused";
308 return "TTL expired";
310 return "protocol error";
312 return "address type not supported";
319 static bool Socks5(
const std::string& strDest,
int port,
const ProxyCredentials *auth,
const SOCKET& hSocket)
322 LogPrint(
BCLog::NET,
"SOCKS5 connecting %s\n", strDest);
323 if (strDest.size() > 255) {
324 return error(
"Hostname too long");
327 std::vector<uint8_t> vSocks5Init;
330 vSocks5Init.push_back(0x02);
334 vSocks5Init.push_back(0x01);
337 ssize_t
ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
338 if (
ret != (ssize_t)vSocks5Init.
size()) {
339 return error(
"Error sending to proxy");
342 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
343 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
347 return error(
"Proxy failed to initialize");
351 std::vector<uint8_t> vAuth;
352 vAuth.push_back(0x01);
354 return error(
"Proxy username or password too long");
355 vAuth.push_back(auth->
username.size());
357 vAuth.push_back(auth->
password.size());
359 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
360 if (
ret != (ssize_t)vAuth.
size()) {
361 return error(
"Error sending authentication to proxy");
365 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
366 return error(
"Error reading proxy authentication response");
368 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
369 return error(
"Proxy authentication unsuccessful");
374 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
376 std::vector<uint8_t> vSocks5;
379 vSocks5.push_back(0x00);
381 vSocks5.push_back(strDest.size());
382 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
383 vSocks5.push_back((port >> 8) & 0xFF);
384 vSocks5.push_back((port >> 0) & 0xFF);
385 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
386 if (
ret != (ssize_t)vSocks5.
size()) {
387 return error(
"Error sending to proxy");
390 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
397 return error(
"Error while reading proxy response");
401 return error(
"Proxy failed to accept request");
405 LogPrintf(
"Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
408 if (pchRet2[2] != 0x00) {
409 return error(
"Error: malformed proxy response");
411 uint8_t pchRet3[256];
414 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
415 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
418 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
420 return error(
"Error reading from proxy");
422 int nRecv = pchRet3[0];
423 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
426 default:
return error(
"Error: malformed proxy response");
429 return error(
"Error reading from proxy");
431 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
432 return error(
"Error reading from proxy");
434 LogPrint(
BCLog::NET,
"SOCKS5 connected %s\n", strDest);
440 struct sockaddr_storage sockaddr;
441 socklen_t len =
sizeof(sockaddr);
442 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
443 LogPrintf(
"Cannot create socket for %s: unsupported network\n", addrConnect.
ToString());
447 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
451 if (!IsSelectableSocket(hSocket)) {
453 LogPrintf(
"Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
460 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&
set,
sizeof(
int));
474 template<
typename... Args>
475 static void LogConnectFailure(
bool manual_connection,
const char* fmt,
const Args&... args) {
476 std::string error_message =
tfm::format(fmt, args...);
477 if (manual_connection) {
478 LogPrintf(
"%s\n", error_message);
486 struct sockaddr_storage sockaddr;
487 socklen_t len =
sizeof(sockaddr);
489 LogPrintf(
"Cannot connect to %s: invalid socket\n", addrConnect.
ToString());
492 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
493 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
496 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
505 FD_SET(hSocket, &fdset);
506 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
517 socklen_t nRetSize =
sizeof(nRet);
525 LogConnectFailure(manual_connection,
"connect() to %s failed after select(): %s", addrConnect.
ToString(),
NetworkErrorString(nRet));
543 assert(net >= 0 && net <
NET_MAX);
547 proxyInfo[net] = addrProxy;
552 assert(net >= 0 && net <
NET_MAX);
554 if (!proxyInfo[net].IsValid())
556 proxyInfoOut = proxyInfo[net];
564 nameProxy = addrProxy;
572 nameProxyOut = nameProxy;
583 for (
int i = 0; i <
NET_MAX; i++) {
584 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
594 if (outProxyConnectionFailed)
595 *outProxyConnectionFailed =
true;
601 static std::atomic_int counter(0);
603 if (!Socks5(strDest, (
unsigned short)port, &random_auth, hSocket)) {
607 if (!Socks5(strDest, (
unsigned short)port, 0, hSocket)) {
616 std::string strSubnet(pszName);
617 size_t slash = strSubnet.find_last_of(
'/');
618 std::vector<CNetAddr> vIP;
620 std::string strAddress = strSubnet.substr(0, slash);
621 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
624 if (slash != strSubnet.npos)
626 std::string strNetmask = strSubnet.substr(slash + 1);
631 return ret.IsValid();
636 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
638 return ret.IsValid();
645 return ret.IsValid();
656 if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
657 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
658 buf, ARRAYSIZE(buf),
nullptr))
660 return strprintf(
"%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t>().to_bytes(buf), err);
664 return strprintf(
"Unknown error (%d)", err);
675 #ifdef STRERROR_R_CHAR_P 676 s = strerror_r(err, buf,
sizeof(buf));
679 if (strerror_r(err, buf,
sizeof(buf)))
691 int ret = closesocket(hSocket);
693 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) {
717 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
719 int fFlags = fcntl(hSocket, F_GETFL, 0);
720 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
732 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&
set,
sizeof(
int));
738 interruptSocks5Recv = interrupt;
SOCKS5Reply
Values defined for REP in RFC1928.
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
void Downcase(std::string &str)
Converts the given string to its lowercase equivalent.
CService LookupNumeric(const char *pszName, int portDefault)
UniValue ret(UniValue::VARR)
bool GetNameProxy(proxyType &nameProxyOut)
bool SetNameProxy(const proxyType &addrProxy)
#define WSAGetLastError()
No authentication required.
SOCKS5Command
Values defined for CMD in RFC1928.
enum Network ParseNetwork(std::string net)
bool randomize_credentials
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
A combination of a network address (CNetAddr) and a (TCP) port.
Credentials for proxy authentication.
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool *outProxyConnectionFailed)
bool IsProxy(const CNetAddr &addr)
SOCKSVersion
SOCKS version.
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
SOCKS5Method
Values defined for METHOD in RFC1928.
bool LookupSubNet(const char *pszName, CSubNet &ret)
bool SetProxy(enum Network net, const proxyType &addrProxy)
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
SOCKET CreateSocket(const CService &addrConnect)
bool error(const char *fmt, const Args &... args)
bool SetSpecial(const std::string &strName)
void InterruptSocks5(bool interrupt)
std::string ToString() const
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Address type not supported.
Connection not allowed by ruleset.
std::string GetNetworkName(enum Network net)
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
SOCKS5Atyp
Values defined for ATYPE in RFC1928.