17 #include <boost/algorithm/string/case_conv.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
20 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
21 #define MSG_NOSIGNAL 0
33 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
39 if (net ==
"tor")
return NET_TOR;
43 void SplitHostPort(std::string in,
int &portOut, std::string &hostOut) {
44 size_t colon = in.find_last_of(
':');
46 bool fHaveColon = colon != in.npos;
47 bool fBracketed = fHaveColon && (in[0]==
'[' && in[colon-1]==
']');
48 bool fMultiColon = fHaveColon && (in.find_last_of(
':',colon-1) != in.npos);
49 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
51 int n = strtol(in.c_str() + colon + 1, &endp, 10);
52 if (endp && *endp == 0 && n >= 0) {
53 in = in.substr(0, colon);
54 if (n > 0 && n < 0x10000)
58 if (in.size()>0 && in[0] ==
'[' && in[in.size()-1] ==
']')
59 hostOut = in.substr(1, in.size()-2);
64 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
76 struct addrinfo aiHint;
77 memset(&aiHint, 0,
sizeof(
struct addrinfo));
79 aiHint.ai_socktype = SOCK_STREAM;
80 aiHint.ai_protocol = IPPROTO_TCP;
81 aiHint.ai_family = AF_UNSPEC;
83 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
85 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
87 struct addrinfo *aiRes = NULL;
88 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
92 struct addrinfo *aiTrav = aiRes;
93 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
95 if (aiTrav->ai_family == AF_INET)
97 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
98 vIP.push_back(
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
101 if (aiTrav->ai_family == AF_INET6)
103 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
104 vIP.push_back(
CNetAddr(((
struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
107 aiTrav = aiTrav->ai_next;
112 return (vIP.size() > 0);
115 bool LookupHost(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
117 std::string strHost(pszName);
120 if (boost::algorithm::starts_with(strHost,
"[") && boost::algorithm::ends_with(strHost,
"]"))
122 strHost = strHost.substr(1, strHost.size() - 2);
125 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
128 bool LookupHostNumeric(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions)
130 return LookupHost(pszName, vIP, nMaxSolutions,
false);
133 bool Lookup(
const char *pszName, std::vector<CService>& vAddr,
int portDefault,
bool fAllowLookup,
unsigned int nMaxSolutions)
137 int port = portDefault;
138 std::string hostname =
"";
141 std::vector<CNetAddr> vIP;
142 bool fRet =
LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
145 vAddr.resize(vIP.size());
146 for (
unsigned int i = 0; i < vIP.size(); i++)
151 bool Lookup(
const char *pszName,
CService& addr,
int portDefault,
bool fAllowLookup)
153 std::vector<CService> vService;
154 bool fRet =
Lookup(pszName, vService, portDefault, fAllowLookup, 1);
163 return Lookup(pszName, addr, portDefault,
false);
172 return error(
"Proxy destination is not IPv4");
174 char pszSocks4IP[] =
"\4\1\0\0\0\0\0\0user";
175 struct sockaddr_in addr;
176 socklen_t len =
sizeof(addr);
177 if (!addrDest.
GetSockAddr((
struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
180 return error(
"Cannot get proxy destination address");
182 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
183 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
184 char* pszSocks4 = pszSocks4IP;
185 int nSize =
sizeof(pszSocks4IP);
187 int ret = send(hSocket, pszSocks4, nSize,
MSG_NOSIGNAL);
191 return error(
"Error sending to proxy");
194 if (recv(hSocket, pchRet, 8, 0) != 8)
197 return error(
"Error reading proxy response");
199 if (pchRet[1] != 0x5a)
202 if (pchRet[1] != 0x5b)
203 LogPrintf(
"ERROR: Proxy returned error %d\n", pchRet[1]);
212 LogPrintf(
"SOCKS5 connecting %s\n", strDest);
213 if (strDest.size() > 255)
216 return error(
"Hostname too long");
218 char pszSocks5Init[] =
"\5\1\0";
219 ssize_t nSize =
sizeof(pszSocks5Init) - 1;
221 ssize_t ret = send(hSocket, pszSocks5Init, nSize,
MSG_NOSIGNAL);
225 return error(
"Error sending to proxy");
228 if (recv(hSocket, pchRet1, 2, 0) != 2)
231 return error(
"Error reading proxy response");
233 if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
236 return error(
"Proxy failed to initialize");
238 string strSocks5(
"\5\1");
239 strSocks5 +=
'\000'; strSocks5 +=
'\003';
240 strSocks5 +=
static_cast<char>(std::min((
int)strDest.size(), 255));
241 strSocks5 += strDest;
242 strSocks5 +=
static_cast<char>((port >> 8) & 0xFF);
243 strSocks5 +=
static_cast<char>((port >> 0) & 0xFF);
244 ret = send(hSocket, strSocks5.c_str(), strSocks5.size(),
MSG_NOSIGNAL);
245 if (ret != (ssize_t)strSocks5.size())
248 return error(
"Error sending to proxy");
251 if (recv(hSocket, pchRet2, 4, 0) != 4)
254 return error(
"Error reading proxy response");
256 if (pchRet2[0] != 0x05)
259 return error(
"Proxy failed to accept request");
261 if (pchRet2[1] != 0x00)
266 case 0x01:
return error(
"Proxy error: general failure");
267 case 0x02:
return error(
"Proxy error: connection not allowed");
268 case 0x03:
return error(
"Proxy error: network unreachable");
269 case 0x04:
return error(
"Proxy error: host unreachable");
270 case 0x05:
return error(
"Proxy error: connection refused");
271 case 0x06:
return error(
"Proxy error: TTL expired");
272 case 0x07:
return error(
"Proxy error: protocol error");
273 case 0x08:
return error(
"Proxy error: address type not supported");
274 default:
return error(
"Proxy error: unknown");
277 if (pchRet2[2] != 0x00)
280 return error(
"Error: malformed proxy response");
285 case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4;
break;
286 case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16;
break;
289 ret = recv(hSocket, pchRet3, 1, 0) != 1;
292 return error(
"Error reading from proxy");
294 int nRecv = pchRet3[0];
295 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
298 default:
closesocket(hSocket);
return error(
"Error: malformed proxy response");
303 return error(
"Error reading from proxy");
305 if (recv(hSocket, pchRet3, 2, 0) != 2)
308 return error(
"Error reading from proxy");
310 LogPrintf(
"SOCKS5 connected %s\n", strDest);
318 struct sockaddr_storage sockaddr;
319 socklen_t len =
sizeof(sockaddr);
320 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
321 LogPrintf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString());
325 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
330 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
334 u_long fNonblock = 1;
335 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) ==
SOCKET_ERROR)
337 int fFlags = fcntl(hSocket, F_GETFL, 0);
338 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
345 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
350 struct timeval timeout;
351 timeout.tv_sec = nTimeout / 1000;
352 timeout.tv_usec = (nTimeout % 1000) * 1000;
356 FD_SET(hSocket, &fdset);
357 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
370 socklen_t nRetSize =
sizeof(nRet);
372 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
374 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
405 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) ==
SOCKET_ERROR)
407 fFlags = fcntl(hSocket, F_GETFL, 0);
408 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR)
415 hSocketRet = hSocket;
420 assert(net >= 0 && net <
NET_MAX);
421 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
423 if (nSocksVersion != 0 && !addrProxy.
IsValid())
426 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
431 assert(net >= 0 && net <
NET_MAX);
440 if (nSocksVersion != 0 && nSocksVersion != 5)
442 if (nSocksVersion != 0 && !addrProxy.
IsValid())
464 for (
int i = 0; i <
NET_MAX; i++) {
486 switch (proxy.second) {
488 if (!
Socks4(addrDest, hSocket))
500 hSocketRet = hSocket;
507 int port = portDefault;
521 if (!nameproxy.second)
526 switch(nameproxy.second) {
532 if (!
Socks5(strDest, port, hSocket))
537 hSocketRet = hSocket;
543 memset(ip, 0,
sizeof(ip));
551 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
555 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) ==
".onion") {
556 std::vector<unsigned char> vchAddr =
DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
560 for (
unsigned int i=0; i<16-
sizeof(
pchOnionCat); i++)
575 memcpy(ip+12, &ipv4Addr, 4);
580 memcpy(ip, &ipv6Addr, 16);
586 std::vector<CNetAddr> vIP;
594 std::vector<CNetAddr> vIP;
595 if (
LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
611 return (!IsIPv4() && !IsTor());
618 (GetByte(3) == 192 && GetByte(2) == 168) ||
619 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
624 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
629 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
634 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
639 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
640 return (memcmp(ip, pchRFC6052,
sizeof(pchRFC6052)) == 0);
645 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
650 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
651 return (memcmp(ip, pchRFC4862,
sizeof(pchRFC4862)) == 0);
656 return ((GetByte(15) & 0xFE) == 0xFC);
661 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
662 return (memcmp(ip, pchRFC6145,
sizeof(pchRFC6145)) == 0);
667 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
678 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
682 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
683 if (memcmp(ip, pchLocal, 16) == 0)
691 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
692 || (GetByte(15) == 0xFF);
707 unsigned char ipNone[16] = {};
708 if (memcmp(ip, ipNone, 16) == 0)
718 uint32_t ipNone = INADDR_NONE;
719 if (memcmp(ip+12, &ipNone, 4) == 0)
724 if (memcmp(ip+12, &ipNone, 4) == 0)
733 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() ||
IsLocal());
755 struct sockaddr_storage sockaddr;
756 socklen_t socklen =
sizeof(sockaddr);
757 if (serv.
GetSockAddr((
struct sockaddr*)&sockaddr, &socklen)) {
758 char name[1025] =
"";
759 if (!getnameinfo((
const struct sockaddr*)&sockaddr, socklen, name,
sizeof(name), NULL, 0, NI_NUMERICHOST))
760 return std::string(name);
763 return strprintf(
"%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
765 return strprintf(
"%x:%x:%x:%x:%x:%x:%x:%x",
766 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
767 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
768 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
769 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
779 return (memcmp(a.
ip, b.
ip, 16) == 0);
784 return (memcmp(a.
ip, b.
ip, 16) != 0);
789 return (memcmp(a.
ip, b.
ip, 16) < 0);
796 memcpy(pipv4Addr, ip+12, 4);
802 memcpy(pipv6Addr, ip, 16);
810 std::vector<unsigned char> vchRet;
830 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
836 else if (IsRFC3964())
842 else if (IsRFC4380())
845 vchRet.push_back(GetByte(3) ^ 0xFF);
846 vchRet.push_back(GetByte(2) ^ 0xFF);
856 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
862 vchRet.push_back(nClass);
865 vchRet.push_back(GetByte(15 - nStartByte));
870 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
879 memcpy(&nRet, &hash,
sizeof(nRet));
915 return REACH_UNREACHABLE;
919 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
924 default:
return REACH_DEFAULT;
929 default:
return REACH_DEFAULT;
930 case NET_TEREDO:
return REACH_TEREDO;
932 case NET_IPV6:
return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG;
936 default:
return REACH_DEFAULT;
938 case NET_TOR:
return REACH_PRIVATE;
942 default:
return REACH_DEFAULT;
943 case NET_TEREDO:
return REACH_TEREDO;
944 case NET_IPV6:
return REACH_IPV6_WEAK;
951 default:
return REACH_DEFAULT;
952 case NET_TEREDO:
return REACH_TEREDO;
953 case NET_IPV6:
return REACH_IPV6_WEAK;
955 case NET_TOR:
return REACH_PRIVATE;
984 assert(addr.sin_family == AF_INET);
989 assert(addr.sin6_family == AF_INET6);
994 switch (paddr->sa_family) {
996 *
this =
CService(*(
const struct sockaddr_in*)paddr);
999 *
this =
CService(*(
const struct sockaddr_in6*)paddr);
1010 if (
Lookup(pszIpPort, ip, 0, fAllowLookup))
1018 if (
Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1026 if (
Lookup(strIpPort.c_str(),
ip, 0, fAllowLookup))
1034 if (
Lookup(strIpPort.c_str(),
ip, portDefault, fAllowLookup))
1061 if (*addrlen < (socklen_t)
sizeof(
struct sockaddr_in))
1063 *addrlen =
sizeof(
struct sockaddr_in);
1064 struct sockaddr_in *paddrin = (
struct sockaddr_in*)paddr;
1065 memset(paddrin, 0, *addrlen);
1068 paddrin->sin_family = AF_INET;
1069 paddrin->sin_port = htons(
port);
1073 if (*addrlen < (socklen_t)
sizeof(
struct sockaddr_in6))
1075 *addrlen =
sizeof(
struct sockaddr_in6);
1076 struct sockaddr_in6 *paddrin6 = (
struct sockaddr_in6*)paddr;
1077 memset(paddrin6, 0, *addrlen);
1080 paddrin6->sin6_family = AF_INET6;
1081 paddrin6->sin6_port = htons(
port);
1089 std::vector<unsigned char> vKey;
1092 vKey[16] =
port / 0x100;
1093 vKey[17] =
port & 0x0FF;
1131 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1132 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1133 buf,
sizeof(buf), NULL))
1139 return strprintf(
"Unknown error (%d)", err);
1146 const char *s = buf;
1150 #ifdef STRERROR_R_CHAR_P
1151 s = strerror_r(err, buf,
sizeof(buf));
1153 (void) strerror_r(err, buf,
sizeof(buf));
unsigned short GetPort() const
void SetIP(const CNetAddr &ip)
static bool ConnectSocketDirectly(const CService &addrConnect, SOCKET &hSocketRet, int nTimeout)
bool operator<(const CNetAddr &a, const CNetAddr &b)
std::string ToStringIP() const
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
std::string ToStringIPPort() const
static bool Socks5(string strDest, int port, SOCKET &hSocket)
void SetPort(unsigned short portIn)
bool LookupNumeric(const char *pszName, CService &addr, int portDefault)
bool ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, int portDefault, int nTimeout)
static const unsigned char pchIPv4[12]
#define WSAGetLastError()
static CCriticalSection cs_proxyInfos
unsigned int GetByte(int n) const
bool operator==(const CNetAddr &a, const CNetAddr &b)
int GetReachabilityFrom(const CNetAddr *paddrPartner=NULL) const
Calculates a metric for how reachable (*this) is from a given partner.
enum Network ParseNetwork(std::string net)
static bool LookupIntern(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
static int LogPrint(const char *category, const char *format)
A combination of a network address (CNetAddr) and a (TCP) port.
static bool error(const char *format)
bool IsProxy(const CNetAddr &addr)
string EncodeBase32(const unsigned char *pch, size_t len)
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout)
static int GetExtNetwork(const CNetAddr *addr)
bool SetNameProxy(CService addrProxy, int nSocksVersion)
std::string ToString() const
uint256 Hash(const T1 pbegin, const T1 pend)
bool GetInAddr(struct in_addr *pipv4Addr) const
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
std::vector< unsigned char > GetGroup() const
static const int NET_UNKNOWN
static proxyType nameproxyInfo
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
static proxyType proxyInfo[NET_MAX]
vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)
void * memcpy(void *a, const void *b, size_t c)
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
static const unsigned char pchOnionCat[]
std::pair< CService, int > proxyType
bool operator!=(const CNetAddr &a, const CNetAddr &b)
bool SetSpecial(const std::string &strName)
static bool Socks4(const CService &addrDest, SOCKET &hSocket)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
std::string ToString() const
std::string ToStringPort() const
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool SetSockAddr(const struct sockaddr *paddr)
bool GetNameProxy(proxyType &nameproxyInfoOut)
static const int NET_TEREDO
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
bool LookupHostNumeric(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions)
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion)
bool IsLocal(const CService &addr)
check whether a given address is potentially local
std::vector< unsigned char > GetKey() const
enum Network GetNetwork() const