30 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
31 #define MSG_NOSIGNAL 0
43 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
44 static std::atomic<bool> interruptSocks5Recv(
false);
51 if (net ==
"tor" || net ==
"onion")
return NET_ONION;
73 size_t colon = in.find_last_of(
':');
75 bool fHaveColon = colon != in.npos;
76 bool fBracketed = fHaveColon && (in[0] ==
'[' && in[colon - 1] ==
']');
77 bool fMultiColon = fHaveColon && (in.find_last_of(
':', colon - 1) != in.npos);
78 if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
80 if (
ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
81 in = in.substr(0, colon);
85 if (in.size() > 0 && in[0] ==
'[' && in[in.size() - 1] ==
']')
86 hostOut = in.substr(1, in.size() - 2);
91 bool static LookupIntern(
const std::string&
name, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
107 struct addrinfo aiHint;
108 memset(&aiHint, 0,
sizeof(
struct addrinfo));
110 aiHint.ai_socktype = SOCK_STREAM;
111 aiHint.ai_protocol = IPPROTO_TCP;
112 aiHint.ai_family = AF_UNSPEC;
114 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
116 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
118 struct addrinfo* aiRes =
nullptr;
119 int nErr = getaddrinfo(
name.c_str(),
nullptr, &aiHint, &aiRes);
123 struct addrinfo* aiTrav = aiRes;
124 while (aiTrav !=
nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
126 if (aiTrav->ai_family == AF_INET) {
127 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
128 resolved =
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
131 if (aiTrav->ai_family == AF_INET6) {
132 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
133 struct sockaddr_in6* s6 = (
struct sockaddr_in6*) aiTrav->ai_addr;
134 resolved =
CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
138 vIP.push_back(resolved);
141 aiTrav = aiTrav->ai_next;
146 return (vIP.size() > 0);
149 bool LookupHost(
const std::string&
name, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
154 std::string strHost =
name;
157 if (strHost.front() ==
'[' && strHost.back() ==
']') {
158 strHost = strHost.substr(1, strHost.size() - 2);
161 return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup);
169 std::vector<CNetAddr> vIP;
177 bool Lookup(
const std::string&
name, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
182 int port = portDefault;
183 std::string hostname;
186 std::vector<CNetAddr> vIP;
187 bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup);
190 vAddr.resize(vIP.size());
191 for (
unsigned int i = 0; i < vIP.size(); i++)
201 std::vector<CService> vService;
202 bool fRet =
Lookup(
name, vService, portDefault, fAllowLookup, 1);
224 struct timeval timeout;
225 timeout.tv_sec = nTimeout / 1000;
226 timeout.tv_usec = (nTimeout % 1000) * 1000;
291 static IntrRecvError InterruptibleRecv(uint8_t* data,
size_t len,
int timeout,
const SOCKET& hSocket)
294 int64_t endTime = curTime + timeout;
297 const int64_t maxWait = 1000;
298 while (len > 0 && curTime < endTime) {
299 ssize_t ret = recv(hSocket, (
char*)data, len, 0);
303 }
else if (ret == 0) {
308 if (!IsSelectableSocket(hSocket)) {
311 int timeout_ms = std::min(endTime - curTime, maxWait);
313 struct pollfd pollfd = {};
315 pollfd.events = POLLIN | POLLOUT;
316 int nRet = poll(&pollfd, 1, timeout_ms);
321 FD_SET(hSocket, &fdset);
322 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
331 if (interruptSocks5Recv)
346 static std::string Socks5ErrorString(uint8_t err)
350 return "general failure";
352 return "connection not allowed";
354 return "network unreachable";
356 return "host unreachable";
358 return "connection refused";
360 return "TTL expired";
362 return "protocol error";
364 return "address type not supported";
375 if (strDest.size() > 255) {
376 return error(
"Hostname too long");
379 std::vector<uint8_t> vSocks5Init;
382 vSocks5Init.push_back(0x02);
386 vSocks5Init.push_back(0x01);
389 ssize_t ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
390 if (ret != (ssize_t)vSocks5Init.size()) {
391 return error(
"Error sending to proxy");
394 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
395 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
399 return error(
"Proxy failed to initialize");
403 std::vector<uint8_t> vAuth;
404 vAuth.push_back(0x01);
406 return error(
"Proxy username or password too long");
407 vAuth.push_back(auth->
username.size());
409 vAuth.push_back(auth->
password.size());
411 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
412 if (ret != (ssize_t)vAuth.size()) {
413 return error(
"Error sending authentication to proxy");
417 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
418 return error(
"Error reading proxy authentication response");
420 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
421 return error(
"Proxy authentication unsuccessful");
426 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
428 std::vector<uint8_t> vSocks5;
431 vSocks5.push_back(0x00);
433 vSocks5.push_back(strDest.size());
434 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
435 vSocks5.push_back((port >> 8) & 0xFF);
436 vSocks5.push_back((port >> 0) & 0xFF);
437 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
438 if (ret != (ssize_t)vSocks5.size()) {
439 return error(
"Error sending to proxy");
442 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
449 return error(
"Error while reading proxy response");
453 return error(
"Proxy failed to accept request");
457 LogPrintf(
"Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
460 if (pchRet2[2] != 0x00) {
461 return error(
"Error: malformed proxy response");
463 uint8_t pchRet3[256];
466 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
467 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
470 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
472 return error(
"Error reading from proxy");
474 int nRecv = pchRet3[0];
475 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
478 default:
return error(
"Error: malformed proxy response");
481 return error(
"Error reading from proxy");
483 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
484 return error(
"Error reading from proxy");
492 struct sockaddr_storage sockaddr;
493 socklen_t len =
sizeof(sockaddr);
494 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
495 LogPrintf(
"Cannot create socket for %s: unsupported network\n", addrConnect.
ToString());
499 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
503 if (!IsSelectableSocket(hSocket)) {
505 LogPrintf(
"Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
512 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
525 template<
typename... Args>
526 static void LogConnectFailure(
bool manual_connection,
const char* fmt,
const Args&... args) {
527 std::string error_message =
tfm::format(fmt, args...);
528 if (manual_connection) {
529 LogPrintf(
"%s\n", error_message);
537 struct sockaddr_storage sockaddr;
538 socklen_t len =
sizeof(sockaddr);
540 LogPrintf(
"Cannot connect to %s: invalid socket\n", addrConnect.
ToString());
543 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
544 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
547 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR) {
552 struct pollfd pollfd = {};
554 pollfd.events = POLLIN | POLLOUT;
555 int nRet = poll(&pollfd, 1, nTimeout);
560 FD_SET(hSocket, &fdset);
561 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
571 socklen_t nRetSize =
sizeof(nRet);
578 LogConnectFailure(manual_connection,
"connect() to %s failed after select(): %s", addrConnect.
ToString(),
NetworkErrorString(nRet));
597 assert(net >= 0 && net <
NET_MAX);
601 proxyInfo[net] = addrProxy;
607 assert(net >= 0 && net <
NET_MAX);
609 if (!proxyInfo[net].IsValid())
611 proxyInfoOut = proxyInfo[net];
620 nameProxy = addrProxy;
629 nameProxyOut = nameProxy;
642 for (
int i = 0; i <
NET_MAX; i++) {
643 if (addr ==
static_cast<CNetAddr>(proxyInfo[i].proxy))
653 if (outProxyConnectionFailed)
654 *outProxyConnectionFailed =
true;
660 static std::atomic_int counter;
662 if (!Socks5(strDest, (uint16_t)port, &random_auth, hSocket)) {
666 if (!Socks5(strDest, (uint16_t)port, 0, hSocket)) {
678 size_t slash = strSubnet.find_last_of(
'/');
679 std::vector<CNetAddr> vIP;
681 std::string strAddress = strSubnet.substr(0, slash);
685 if (slash != strSubnet.npos) {
686 std::string strNetmask = strSubnet.substr(slash + 1);
696 ret =
CSubNet(network, vIP[0]);
713 if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
714 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
715 buf, ARRAYSIZE(buf),
nullptr))
717 const auto& bufConvert = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t>().to_bytes(buf);
718 return strprintf(
"%s (%d)", bufConvert, err);
720 return strprintf(
"Unknown error (%d)", err);
731 #ifdef STRERROR_R_CHAR_P
732 s = strerror_r(err, buf,
sizeof(buf));
735 if (strerror_r(err, buf,
sizeof(buf)))
747 int ret = closesocket(hSocket);
749 int ret = close(hSocket);
760 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
762 int fFlags = fcntl(hSocket, F_GETFL, 0);
763 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
771 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
773 int fFlags = fcntl(hSocket, F_GETFL, 0);
774 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
787 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&set,
sizeof(
int));
793 interruptSocks5Recv = interrupt;
bool SetSpecial(const std::string &strName)
Parse a TOR address and set this object to it.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToString() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
bool randomize_credentials
#define WSAGetLastError()
#define LogPrint(category,...)
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
SOCKS5Command
Values defined for CMD in RFC1928.
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
bool GetNameProxy(proxyType &nameProxyOut)
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
bool SetSocketNoDelay(SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
enum Network ParseNetwork(std::string net)
std::string GetNetworkName(enum Network net)
SOCKSVersion
SOCKS version.
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
CService LookupNumeric(const std::string &name, int portDefault)
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool *outProxyConnectionFailed)
bool SetSocketNonBlocking(SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
SOCKS5Method
Values defined for METHOD in RFC1928.
@ GSSAPI
No authentication required.
@ NO_ACCEPTABLE
Username/password.
void InterruptSocks5(bool interrupt)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
SOCKS5Reply
Values defined for REP in RFC1928.
@ TTLEXPIRED
Connection refused.
@ CMDUNSUPPORTED
TTL expired.
@ NETUNREACHABLE
Connection not allowed by ruleset.
@ CONNREFUSED
Network unreachable.
@ ATYPEUNSUPPORTED
Command not supported.
@ NOTALLOWED
General failure.
@ HOSTUNREACHABLE
Network unreachable.
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
bool SetNameProxy(const proxyType &addrProxy)
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
bool IsProxy(const CNetAddr &addr)
SOCKET CreateSocket(const CService &addrConnect)
bool SetProxy(enum Network net, const proxyType &addrProxy)
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Credentials for proxy authentication.
bool error(const char *fmt, const Args &... args)
void Downcase(std::string &str)
Converts the given string to its lowercase equivalent.
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
int64_t GetTimeMillis()
Returns the system time (not mockable)