28 #if !defined(MSG_NOSIGNAL)
29 #define MSG_NOSIGNAL 0
44 std::string net =
ToLower(net_in);
49 LogPrintf(
"Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
71 bool static LookupIntern(
const std::string&
name, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
93 struct addrinfo aiHint;
94 memset(&aiHint, 0,
sizeof(
struct addrinfo));
97 aiHint.ai_socktype = SOCK_STREAM;
98 aiHint.ai_protocol = IPPROTO_TCP;
100 aiHint.ai_family = AF_UNSPEC;
107 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
108 struct addrinfo *aiRes =
nullptr;
109 int nErr = getaddrinfo(name.c_str(),
nullptr, &aiHint, &aiRes);
115 struct addrinfo *aiTrav = aiRes;
116 while (aiTrav !=
nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
119 if (aiTrav->ai_family == AF_INET)
121 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
122 resolved =
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
125 if (aiTrav->ai_family == AF_INET6)
127 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
128 struct sockaddr_in6* s6 = (
struct sockaddr_in6*) aiTrav->ai_addr;
129 resolved =
CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
133 vIP.push_back(resolved);
136 aiTrav = aiTrav->ai_next;
141 return (vIP.size() > 0);
159 bool LookupHost(
const std::string&
name, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
164 std::string strHost =
name;
167 if (strHost.front() ==
'[' && strHost.back() ==
']') {
168 strHost = strHost.substr(1, strHost.size() - 2);
171 return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup);
185 std::vector<CNetAddr> vIP;
213 bool Lookup(
const std::string&
name, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
218 int port = portDefault;
219 std::string hostname;
222 std::vector<CNetAddr> vIP;
223 bool fRet =
LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup);
226 vAddr.resize(vIP.size());
227 for (
unsigned int i = 0; i < vIP.size(); i++)
243 std::vector<CService> vService;
244 bool fRet =
Lookup(name, vService, portDefault, fAllowLookup, 1);
269 if(!
Lookup(name, addr, portDefault,
false))
276 struct timeval timeout;
277 timeout.tv_sec = nTimeout / 1000;
278 timeout.tv_usec = (nTimeout % 1000) * 1000;
353 int64_t endTime = curTime + timeout;
356 const int64_t maxWait = 1000;
357 while (len > 0 && curTime < endTime) {
358 ssize_t ret = recv(hSocket, (
char*)data, len, 0);
362 }
else if (ret == 0) {
372 int timeout_ms = std::min(endTime - curTime, maxWait);
374 struct pollfd pollfd = {};
376 pollfd.events = POLLIN;
377 int nRet = poll(&pollfd, 1, timeout_ms);
382 FD_SET(hSocket, &fdset);
383 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
411 return "general failure";
413 return "connection not allowed";
415 return "network unreachable";
417 return "host unreachable";
419 return "connection refused";
421 return "TTL expired";
423 return "protocol error";
425 return "address type not supported";
453 if (strDest.size() > 255) {
454 return error(
"Hostname too long");
457 std::vector<uint8_t> vSocks5Init;
460 vSocks5Init.push_back(0x02);
464 vSocks5Init.push_back(0x01);
467 ssize_t ret =
send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
468 if (ret != (ssize_t)vSocks5Init.size()) {
469 return error(
"Error sending to proxy");
473 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
477 return error(
"Proxy failed to initialize");
481 std::vector<uint8_t> vAuth;
482 vAuth.push_back(0x01);
484 return error(
"Proxy username or password too long");
485 vAuth.push_back(auth->
username.size());
487 vAuth.push_back(auth->
password.size());
490 if (ret != (ssize_t)vAuth.size()) {
491 return error(
"Error sending authentication to proxy");
496 return error(
"Error reading proxy authentication response");
498 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
499 return error(
"Proxy authentication unsuccessful");
504 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
506 std::vector<uint8_t> vSocks5;
509 vSocks5.push_back(0x00);
511 vSocks5.push_back(strDest.size());
512 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
513 vSocks5.push_back((port >> 8) & 0xFF);
514 vSocks5.push_back((port >> 0) & 0xFF);
515 ret =
send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
516 if (ret != (ssize_t)vSocks5.size()) {
517 return error(
"Error sending to proxy");
527 return error(
"Error while reading proxy response");
531 return error(
"Proxy failed to accept request");
538 if (pchRet2[2] != 0x00) {
539 return error(
"Error: malformed proxy response");
541 uint8_t pchRet3[256];
550 return error(
"Error reading from proxy");
552 int nRecv = pchRet3[0];
556 default:
return error(
"Error: malformed proxy response");
559 return error(
"Error reading from proxy");
562 return error(
"Error reading from proxy");
578 struct sockaddr_storage sockaddr;
579 socklen_t len =
sizeof(sockaddr);
580 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
581 LogPrintf(
"Cannot create socket for %s: unsupported network\n", addrConnect.
ToString());
586 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
594 LogPrintf(
"Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
602 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
616 template<
typename... Args>
618 std::string error_message =
tfm::format(fmt, args...);
619 if (manual_connection) {
641 struct sockaddr_storage sockaddr;
642 socklen_t len =
sizeof(sockaddr);
647 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
648 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
653 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
663 struct pollfd pollfd = {};
665 pollfd.events = POLLIN | POLLOUT;
666 int nRet = poll(&pollfd, 1, nTimeout);
671 FD_SET(hSocket, &fdset);
672 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
693 socklen_t nRetSize =
sizeof(nRet);
719 assert(net >= 0 && net <
NET_MAX);
722 LOCK(g_proxyinfo_mutex);
723 proxyInfo[net] = addrProxy;
728 assert(net >= 0 && net <
NET_MAX);
729 LOCK(g_proxyinfo_mutex);
730 if (!proxyInfo[net].IsValid())
732 proxyInfoOut = proxyInfo[net];
755 LOCK(g_proxyinfo_mutex);
756 nameProxy = addrProxy;
761 LOCK(g_proxyinfo_mutex);
762 if(!nameProxy.IsValid())
764 nameProxyOut = nameProxy;
769 LOCK(g_proxyinfo_mutex);
770 return nameProxy.IsValid();
774 LOCK(g_proxyinfo_mutex);
775 for (
int i = 0; i <
NET_MAX; i++) {
776 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
801 outProxyConnectionFailed =
true;
807 static std::atomic_int counter(0);
809 if (!
Socks5(strDest, (uint16_t)port, &random_auth, hSocket)) {
813 if (!
Socks5(strDest, (uint16_t)port, 0, hSocket)) {
836 size_t slash = strSubnet.find_last_of(
'/');
837 std::vector<CNetAddr> vIP;
839 std::string strAddress = strSubnet.substr(0, slash);
845 if (slash != strSubnet.npos)
847 std::string strNetmask = strSubnet.substr(slash + 1);
858 ret =
CSubNet(network, vIP[0]);
877 if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
878 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
879 buf, ARRAYSIZE(buf),
nullptr))
881 return strprintf(
"%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t>().to_bytes(buf), err);
885 return strprintf(
"Unknown error (%d)", err);
896 #ifdef STRERROR_R_CHAR_P
897 s = strerror_r(err, buf,
sizeof(buf));
900 if (strerror_r(err, buf,
sizeof(buf)))
912 int ret = closesocket(hSocket);
914 int ret = close(hSocket);
928 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
930 int fFlags = fcntl(hSocket, F_GETFL, 0);
931 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
938 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
940 int fFlags = fcntl(hSocket, F_GETFL, 0);
941 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
953 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&set,
sizeof(
int));
SOCKS5Reply
Values defined for REP in RFC1928.
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
#define LogPrint(category,...)
A set of addresses that represent the hash of a string or FQDN.
Dummy value to indicate the number of NET_* constants.
static bool IsSelectableSocket(const SOCKET &s)
static Mutex g_proxyinfo_mutex
int64_t GetTimeMillis()
Returns the system time (not mockable)
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout, const SOCKET &hSocket)
Try to read a specified number of bytes from a socket.
NODISCARD bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex)
static void LogPrintf(const char *fmt, const Args &...args)
bool GetNameProxy(proxyType &nameProxyOut)
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
#define WSAGetLastError()
No authentication required.
SOCKS5Command
Values defined for CMD in RFC1928.
static const int SOCKS5_RECV_TIMEOUT
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
Parse and resolve a specified subnet string into the appropriate internal representation.
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &...args)
bool error(const char *fmt, const Args &...args)
bool randomize_credentials
A combination of a network address (CNetAddr) and a (TCP) port.
Credentials for proxy authentication.
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
static bool LookupIntern(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool IsProxy(const CNetAddr &addr)
SOCKSVersion
SOCKS version.
std::string ToString() const
static std::atomic< bool > interruptSocks5Recv(false)
static const int DEFAULT_NAME_LOOKUP
-dns default
static bool Socks5(const std::string &strDest, int port, const ProxyCredentials *auth, const SOCKET &hSocket)
Connect to a specified destination service through an already connected SOCKS5 proxy.
bool CloseSocket(SOCKET &hSocket)
Close socket and set hSocket to INVALID_SOCKET.
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
SOCKS5Method
Values defined for METHOD in RFC1928.
bool SetProxy(enum Network net, const proxyType &addrProxy)
bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking)
Disable or enable blocking-mode for a socket.
enum Network ParseNetwork(const std::string &net_in)
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
SOCKET CreateSocket(const CService &addrConnect)
Try to create a socket file descriptor with specific properties in the communications domain (address...
bool SetSpecial(const std::string &strName)
Parse a TOR address and set this object to it.
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.
Address type not supported.
bool ParseUInt8(const std::string &str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
Connection not allowed by ruleset.
std::string GetNetworkName(enum Network net)
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Addresses from these networks are not publicly routable on the global Internet.