12 #include <sys/fcntl.h>
15 #include <boost/algorithm/string/case_conv.hpp>
16 #include <boost/algorithm/string/predicate.hpp>
27 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
33 if (net ==
"tor")
return NET_TOR;
37 void SplitHostPort(std::string in,
int &portOut, std::string &hostOut) {
38 size_t colon = in.find_last_of(
':');
40 bool fHaveColon = colon != in.npos;
41 bool fBracketed = fHaveColon && (in[0]==
'[' && in[colon-1]==
']');
42 bool fMultiColon = fHaveColon && (in.find_last_of(
':',colon-1) != in.npos);
43 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
45 int n = strtol(in.c_str() + colon + 1, &endp, 10);
46 if (endp && *endp == 0 && n >= 0) {
47 in = in.substr(0, colon);
48 if (n > 0 && n < 0x10000)
52 if (in.size()>0 && in[0] ==
'[' && in[in.size()-1] ==
']')
53 hostOut = in.substr(1, in.size()-2);
58 bool static LookupIntern(
const char *pszName, std::vector<CNetAddr>& vIP,
unsigned int nMaxSolutions,
bool fAllowLookup)
70 struct addrinfo aiHint;
71 memset(&aiHint, 0,
sizeof(
struct addrinfo));
73 aiHint.ai_socktype = SOCK_STREAM;
74 aiHint.ai_protocol = IPPROTO_TCP;
76 aiHint.ai_family = AF_UNSPEC;
78 aiHint.ai_family = AF_INET;
81 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
83 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
85 struct addrinfo *aiRes = NULL;
86 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
90 struct addrinfo *aiTrav = aiRes;
91 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
93 if (aiTrav->ai_family == AF_INET)
95 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in));
96 vIP.push_back(
CNetAddr(((
struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
100 if (aiTrav->ai_family == AF_INET6)
102 assert(aiTrav->ai_addrlen >=
sizeof(sockaddr_in6));
103 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 printf(
"ERROR: Proxy returned error %d\n", pchRet[1]);
210 bool static Socks5(
string strDest,
int port,
SOCKET& hSocket)
212 printf(
"SOCKS5 connecting %s\n", strDest.c_str());
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;
291 return error(
"Error reading from proxy");
292 int nRecv = pchRet3[0];
293 ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
296 default:
closesocket(hSocket);
return error(
"Error: malformed proxy response");
301 return error(
"Error reading from proxy");
303 if (recv(hSocket, pchRet3, 2, 0) != 2)
306 return error(
"Error reading from proxy");
308 printf(
"SOCKS5 connected %s\n", strDest.c_str());
312 bool static ConnectSocketDirectly(
const CService &addrConnect,
SOCKET& hSocketRet,
int nTimeout)
317 struct sockaddr_storage sockaddr;
319 struct sockaddr sockaddr;
321 socklen_t len =
sizeof(sockaddr);
322 if (!addrConnect.
GetSockAddr((
struct sockaddr*)&sockaddr, &len)) {
323 printf(
"Cannot connect to %s: unsupported network\n", addrConnect.
ToString().c_str());
327 SOCKET hSocket = socket(((
struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
332 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (
void*)&set,
sizeof(
int));
336 u_long fNonblock = 1;
337 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) ==
SOCKET_ERROR)
339 int fFlags = fcntl(hSocket, F_GETFL, 0);
340 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
347 if (connect(hSocket, (
struct sockaddr*)&sockaddr, len) ==
SOCKET_ERROR)
352 struct timeval timeout;
353 timeout.tv_sec = nTimeout / 1000;
354 timeout.tv_usec = (nTimeout % 1000) * 1000;
358 FD_SET(hSocket, &fdset);
359 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
362 printf(
"connection timeout\n");
372 socklen_t nRetSize =
sizeof(nRet);
374 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (
char*)(&nRet), &nRetSize) ==
SOCKET_ERROR)
376 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) ==
SOCKET_ERROR)
385 printf(
"connect() failed after select(): %s\n",strerror(nRet));
407 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) ==
SOCKET_ERROR)
409 fFlags = fcntl(hSocket, F_GETFL, 0);
410 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) ==
SOCKET_ERROR)
417 hSocketRet = hSocket;
422 assert(net >= 0 && net <
NET_MAX);
423 if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
425 if (nSocksVersion != 0 && !addrProxy.
IsValid())
428 proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
433 assert(net >= 0 && net <
NET_MAX);
435 if (!proxyInfo[net].second)
437 proxyInfoOut = proxyInfo[net];
442 if (nSocksVersion != 0 && nSocksVersion != 5)
444 if (nSocksVersion != 0 && !addrProxy.
IsValid())
447 nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
453 if (!nameproxyInfo.second)
455 nameproxyInfoOut = nameproxyInfo;
461 return nameproxyInfo.second != 0;
466 for (
int i = 0; i <
NET_MAX; i++) {
467 if (proxyInfo[i].second && (addr == (
CNetAddr)proxyInfo[i].first))
479 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
484 if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
488 switch (proxy.second) {
490 if (!Socks4(addrDest, hSocket))
501 hSocketRet = hSocket;
508 int port = portDefault;
522 if (!nameproxy.second)
524 if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
527 switch(nameproxy.second) {
529 case 4:
return false;
531 if (!Socks5(strDest, port, hSocket))
536 hSocketRet = hSocket;
542 memset(
ip, 0,
sizeof(
ip));
547 memcpy(
ip, ipIn.
ip,
sizeof(
ip));
550 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
554 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) ==
".onion") {
555 std::vector<unsigned char> vchAddr =
DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
556 if (vchAddr.size() != 16-
sizeof(pchOnionCat))
558 memcpy(
ip, pchOnionCat,
sizeof(pchOnionCat));
559 for (
unsigned int i=0; i<16-
sizeof(pchOnionCat); i++)
560 ip[i +
sizeof(pchOnionCat)] = vchAddr[i];
573 memcpy(
ip, pchIPv4, 12);
574 memcpy(
ip+12, &ipv4Addr, 4);
580 memcpy(
ip, &ipv6Addr, 16);
587 std::vector<CNetAddr> vIP;
595 std::vector<CNetAddr> vIP;
596 if (
LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
607 return (memcmp(
ip, pchIPv4,
sizeof(pchIPv4)) == 0);
612 return (!IsIPv4() && !IsTor());
619 (GetByte(3) == 192 && GetByte(2) == 168) ||
620 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
625 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
630 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
635 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
640 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
641 return (memcmp(
ip, pchRFC6052,
sizeof(pchRFC6052)) == 0);
646 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
651 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
652 return (memcmp(
ip, pchRFC4862,
sizeof(pchRFC4862)) == 0);
657 return ((GetByte(15) & 0xFE) == 0xFC);
662 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
663 return (memcmp(
ip, pchRFC6145,
sizeof(pchRFC6145)) == 0);
668 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
673 return (memcmp(
ip, pchOnionCat,
sizeof(pchOnionCat)) == 0);
679 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
683 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
684 if (memcmp(
ip, pchLocal, 16) == 0)
692 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
693 || (GetByte(15) == 0xFF);
704 if (memcmp(
ip, pchIPv4+3,
sizeof(pchIPv4)-3) == 0)
708 unsigned char ipNone[16] = {};
709 if (memcmp(
ip, ipNone, 16) == 0)
720 if (memcmp(
ip+12, &ipNone, 4) == 0)
725 if (memcmp(
ip+12, &ipNone, 4) == 0)
734 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() ||
IsLocal());
757 struct sockaddr_storage sockaddr;
759 struct sockaddr sockaddr;
761 socklen_t socklen =
sizeof(sockaddr);
762 if (serv.
GetSockAddr((
struct sockaddr*)&sockaddr, &socklen)) {
763 char name[1025] =
"";
764 if (!getnameinfo((
const struct sockaddr*)&sockaddr, socklen, name,
sizeof(name), NULL, 0, NI_NUMERICHOST))
765 return std::string(name);
768 return strprintf(
"%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
770 return strprintf(
"%x:%x:%x:%x:%x:%x:%x:%x",
771 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
772 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
773 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
774 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
784 return (memcmp(a.
ip, b.
ip, 16) == 0);
789 return (memcmp(a.
ip, b.
ip, 16) != 0);
794 return (memcmp(a.
ip, b.
ip, 16) < 0);
801 memcpy(pipv4Addr,
ip+12, 4);
806 bool CNetAddr::GetIn6Addr(
struct in6_addr* pipv6Addr)
const
808 memcpy(pipv6Addr,
ip, 16);
817 std::vector<unsigned char> vchRet;
837 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
843 else if (IsRFC3964())
849 else if (IsRFC4380())
852 vchRet.push_back(GetByte(3) ^ 0xFF);
853 vchRet.push_back(GetByte(2) ^ 0xFF);
863 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
869 vchRet.push_back(nClass);
872 vchRet.push_back(GetByte(15 - nStartByte));
877 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
886 memcpy(&nRet, &hash,
sizeof(nRet));
892 printf(
"CNetAddr(%s)\n", ToString().c_str());
897 static const int NET_UNKNOWN =
NET_MAX + 0;
898 static const int NET_TEREDO =
NET_MAX + 1;
899 int static GetExtNetwork(
const CNetAddr *addr)
922 return REACH_UNREACHABLE;
924 int ourNet = GetExtNetwork(
this);
925 int theirNet = GetExtNetwork(paddrPartner);
926 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
931 default:
return REACH_DEFAULT;
936 default:
return REACH_DEFAULT;
937 case NET_TEREDO:
return REACH_TEREDO;
939 case NET_IPV6:
return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG;
943 default:
return REACH_DEFAULT;
945 case NET_TOR:
return REACH_PRIVATE;
949 default:
return REACH_DEFAULT;
950 case NET_TEREDO:
return REACH_TEREDO;
951 case NET_IPV6:
return REACH_IPV6_WEAK;
958 default:
return REACH_DEFAULT;
959 case NET_TEREDO:
return REACH_TEREDO;
960 case NET_IPV6:
return REACH_IPV6_WEAK;
962 case NET_TOR:
return REACH_PRIVATE;
993 assert(addr.sin_family == AF_INET);
999 assert(addr.sin6_family == AF_INET6);
1005 switch (paddr->sa_family) {
1007 *
this =
CService(*(
const struct sockaddr_in*)paddr);
1011 *
this =
CService(*(
const struct sockaddr_in6*)paddr);
1023 if (
Lookup(pszIpPort, ip, 0, fAllowLookup))
1031 if (
Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1039 if (
Lookup(strIpPort.c_str(),
ip, 0, fAllowLookup))
1047 if (
Lookup(strIpPort.c_str(),
ip, portDefault, fAllowLookup))
1074 if (*addrlen < (socklen_t)
sizeof(
struct sockaddr_in))
1076 *addrlen =
sizeof(
struct sockaddr_in);
1077 struct sockaddr_in *paddrin = (
struct sockaddr_in*)paddr;
1078 memset(paddrin, 0, *addrlen);
1081 paddrin->sin_family = AF_INET;
1082 paddrin->sin_port = htons(port);
1087 if (*addrlen < (socklen_t)
sizeof(
struct sockaddr_in6))
1089 *addrlen =
sizeof(
struct sockaddr_in6);
1090 struct sockaddr_in6 *paddrin6 = (
struct sockaddr_in6*)paddr;
1091 memset(paddrin6, 0, *addrlen);
1092 if (!GetIn6Addr(&paddrin6->sin6_addr))
1094 paddrin6->sin6_family = AF_INET6;
1095 paddrin6->sin6_port = htons(port);
1104 std::vector<unsigned char> vKey;
1106 memcpy(&vKey[0],
ip, 16);
1107 vKey[16] = port / 0x100;
1108 vKey[17] = port & 0x0FF;
bool error(const char *format,...)
#define strprintf(format,...)
unsigned short GetPort() const
void SetIP(const CNetAddr &ip)
bool operator<(const CNetAddr &a, const CNetAddr &b)
std::string ToStringIP() const
std::string ToStringIPPort() const
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)
unsigned long long uint64
#define WSAGetLastError()
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)
A combination of a network address (CNetAddr) and a (TCP) port.
bool IsProxy(const CNetAddr &addr)
string EncodeBase32(const unsigned char *pch, size_t len)
bool ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout)
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
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
std::pair< CService, int > proxyType
bool operator!=(const CNetAddr &a, const CNetAddr &b)
bool SetSpecial(const std::string &strName)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
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)
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