21 #ifdef HAVE_GETADDRINFO_A
27 #include <arpa/inet.h>
32 #include <boost/algorithm/string/case_conv.hpp>
33 #include <boost/algorithm/string/predicate.hpp>
34 #include <boost/thread.hpp>
36 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
37 #define MSG_NOSIGNAL 0
49 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
56 if (net ==
"tor" || net ==
"onion")
return NET_TOR;
76 size_t colon = in.find_last_of(
':');
78 bool fHaveColon = colon != in.npos;
79 bool fBracketed = fHaveColon && (in[0] ==
'[' && in[colon - 1] ==
']');
80 bool fMultiColon = fHaveColon && (in.find_last_of(
':', colon - 1) != in.npos);
81 if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
83 if (
ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
84 in = in.substr(0, colon);
88 if (in.size() > 0 && in[0] ==
'[' && in[in.size() - 1] ==
']')
89 hostOut = in.substr(1, in.size() - 2);
94 bool static LookupIntern(
const char* pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
106 #ifdef HAVE_GETADDRINFO_A
107 struct in_addr ipv4_addr;
108 #ifdef HAVE_INET_PTON
109 if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
114 struct in6_addr ipv6_addr;
115 if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
120 ipv4_addr.s_addr = inet_addr(pszName);
121 if (ipv4_addr.s_addr != INADDR_NONE) {
128 struct addrinfo aiHint;
129 memset(&aiHint, 0,
sizeof(
struct addrinfo));
130 aiHint.ai_socktype = SOCK_STREAM;
131 aiHint.ai_protocol = IPPROTO_TCP;
132 aiHint.ai_family = AF_UNSPEC;
133 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
135 struct addrinfo* aiRes = NULL;
136 #ifdef HAVE_GETADDRINFO_A
137 struct gaicb gcb, *query = &gcb;
138 memset(query, 0,
sizeof(
struct gaicb));
139 gcb.ar_name = pszName;
140 gcb.ar_request = &aiHint;
141 int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
150 struct timespec ts = {2, 0};
151 gai_suspend(&query, 1, &ts);
152 boost::this_thread::interruption_point();
154 nErr = gai_error(query);
156 aiRes = query->ar_result;
157 }
while (nErr == EAI_INPROGRESS);
159 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
164 struct addrinfo* aiTrav = aiRes;
165 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
166 if (aiTrav->ai_family == AF_INET) {
167 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
168 vIP.push_back(
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
171 if (aiTrav->ai_family == AF_INET6) {
172 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
173 vIP.push_back(
CNetAddr(((
struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
176 aiTrav = aiTrav->ai_next;
181 return (vIP.size() > 0);
184 bool LookupHost(
const char* pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
186 std::string strHost(pszName);
189 if (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]")) {
190 strHost = strHost.substr(1, strHost.size() - 2);
193 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
198 std::vector<CNetAddr> vIP;
206 bool Lookup(
const char* pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
210 int port = portDefault;
211 std::string hostname =
"";
214 std::vector<CNetAddr> vIP;
215 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
218 vAddr.resize(vIP.size());
219 for (
unsigned int i = 0; i < vIP.size(); i++)
224 bool Lookup(
const char* pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
226 std::vector<CService> vService;
227 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
239 if(!
Lookup(pszName, addr, portDefault,
false))
246 struct timeval timeout;
247 timeout.tv_sec = nTimeout / 1000;
248 timeout.tv_usec = (nTimeout % 1000) * 1000;
271 static IntrRecvError InterruptibleRecv(
char* data,
size_t len,
int timeout,
SOCKET& hSocket)
274 int64_t endTime = curTime + timeout;
277 const int64_t maxWait = 1000;
278 while (len > 0 && curTime < endTime) {
279 ssize_t ret = recv(hSocket, data, len, 0);
283 }
else if (ret == 0) {
288 if (!IsSelectableSocket(hSocket)) {
291 struct timeval tval =
MillisToTimeval(std::min(endTime - curTime, maxWait));
294 FD_SET(hSocket, &fdset);
295 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
303 boost::this_thread::interruption_point();
319 LogPrintf(
"SOCKS5 connecting %s\n", strDest);
320 if (strDest.size() > 255) {
322 return error(
"Hostname too long");
325 std::vector<uint8_t> vSocks5Init;
326 vSocks5Init.push_back(0x05);
328 vSocks5Init.push_back(0x02);
329 vSocks5Init.push_back(0x00);
330 vSocks5Init.push_back(0x02);
332 vSocks5Init.push_back(0x01);
333 vSocks5Init.push_back(0x00);
335 ssize_t ret = send(hSocket, (
const char*)vSocks5Init.data(), vSocks5Init.size(),
MSG_NOSIGNAL);
336 if (ret != (ssize_t)vSocks5Init.size()) {
338 return error(
"Error sending to proxy");
341 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
343 return error(
"Error reading proxy response");
345 if (pchRet1[0] != 0x05) {
347 return error(
"Proxy failed to initialize");
349 if (pchRet1[1] == 0x02 && auth) {
351 std::vector<uint8_t> vAuth;
352 vAuth.push_back(0x01);
354 return error(
"Proxy username or password too long");
355 vAuth.push_back(auth->
username.size());
357 vAuth.push_back(auth->
password.size());
359 ret = send(hSocket, (
const char*)vAuth.data(), vAuth.size(),
MSG_NOSIGNAL);
360 if (ret != (ssize_t)vAuth.size()) {
362 return error(
"Error sending authentication to proxy");
366 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
368 return error(
"Error reading proxy authentication response");
370 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
372 return error(
"Proxy authentication unsuccesful");
374 }
else if (pchRet1[1] == 0x00) {
378 return error(
"Proxy requested wrong authentication method %02x", pchRet1[1]);
380 std::vector<uint8_t> vSocks5;
381 vSocks5.push_back(0x05);
382 vSocks5.push_back(0x01);
383 vSocks5.push_back(0x00);
384 vSocks5.push_back(0x03);
385 vSocks5.push_back(strDest.size());
386 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
387 vSocks5.push_back((port >> 8) & 0xFF);
388 vSocks5.push_back((port >> 0) & 0xFF);
389 ret = send(hSocket, (
const char*)vSocks5.data(), vSocks5.size(),
MSG_NOSIGNAL);
390 if (ret != (ssize_t)vSocks5.size()) {
392 return error(
"Error sending to proxy");
395 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
403 return error(
"Error while reading proxy response");
406 if (pchRet2[0] != 0x05) {
408 return error(
"Proxy failed to accept request");
410 if (pchRet2[1] != 0x00) {
412 switch (pchRet2[1]) {
414 return error(
"Proxy error: general failure");
416 return error(
"Proxy error: connection not allowed");
418 return error(
"Proxy error: network unreachable");
420 return error(
"Proxy error: host unreachable");
422 return error(
"Proxy error: connection refused");
424 return error(
"Proxy error: TTL expired");
426 return error(
"Proxy error: protocol error");
428 return error(
"Proxy error: address type not supported");
430 return error(
"Proxy error: unknown");
433 if (pchRet2[2] != 0x00) {
435 return error(
"Error: malformed proxy response");
438 switch (pchRet2[3]) {
440 recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
443 recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
446 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
449 return error(
"Error reading from proxy");
451 int nRecv = pchRet3[0];
452 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
457 return error(
"Error: malformed proxy response");
461 return error(
"Error reading from proxy");
463 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
465 return error(
"Error reading from proxy");
467 LogPrintf(
"SOCKS5 connected %s\n", strDest);
471 bool static ConnectSocketDirectly(
const CService& addrConnect,
SOCKET& hSocketRet,
int nTimeout)
475 struct sockaddr_storage sockaddr;
476 socklen_t len =
sizeof(sockaddr);
477 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
478 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
482 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
489 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
496 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR) {
503 FD_SET(hSocket, &fdset);
504 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
515 socklen_t nRetSize =
sizeof(nRet);
517 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
519 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
544 hSocketRet = hSocket;
550 assert(net >= 0 && net <
NET_MAX);
554 proxyInfo[net] = addrProxy;
560 assert(net >= 0 && net <
NET_MAX);
562 if (!proxyInfo[net].IsValid())
564 proxyInfoOut = proxyInfo[net];
573 nameProxy = addrProxy;
582 nameProxyOut = nameProxy;
595 for (
int i = 0; i <
NET_MAX; i++) {
596 if (addr == (
CNetAddr)proxyInfo[i].proxy)
602 static bool ConnectThroughProxy(
const proxyType &proxy,
const std::string strDest,
int port,
SOCKET& hSocketRet,
int nTimeout,
bool *outProxyConnectionFailed)
606 if (!ConnectSocketDirectly(proxy.
proxy, hSocket, nTimeout)) {
607 if (outProxyConnectionFailed)
608 *outProxyConnectionFailed =
true;
614 static std::atomic_int counter;
616 if (!Socks5(strDest, (
unsigned short)port, &random_auth, hSocket))
619 if (!Socks5(strDest, (
unsigned short)port, 0, hSocket))
623 hSocketRet = hSocket;
630 if (outProxyConnectionFailed)
631 *outProxyConnectionFailed =
false;
634 return ConnectThroughProxy(proxy, addrDest.
ToStringIP(), addrDest.
GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
636 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
642 int port = portDefault;
644 if (outProxyConnectionFailed)
645 *outProxyConnectionFailed =
false;
652 std::vector<CService> addrResolved;
654 if (addrResolved.size() > 0) {
655 addr = addrResolved[
GetRand(addrResolved.size())];
664 return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
669 std::string strSubnet(pszName);
670 size_t slash = strSubnet.find_last_of(
'/');
671 std::vector<CNetAddr> vIP;
673 std::string strAddress = strSubnet.substr(0, slash);
674 if (
LookupHost(strAddress.c_str(), vIP, 1,
false))
677 if (slash != strSubnet.npos)
679 std::string strNetmask = strSubnet.substr(slash + 1);
689 if (
LookupHost(strNetmask.c_str(), vIP, 1,
false)) {
690 ret =
CSubNet(network, vIP[0]);
709 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
710 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
711 buf,
sizeof(buf), NULL)) {
714 return strprintf(
"Unknown error (%d)", err);
725 #ifdef STRERROR_R_CHAR_P
726 s = strerror_r(err, buf,
sizeof(buf));
728 if (strerror_r(err, buf,
sizeof(buf)))
740 int ret = closesocket(hSocket);
742 int ret = close(hSocket);
756 if (ioctlsocket(hSocket, FIONBIO, &nOne) ==
SOCKET_ERROR) {
758 int fFlags = fcntl(hSocket, F_GETFL, 0);
759 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) ==
SOCKET_ERROR) {
767 if (ioctlsocket(hSocket, FIONBIO, &nZero) ==
SOCKET_ERROR) {
769 int fFlags = fcntl(hSocket, F_GETFL, 0);
770 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR) {