24 #if !defined(MSG_NOSIGNAL) 25 #define MSG_NOSIGNAL 0 41 std::string net =
ToLower(net_in);
52 LogPrintf(
"Warning: net name 'tor' is deprecated and will be removed " 53 "in the future. You should use 'onion' instead.\n");
73 unsigned int nMaxSolutions,
bool fAllowLookup) {
94 struct addrinfo aiHint;
95 memset(&aiHint, 0,
sizeof(
struct addrinfo));
98 aiHint.ai_socktype = SOCK_STREAM;
99 aiHint.ai_protocol = IPPROTO_TCP;
101 aiHint.ai_family = AF_UNSPEC;
108 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
109 struct addrinfo *aiRes =
nullptr;
110 int nErr = getaddrinfo(name.c_str(),
nullptr, &aiHint, &aiRes);
117 struct addrinfo *aiTrav = aiRes;
118 while (aiTrav !=
nullptr &&
119 (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
121 if (aiTrav->ai_family == AF_INET) {
122 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
124 CNetAddr(reinterpret_cast<struct sockaddr_in *>(aiTrav->ai_addr)
128 if (aiTrav->ai_family == AF_INET6) {
129 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
130 struct sockaddr_in6 *s6 =
131 reinterpret_cast<struct sockaddr_in6 *
>(aiTrav->ai_addr);
132 resolved =
CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
138 vIP.push_back(resolved);
141 aiTrav = aiTrav->ai_next;
146 return (vIP.size() > 0);
165 unsigned int nMaxSolutions,
bool fAllowLookup) {
169 std::string strHost =
name;
170 if (strHost.empty()) {
173 if (strHost.front() ==
'[' && strHost.back() ==
']') {
174 strHost = strHost.substr(1, strHost.size() - 2);
177 return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup);
190 std::vector<CNetAddr> vIP;
219 bool Lookup(
const std::string &
name, std::vector<CService> &vAddr,
220 int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions) {
224 int port = portDefault;
225 std::string hostname;
228 std::vector<CNetAddr> vIP;
229 bool fRet =
LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup);
233 vAddr.resize(vIP.size());
234 for (
unsigned int i = 0; i < vIP.size(); i++) {
251 std::vector<CService> vService;
252 bool fRet =
Lookup(name, vService, portDefault, fAllowLookup, 1);
277 if (!
Lookup(name, addr, portDefault,
false)) {
284 struct timeval timeout;
285 timeout.tv_sec = nTimeout / 1000;
286 timeout.tv_usec = (nTimeout % 1000) * 1000;
358 int64_t endTime = curTime + timeout;
361 const int64_t maxWait = 1000;
362 while (len > 0 && curTime < endTime) {
364 ssize_t ret = recv(hSocket, (
char *)data, len, 0);
368 }
else if (ret == 0) {
381 int timeout_ms = std::min(endTime - curTime, maxWait);
383 struct pollfd pollfd = {};
385 pollfd.events = POLLIN;
386 int nRet = poll(&pollfd, 1, timeout_ms);
391 FD_SET(hSocket, &fdset);
392 int nRet = select(hSocket + 1, &fdset,
nullptr,
nullptr, &tval);
419 return "general failure";
421 return "connection not allowed";
423 return "network unreachable";
425 return "host unreachable";
427 return "connection refused";
429 return "TTL expired";
431 return "protocol error";
433 return "address type not supported";
457 static bool Socks5(
const std::string &strDest,
int port,
461 if (strDest.size() > 255) {
462 return error(
"Hostname too long");
465 std::vector<uint8_t> vSocks5Init;
470 vSocks5Init.push_back(0x02);
475 vSocks5Init.push_back(0x01);
478 ssize_t ret = send(hSocket, (
const char *)vSocks5Init.data(),
480 if (ret != (ssize_t)vSocks5Init.size()) {
481 return error(
"Error sending to proxy");
486 LogPrintf(
"Socks5() connect to %s:%d failed: InterruptibleRecv() " 487 "timeout or other failure\n",
492 return error(
"Proxy failed to initialize");
496 std::vector<uint8_t> vAuth;
498 vAuth.push_back(0x01);
500 return error(
"Proxy username or password too long");
502 vAuth.push_back(auth->
username.size());
504 vAuth.push_back(auth->
password.size());
506 ret = send(hSocket, (
const char *)vAuth.data(), vAuth.size(),
508 if (ret != (ssize_t)vAuth.size()) {
509 return error(
"Error sending authentication to proxy");
516 return error(
"Error reading proxy authentication response");
518 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
519 return error(
"Proxy authentication unsuccessful");
524 return error(
"Proxy requested wrong authentication method %02x",
527 std::vector<uint8_t> vSocks5;
533 vSocks5.push_back(0x00);
537 vSocks5.push_back(strDest.size());
538 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
539 vSocks5.push_back((port >> 8) & 0xFF);
540 vSocks5.push_back((port >> 0) & 0xFF);
541 ret = send(hSocket, (
const char *)vSocks5.data(), vSocks5.size(),
543 if (ret != (ssize_t)vSocks5.size()) {
544 return error(
"Error sending to proxy");
557 return error(
"Error while reading proxy response");
561 return error(
"Proxy failed to accept request");
565 LogPrintf(
"Socks5() connect to %s:%d failed: %s\n", strDest, port,
570 if (pchRet2[2] != 0x00) {
571 return error(
"Error: malformed proxy response");
573 uint8_t pchRet3[256];
574 switch (pchRet2[3]) {
585 return error(
"Error reading from proxy");
587 int nRecv = pchRet3[0];
593 return error(
"Error: malformed proxy response");
596 return error(
"Error reading from proxy");
600 return error(
"Error reading from proxy");
615 struct sockaddr_storage sockaddr;
616 socklen_t len =
sizeof(sockaddr);
617 if (!addrConnect.
GetSockAddr((
struct sockaddr *)&sockaddr, &len)) {
618 LogPrintf(
"Cannot create socket for %s: unsupported network\n",
624 SOCKET hSocket = socket(((
struct sockaddr *)&sockaddr)->sa_family,
625 SOCK_STREAM, IPPROTO_TCP);
634 LogPrintf(
"Cannot create connection: non-selectable socket created (fd " 635 ">= FD_SETSIZE ?)\n");
653 LogPrintf(
"CreateSocket: Setting socket to non-blocking " 654 "failed, error %s\n",
660 template <
typename... Args>
662 const Args &... args) {
663 std::string error_message =
tfm::format(fmt, args...);
664 if (manual_connection) {
684 int nTimeout,
bool manual_connection) {
686 struct sockaddr_storage sockaddr;
687 socklen_t len =
sizeof(sockaddr);
689 LogPrintf(
"Cannot connect to %s: invalid socket\n",
693 if (!addrConnect.
GetSockAddr((
struct sockaddr *)&sockaddr, &len)) {
694 LogPrintf(
"Cannot connect to %s: unsupported network\n",
700 if (connect(hSocket, (
struct sockaddr *)&sockaddr, len) ==
SOCKET_ERROR) {
709 struct pollfd pollfd = {};
711 pollfd.events = POLLIN | POLLOUT;
712 int nRet = poll(&pollfd, 1, nTimeout);
717 FD_SET(hSocket, &fdset);
718 int nRet = select(hSocket + 1,
nullptr, &fdset,
nullptr, &timeout);
730 LogPrintf(
"select() for %s failed: %s\n",
740 socklen_t nRetSize =
sizeof(nRet);
741 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR,
744 LogPrintf(
"getsockopt() for %s failed: %s\n",
751 "connect() to %s failed after select(): %s",
773 assert(net >= 0 && net <
NET_MAX);
778 proxyInfo[net] = addrProxy;
783 assert(net >= 0 && net <
NET_MAX);
785 if (!proxyInfo[net].IsValid()) {
788 proxyInfoOut = proxyInfo[net];
813 nameProxy = addrProxy;
819 if (!nameProxy.IsValid()) {
822 nameProxyOut = nameProxy;
828 return nameProxy.IsValid();
833 for (
int i = 0; i <
NET_MAX; i++) {
834 if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) {
857 int port,
const SOCKET &hSocket,
int nTimeout,
858 bool &outProxyConnectionFailed) {
861 outProxyConnectionFailed =
true;
867 static std::atomic_int counter(0);
870 if (!
Socks5(strDest, (
unsigned short)port, &random_auth, hSocket)) {
873 }
else if (!
Socks5(strDest, (
unsigned short)port, 0, hSocket)) {
894 size_t slash = strSubnet.find_last_of(
'/');
895 std::vector<CNetAddr> vIP;
897 std::string strAddress = strSubnet.substr(0, slash);
902 if (slash != strSubnet.npos) {
903 std::string strNetmask = strSubnet.substr(slash + 1);
913 ret =
CSubNet(network, vIP[0]);
929 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
930 FORMAT_MESSAGE_IGNORE_INSERTS |
931 FORMAT_MESSAGE_MAX_WIDTH_MASK,
932 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
933 buf,
sizeof(buf),
nullptr)) {
936 return strprintf(
"Unknown error (%d)", err);
948 #ifdef STRERROR_R_CHAR_P 950 s = strerror_r(err, buf,
sizeof(buf));
954 if (strerror_r(err, buf,
sizeof(buf))) {
967 int ret = closesocket(hSocket);
969 int ret = close(hSocket);
972 LogPrintf(
"Socket close failed: %d. Error: %s\n", hSocket,
983 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
985 int fFlags = fcntl(hSocket, F_GETFL, 0);
986 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
993 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
995 int fFlags = fcntl(hSocket, F_GETFL, 0);
996 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
1007 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY,
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,...)
static bool IsSelectableSocket(const SOCKET &s)
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 void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args)
bool GetNameProxy(proxyType &nameProxyOut)
static void LogPrintf(const char *fmt, const Args &... args)
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.
bool randomize_credentials
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
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)
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
SOCKSVersion
SOCKS version.
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.
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
static proxyType proxyInfo [NET_MAX] GUARDED_BY(cs_proxyInfos)
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
static RecursiveMutex cs_proxyInfos
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)
Try to make this a dummy address that maps the specified onion address into IPv6 using OnionCat's ran...
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)
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
bool error(const char *fmt, const Args &... args)
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)