25 #include <boost/algorithm/string/case_conv.hpp> 26 #include <boost/algorithm/string/predicate.hpp> 28 #if !defined(HAVE_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 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 (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]"))
125 strHost = strHost.substr(1, strHost.size() - 2);
128 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
133 std::vector<CNetAddr> vIP;
141 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
145 int port = portDefault;
146 std::string hostname =
"";
149 std::vector<CNetAddr> vIP;
150 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
153 vAddr.resize(vIP.size());
154 for (
unsigned int i = 0; i < vIP.size(); i++)
159 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
161 std::vector<CService> vService;
162 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
174 if(!
Lookup(pszName, addr, portDefault,
false))
181 struct timeval timeout;
182 timeout.tv_sec = nTimeout / 1000;
183 timeout.tv_usec = (nTimeout % 1000) * 1000;
251 int64_t endTime = curTime + timeout;
254 const int64_t maxWait = 1000;
255 while (len > 0 && curTime < endTime) {
256 ssize_t ret = recv(hSocket, (
char*)
data, len, 0);
260 }
else if (ret == 0) {
265 if (!IsSelectableSocket(hSocket)) {
271 FD_SET(hSocket, &fdset);
272 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
280 if (interruptSocks5Recv)
299 return "general failure";
301 return "connection not allowed";
303 return "network unreachable";
305 return "host unreachable";
307 return "connection refused";
309 return "TTL expired";
311 return "protocol error";
313 return "address type not supported";
324 if (strDest.size() > 255) {
326 return error(
"Hostname too long");
329 std::vector<uint8_t> vSocks5Init;
332 vSocks5Init.push_back(0x02);
336 vSocks5Init.push_back(0x01);
339 ssize_t ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
340 if (ret != (ssize_t)vSocks5Init.size()) {
342 return error(
"Error sending to proxy");
345 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
347 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
352 return error(
"Proxy failed to initialize");
356 std::vector<uint8_t> vAuth;
357 vAuth.push_back(0x01);
359 return error(
"Proxy username or password too long");
360 vAuth.push_back(auth->
username.size());
362 vAuth.push_back(auth->
password.size());
364 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
365 if (ret != (ssize_t)vAuth.size()) {
367 return error(
"Error sending authentication to proxy");
371 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
373 return error(
"Error reading proxy authentication response");
375 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
377 return error(
"Proxy authentication unsuccessful");
383 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
385 std::vector<uint8_t> vSocks5;
388 vSocks5.push_back(0x00);
390 vSocks5.push_back(strDest.size());
391 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
392 vSocks5.push_back((port >> 8) & 0xFF);
393 vSocks5.push_back((port >> 0) & 0xFF);
394 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
395 if (ret != (ssize_t)vSocks5.size()) {
397 return error(
"Error sending to proxy");
400 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
408 return error(
"Error while reading proxy response");
413 return error(
"Proxy failed to accept request");
421 if (pchRet2[2] != 0x00) {
423 return error(
"Error: malformed proxy response");
425 uint8_t pchRet3[256];
428 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
429 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
432 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
435 return error(
"Error reading from proxy");
437 int nRecv = pchRet3[0];
438 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
441 default:
CloseSocket(hSocket);
return error(
"Error: malformed proxy response");
445 return error(
"Error reading from proxy");
447 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
449 return error(
"Error reading from proxy");
455 bool static ConnectSocketDirectly(
const CService &addrConnect,
SOCKET& hSocketRet,
int nTimeout)
459 struct sockaddr_storage sockaddr;
460 socklen_t len =
sizeof(sockaddr);
461 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
462 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
466 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
473 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&
set,
sizeof(
int));
485 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
487 if (!IsSelectableSocket(hSocket)) {
488 LogPrintf(
"Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
499 FD_SET(hSocket, &fdset);
500 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
513 socklen_t nRetSize =
sizeof(nRet);
515 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
517 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
543 hSocketRet = hSocket;
552 proxyInfo[net] = addrProxy;
559 if (!proxyInfo[net].IsValid())
561 proxyInfoOut = proxyInfo[net];
569 nameProxy = addrProxy;
577 nameProxyOut = nameProxy;
588 for (
int i = 0; i <
NET_MAX; i++) {
589 if (addr == (
CNetAddr)proxyInfo[i].proxy)
595 static bool ConnectThroughProxy(
const proxyType &proxy,
const std::string& strDest,
int port,
SOCKET& hSocketRet,
int nTimeout,
bool *outProxyConnectionFailed)
599 if (!ConnectSocketDirectly(proxy.
proxy, hSocket, nTimeout)) {
600 if (outProxyConnectionFailed)
601 *outProxyConnectionFailed =
true;
607 static std::atomic_int counter(0);
609 if (!Socks5(strDest, (
unsigned short)port, &random_auth, hSocket))
612 if (!Socks5(strDest, (
unsigned short)port, 0, hSocket))
616 hSocketRet = hSocket;
623 if (outProxyConnectionFailed)
624 *outProxyConnectionFailed =
false;
627 return ConnectThroughProxy(proxy, addrDest.
ToStringIP(), addrDest.
GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
629 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
635 int port = portDefault;
637 if (outProxyConnectionFailed)
638 *outProxyConnectionFailed =
false;
645 std::vector<CService> addrResolved;
647 if (addrResolved.size() > 0) {
648 addr = addrResolved[
GetRand(addrResolved.size())];
657 return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
662 std::string strSubnet(pszName);
663 size_t slash = strSubnet.find_last_of(
'/');
664 std::vector<CNetAddr> vIP;
666 std::string strAddress = strSubnet.substr(0, slash);
667 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
670 if (slash != strSubnet.npos)
672 std::string strNetmask = strSubnet.substr(slash + 1);
682 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
683 ret =
CSubNet(network, vIP[0]);
702 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
703 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
704 buf,
sizeof(buf),
nullptr))
710 return strprintf(
"Unknown error (%d)", err);
721 #ifdef STRERROR_R_CHAR_P 722 s = strerror_r(err, buf,
sizeof(buf));
725 if (strerror_r(err, buf,
sizeof(buf)))
737 int ret = closesocket(hSocket);
739 int ret = close(hSocket);
750 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
752 int fFlags = fcntl(hSocket, F_GETFL, 0);
753 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
760 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
762 int fFlags = fcntl(hSocket, F_GETFL, 0);
763 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
775 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&
set,
sizeof(
int));
781 interruptSocks5Recv = interrupt;
bool error(const char *fmt, const Args &...args)
SOCKS5Reply
Values defined for REP in RFC1928.
unsigned short GetPort() const
No authentication required.
std::string ToStringIP() const
Connection not allowed by ruleset.
CService LookupNumeric(const char *pszName, int portDefault)
bool GetNameProxy(proxyType &nameProxyOut)
assert(len-trim+(2 *lenIndices)<=WIDTH)
bool SetNameProxy(const proxyType &addrProxy)
#define WSAGetLastError()
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
SOCKS5Command
Values defined for CMD in RFC1928.
std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to a 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 ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
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.
std::string ToString() const
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 SetSpecial(const std::string &strName)
void InterruptSocks5(bool interrupt)
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.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
uint64_t GetRand(uint64_t nMax)
enum Network GetNetwork() const