26 #include <boost/algorithm/string/case_conv.hpp> 27 #include <boost/algorithm/string/predicate.hpp> 29 #if !defined(HAVE_MSG_NOSIGNAL) 30 #define MSG_NOSIGNAL 0 41 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
42 static std::atomic<bool> interruptSocks5Recv(
false);
48 if (net ==
"tor" || net ==
"onion")
return NET_TOR;
62 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
74 struct addrinfo aiHint;
75 memset(&aiHint, 0,
sizeof(
struct addrinfo));
77 aiHint.ai_socktype = SOCK_STREAM;
78 aiHint.ai_protocol = IPPROTO_TCP;
79 aiHint.ai_family = AF_UNSPEC;
81 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
83 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
85 struct addrinfo *aiRes =
nullptr;
86 int nErr = getaddrinfo(pszName,
nullptr, &aiHint, &aiRes);
90 struct addrinfo *aiTrav = aiRes;
91 while (aiTrav !=
nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
94 if (aiTrav->ai_family == AF_INET)
96 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
97 resolved =
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
100 if (aiTrav->ai_family == AF_INET6)
102 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
103 struct sockaddr_in6*
s6 = (
struct sockaddr_in6*) aiTrav->ai_addr;
104 resolved =
CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
108 vIP.push_back(resolved);
111 aiTrav = aiTrav->ai_next;
116 return (vIP.size() > 0);
119 bool LookupHost(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
121 std::string strHost(pszName);
124 if (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]"))
126 strHost = strHost.substr(1, strHost.size() - 2);
129 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
134 std::vector<CNetAddr> vIP;
142 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
146 int port = portDefault;
147 std::string hostname =
"";
150 std::vector<CNetAddr> vIP;
151 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
154 vAddr.resize(vIP.size());
155 for (
unsigned int i = 0; i < vIP.size(); i++)
160 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
162 std::vector<CService> vService;
163 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
175 if(!
Lookup(pszName, addr, portDefault,
false))
182 struct timeval timeout;
183 timeout.tv_sec = nTimeout / 1000;
184 timeout.tv_usec = (nTimeout % 1000) * 1000;
249 static IntrRecvError InterruptibleRecv(uint8_t* data,
size_t len,
int timeout,
const SOCKET& hSocket)
252 int64_t endTime = curTime + timeout;
255 const int64_t maxWait = 1000;
256 while (len > 0 && curTime < endTime) {
257 ssize_t ret = recv(hSocket, (
char*)data, len, 0);
261 }
else if (ret == 0) {
266 if (!IsSelectableSocket(hSocket)) {
269 struct timeval tval =
MillisToTimeval(std::min(endTime - curTime, maxWait));
272 FD_SET(hSocket, &fdset);
273 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
281 if (interruptSocks5Recv)
300 return "general failure";
302 return "connection not allowed";
304 return "network unreachable";
306 return "host unreachable";
308 return "connection refused";
310 return "TTL expired";
312 return "protocol error";
314 return "address type not supported";
325 if (strDest.size() > 255) {
327 return error(
"Hostname too long");
330 std::vector<uint8_t> vSocks5Init;
333 vSocks5Init.push_back(0x02);
337 vSocks5Init.push_back(0x01);
340 ssize_t ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
341 if (ret != (ssize_t)vSocks5Init.size()) {
343 return error(
"Error sending to proxy");
346 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
348 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
353 return error(
"Proxy failed to initialize");
357 std::vector<uint8_t> vAuth;
358 vAuth.push_back(0x01);
360 return error(
"Proxy username or password too long");
361 vAuth.push_back(auth->
username.size());
363 vAuth.push_back(auth->
password.size());
365 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
366 if (ret != (ssize_t)vAuth.size()) {
368 return error(
"Error sending authentication to proxy");
372 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
374 return error(
"Error reading proxy authentication response");
376 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
378 return error(
"Proxy authentication unsuccessful");
384 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
386 std::vector<uint8_t> vSocks5;
389 vSocks5.push_back(0x00);
391 vSocks5.push_back(strDest.size());
392 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
393 vSocks5.push_back((port >> 8) & 0xFF);
394 vSocks5.push_back((port >> 0) & 0xFF);
395 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
396 if (ret != (ssize_t)vSocks5.size()) {
398 return error(
"Error sending to proxy");
401 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
409 return error(
"Error while reading proxy response");
414 return error(
"Proxy failed to accept request");
422 if (pchRet2[2] != 0x00) {
424 return error(
"Error: malformed proxy response");
426 uint8_t pchRet3[256];
429 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
430 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
433 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
436 return error(
"Error reading from proxy");
438 int nRecv = pchRet3[0];
439 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
442 default:
CloseSocket(hSocket);
return error(
"Error: malformed proxy response");
446 return error(
"Error reading from proxy");
448 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
450 return error(
"Error reading from proxy");
460 struct sockaddr_storage sockaddr;
461 socklen_t len =
sizeof(sockaddr);
462 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
463 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
467 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
474 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&
set,
sizeof(
int));
486 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
495 FD_SET(hSocket, &fdset);
496 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
509 socklen_t nRetSize =
sizeof(nRet);
511 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
513 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
539 hSocketRet = hSocket;
544 assert(net >= 0 && net <
NET_MAX);
548 proxyInfo[net] = addrProxy;
553 assert(net >= 0 && net <
NET_MAX);
555 if (!proxyInfo[net].IsValid())
557 proxyInfoOut = proxyInfo[net];
565 nameProxy = addrProxy;
573 nameProxyOut = nameProxy;
584 for (
int i = 0; i <
NET_MAX; i++) {
585 if (addr == (
CNetAddr)proxyInfo[i].proxy)
596 if (outProxyConnectionFailed)
597 *outProxyConnectionFailed =
true;
603 static std::atomic_int counter(0);
605 if (!Socks5(strDest, (
unsigned short)port, &random_auth, hSocket))
608 if (!Socks5(strDest, (
unsigned short)port, 0, hSocket))
612 hSocketRet = hSocket;
617 std::string strSubnet(pszName);
618 size_t slash = strSubnet.find_last_of(
'/');
619 std::vector<CNetAddr> vIP;
621 std::string strAddress = strSubnet.substr(0, slash);
622 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
625 if (slash != strSubnet.npos)
627 std::string strNetmask = strSubnet.substr(slash + 1);
637 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
638 ret =
CSubNet(network, vIP[0]);
657 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
658 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
659 buf,
sizeof(buf),
nullptr))
665 return strprintf(
"Unknown error (%d)", err);
676 #ifdef STRERROR_R_CHAR_P 677 s = strerror_r(err, buf,
sizeof(buf));
680 if (strerror_r(err, buf,
sizeof(buf)))
692 int ret = closesocket(hSocket);
694 int ret = close(hSocket);
705 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
707 int fFlags = fcntl(hSocket, F_GETFL, 0);
708 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
715 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
717 int fFlags = fcntl(hSocket, F_GETFL, 0);
718 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
730 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&
set,
sizeof(
int));
736 interruptSocks5Recv = interrupt;
SOCKS5Reply
Values defined for REP in RFC1928.
bool ConnectSocketDirectly(const CService &addrConnect, SOCKET &hSocketRet, int nTimeout)
No authentication required.
Connection not allowed by ruleset.
CService LookupNumeric(const char *pszName, int portDefault)
bool GetNameProxy(proxyType &nameProxyOut)
bool SetNameProxy(const proxyType &addrProxy)
#define WSAGetLastError()
SOCKS5Command
Values defined for CMD in RFC1928.
std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
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 IsProxy(const CNetAddr &addr)
SOCKSVersion
SOCKS version.
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
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.
#define LogPrint(category,...)
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)
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.
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.
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...