25 #include <boost/algorithm/string/case_conv.hpp> 26 #include <boost/algorithm/string/predicate.hpp> 28 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) 29 #define MSG_NOSIGNAL 0 47 if (net ==
"tor" || net ==
"onion")
return NET_TOR;
61 void SplitHostPort(std::string in,
int &portOut, std::string &hostOut) {
62 size_t colon = in.find_last_of(
':');
64 bool fHaveColon = colon != in.npos;
65 bool fBracketed = fHaveColon && (in[0]==
'[' && in[colon-1]==
']');
66 bool fMultiColon = fHaveColon && (in.find_last_of(
':',colon-1) != in.npos);
67 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
69 if (
ParseInt32(in.substr(colon + 1), &
n) &&
n > 0 &&
n < 0x10000) {
70 in = in.substr(0, colon);
74 if (in.size()>0 && in[0] ==
'[' && in[in.size()-1] ==
']')
75 hostOut = in.substr(1, in.size()-2);
80 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
92 #ifdef HAVE_GETADDRINFO_A 93 struct in_addr ipv4_addr;
95 if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
100 struct in6_addr ipv6_addr;
101 if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
106 ipv4_addr.s_addr = inet_addr(pszName);
107 if (ipv4_addr.s_addr != INADDR_NONE) {
114 struct addrinfo aiHint;
115 memset(&aiHint, 0,
sizeof(
struct addrinfo));
116 aiHint.ai_socktype = SOCK_STREAM;
117 aiHint.ai_protocol = IPPROTO_TCP;
118 aiHint.ai_family = AF_UNSPEC;
120 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
122 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
125 struct addrinfo *aiRes = NULL;
126 #ifdef HAVE_GETADDRINFO_A 127 struct gaicb gcb, *query = &gcb;
128 memset(query, 0,
sizeof(
struct gaicb));
129 gcb.ar_name = pszName;
130 gcb.ar_request = &aiHint;
131 int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
140 struct timespec ts = { 2, 0 };
141 gai_suspend(&query, 1, &ts);
142 boost::this_thread::interruption_point();
144 nErr = gai_error(query);
146 aiRes = query->ar_result;
147 }
while (nErr == EAI_INPROGRESS);
149 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
154 struct addrinfo *aiTrav = aiRes;
155 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
157 if (aiTrav->ai_family == AF_INET)
159 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
160 vIP.push_back(
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
163 if (aiTrav->ai_family == AF_INET6)
165 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
166 vIP.push_back(
CNetAddr(((
struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
169 aiTrav = aiTrav->ai_next;
174 return (vIP.size() > 0);
177 bool LookupHost(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
179 std::string strHost(pszName);
182 if (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]"))
184 strHost = strHost.substr(1, strHost.size() - 2);
187 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
192 std::vector<CNetAddr> vIP;
200 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
204 int port = portDefault;
205 std::string hostname =
"";
208 std::vector<CNetAddr> vIP;
209 bool fRet =
LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
212 vAddr.resize(vIP.size());
213 for (
unsigned int i = 0; i < vIP.size(); i++)
218 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
220 std::vector<CService> vService;
221 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
233 if(!
Lookup(pszName, addr, portDefault,
false))
240 struct timeval timeout;
241 timeout.tv_sec = nTimeout / 1000;
242 timeout.tv_usec = (nTimeout % 1000) * 1000;
260 int64_t endTime = curTime + timeout;
263 const int64_t maxWait = 1000;
264 while (len > 0 && curTime < endTime) {
265 ssize_t ret = recv(hSocket,
data, len, 0);
269 }
else if (ret == 0) {
277 struct timeval tval =
MillisToTimeval(std::min(endTime - curTime, maxWait));
280 FD_SET(hSocket, &fdset);
281 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
305 LogPrintf(
"SOCKS5 connecting %s\n", strDest);
306 if (strDest.size() > 255) {
308 return error(
"Hostname too long");
311 std::vector<uint8_t> vSocks5Init;
312 vSocks5Init.push_back(0x05);
314 vSocks5Init.push_back(0x02);
315 vSocks5Init.push_back(0x00);
316 vSocks5Init.push_back(0x02);
318 vSocks5Init.push_back(0x01);
319 vSocks5Init.push_back(0x00);
322 if (ret != (ssize_t)vSocks5Init.size()) {
324 return error(
"Error sending to proxy");
329 return error(
"Error reading proxy response");
331 if (pchRet1[0] != 0x05) {
333 return error(
"Proxy failed to initialize");
335 if (pchRet1[1] == 0x02 && auth) {
337 std::vector<uint8_t> vAuth;
338 vAuth.push_back(0x01);
340 return error(
"Proxy username or password too long");
341 vAuth.push_back(auth->
username.size());
343 vAuth.push_back(auth->
password.size());
346 if (ret != (ssize_t)vAuth.size()) {
348 return error(
"Error sending authentication to proxy");
354 return error(
"Error reading proxy authentication response");
356 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
358 return error(
"Proxy authentication unsuccessful");
360 }
else if (pchRet1[1] == 0x00) {
364 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
366 std::vector<uint8_t> vSocks5;
367 vSocks5.push_back(0x05);
368 vSocks5.push_back(0x01);
369 vSocks5.push_back(0x00);
370 vSocks5.push_back(0x03);
371 vSocks5.push_back(strDest.size());
372 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
373 vSocks5.push_back((
port >> 8) & 0xFF);
374 vSocks5.push_back((
port >> 0) & 0xFF);
376 if (ret != (ssize_t)vSocks5.size()) {
378 return error(
"Error sending to proxy");
383 return error(
"Error reading proxy response");
385 if (pchRet2[0] != 0x05) {
387 return error(
"Proxy failed to accept request");
389 if (pchRet2[1] != 0x00) {
393 case 0x01:
return error(
"Proxy error: general failure");
394 case 0x02:
return error(
"Proxy error: connection not allowed");
395 case 0x03:
return error(
"Proxy error: network unreachable");
396 case 0x04:
return error(
"Proxy error: host unreachable");
397 case 0x05:
return error(
"Proxy error: connection refused");
398 case 0x06:
return error(
"Proxy error: TTL expired");
399 case 0x07:
return error(
"Proxy error: protocol error");
400 case 0x08:
return error(
"Proxy error: address type not supported");
401 default:
return error(
"Proxy error: unknown");
404 if (pchRet2[2] != 0x00) {
406 return error(
"Error: malformed proxy response");
418 return error(
"Error reading from proxy");
420 int nRecv = pchRet3[0];
424 default:
CloseSocket(hSocket);
return error(
"Error: malformed proxy response");
428 return error(
"Error reading from proxy");
432 return error(
"Error reading from proxy");
434 LogPrintf(
"SOCKS5 connected %s\n", strDest);
442 struct sockaddr_storage sockaddr;
443 socklen_t len =
sizeof(sockaddr);
444 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
445 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
449 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
456 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&
set,
sizeof(
int));
461 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
const char*)&
set,
sizeof(
int));
463 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (
void*)&
set,
sizeof(
int));
470 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
479 FD_SET(hSocket, &fdset);
480 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
493 socklen_t nRetSize =
sizeof(nRet);
495 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
497 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
523 hSocketRet = hSocket;
528 assert(net >= 0 && net <
NET_MAX);
537 assert(net >= 0 && net <
NET_MAX);
568 for (
int i = 0; i <
NET_MAX; i++) {
580 if (outProxyConnectionFailed)
581 *outProxyConnectionFailed =
true;
589 if (!
Socks5(strDest, (
unsigned short)
port, &random_auth, hSocket))
592 if (!
Socks5(strDest, (
unsigned short)
port, 0, hSocket))
596 hSocketRet = hSocket;
603 if (outProxyConnectionFailed)
604 *outProxyConnectionFailed =
false;
615 int port = portDefault;
617 if (outProxyConnectionFailed)
618 *outProxyConnectionFailed =
false;
625 std::vector<CService> addrResolved;
627 if (addrResolved.size() > 0) {
628 addr = addrResolved[
GetRand(addrResolved.size())];
642 std::string strSubnet(pszName);
643 size_t slash = strSubnet.find_last_of(
'/');
644 std::vector<CNetAddr> vIP;
646 std::string strAddress = strSubnet.substr(0, slash);
647 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
650 if (slash != strSubnet.npos)
652 std::string strNetmask = strSubnet.substr(slash + 1);
662 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
663 ret =
CSubNet(network, vIP[0]);
682 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
683 NULL,
err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
684 buf,
sizeof(buf), NULL))
701 #ifdef STRERROR_R_CHAR_P 702 s = strerror_r(
err, buf,
sizeof(buf));
704 if (strerror_r(
err, buf,
sizeof(buf)))
716 int ret = closesocket(hSocket);
718 int ret = close(hSocket);
729 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
731 int fFlags = fcntl(hSocket, F_GETFL, 0);
732 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
740 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
742 int fFlags = fcntl(hSocket, F_GETFL, 0);
743 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {
static bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
bool randomize_credentials
static bool ConnectSocketDirectly(const CService &addrConnect, SOCKET &hSocketRet, int nTimeout)
std::string ToStringIP(bool fUseGetnameinfo=true) const
static bool InterruptibleRecv(char *data, size_t len, int timeout, SOCKET &hSocket)
CService LookupNumeric(const char *pszName, int portDefault)
static bool Socks5(const std::string &strDest, int port, const ProxyCredentials *auth, SOCKET &hSocket)
bool GetNameProxy(proxyType &nameProxyOut)
std::string ToString(bool fUseGetnameinfo=true) const
bool SetNameProxy(const proxyType &addrProxy)
#define WSAGetLastError()
static uint32_t insecure_rand(void)
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
static CCriticalSection cs_proxyInfos
static const int SOCKS5_RECV_TIMEOUT
unsigned short GetPort() const
bool SetSocketNonBlocking(SOCKET &hSocket, bool fNonBlocking)
static bool IsSelectableSocket(SOCKET s)
enum Network ParseNetwork(std::string net)
static bool LookupIntern(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool ParseInt32(const std::string &str, int32_t *out)
static int LogPrint(const char *category, const char *format)
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
static bool error(const char *format)
bool IsProxy(const CNetAddr &addr)
static std::atomic< bool > interruptSocks5Recv(false)
static const int DEFAULT_NAME_LOOKUP
-dns default
bool CloseSocket(SOCKET &hSocket)
V::value_type * begin_ptr(V &v)
bool LookupSubNet(const char *pszName, CSubNet &ret)
bool SetProxy(enum Network net, const proxyType &addrProxy)
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
struct timeval MillisToTimeval(int64_t nTimeout)
static proxyType proxyInfo[NET_MAX]
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
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)
std::string GetNetworkName(enum Network net)
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
enum Network GetNetwork() const
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
static proxyType nameProxy
uint64_t GetRand(uint64_t nMax)