aboutsummaryrefslogtreecommitdiff
path: root/src/netbase.cpp
diff options
context:
space:
mode:
authorRoy Badami <roy@gnomon.org.uk>2014-07-07 22:06:21 +0100
committerRoy Badami <roy@gnomon.org.uk>2014-07-07 22:06:21 +0100
commit96df327834af3b55918adfac9b3f65adfc960b3a (patch)
tree8bd199df46ea6f39f7094c0e7db2185b4d3f5d6d /src/netbase.cpp
parent2e4fee2ac4824570c1340a8f8fe2aed4580de879 (diff)
parent1fedd65fcf9ac04b70f0fa8cf6caa9629857d586 (diff)
Merge remote-tracking branch 'upstream/master'
Conflicts: src/qt/overviewpage.cpp src/qt/transactiondesc.cpp
Diffstat (limited to 'src/netbase.cpp')
-rw-r--r--src/netbase.cpp359
1 files changed, 247 insertions, 112 deletions
diff --git a/src/netbase.cpp b/src/netbase.cpp
index ec275f738c..175406322a 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -3,6 +3,14 @@
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#ifdef HAVE_CONFIG_H
+#include "bitcoin-config.h"
+#endif
+
+#ifdef HAVE_GETADDRINFO_A
+#include <netdb.h>
+#endif
+
#include "netbase.h"
#include "hash.h"
@@ -11,6 +19,9 @@
#include "util.h"
#ifndef WIN32
+#if HAVE_INET_PTON
+#include <arpa/inet.h>
+#endif
#include <fcntl.h>
#endif
@@ -25,7 +36,7 @@ using namespace std;
// Settings
static proxyType proxyInfo[NET_MAX];
-static proxyType nameproxyInfo;
+static CService nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = 5000;
bool fNameLookup = false;
@@ -47,12 +58,10 @@ void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
- char *endp = NULL;
- int n = strtol(in.c_str() + colon + 1, &endp, 10);
- if (endp && *endp == 0 && n >= 0) {
+ int32_t n;
+ if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
- if (n > 0 && n < 0x10000)
- portOut = n;
+ portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
@@ -73,9 +82,30 @@ bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsign
}
}
+#ifdef HAVE_GETADDRINFO_A
+ struct in_addr ipv4_addr;
+#ifdef HAVE_INET_PTON
+ if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
+ vIP.push_back(CNetAddr(ipv4_addr));
+ return true;
+ }
+
+ struct in6_addr ipv6_addr;
+ if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
+ vIP.push_back(CNetAddr(ipv6_addr));
+ return true;
+ }
+#else
+ ipv4_addr.s_addr = inet_addr(pszName);
+ if (ipv4_addr.s_addr != INADDR_NONE) {
+ vIP.push_back(CNetAddr(ipv4_addr));
+ return true;
+ }
+#endif
+#endif
+
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
-
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
aiHint.ai_family = AF_UNSPEC;
@@ -84,8 +114,33 @@ bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsign
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
+
struct addrinfo *aiRes = NULL;
+#ifdef HAVE_GETADDRINFO_A
+ struct gaicb gcb, *query = &gcb;
+ memset(query, 0, sizeof(struct gaicb));
+ gcb.ar_name = pszName;
+ gcb.ar_request = &aiHint;
+ int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
+ if (nErr)
+ return false;
+
+ do {
+ // Should set the timeout limit to a resonable value to avoid
+ // generating unnecessary checking call during the polling loop,
+ // while it can still response to stop request quick enough.
+ // 2 seconds looks fine in our situation.
+ struct timespec ts = { 2, 0 };
+ gai_suspend(&query, 1, &ts);
+ boost::this_thread::interruption_point();
+
+ nErr = gai_error(query);
+ if (0 == nErr)
+ aiRes = query->ar_result;
+ } while (nErr == EAI_INPROGRESS);
+#else
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
+#endif
if (nErr)
return false;
@@ -125,11 +180,6 @@ bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nM
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
-bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
-{
- return LookupHost(pszName, vIP, nMaxSolutions, false);
-}
-
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
@@ -163,50 +213,6 @@ bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
return Lookup(pszName, addr, portDefault, false);
}
-bool static Socks4(const CService &addrDest, SOCKET& hSocket)
-{
- LogPrintf("SOCKS4 connecting %s\n", addrDest.ToString());
- if (!addrDest.IsIPv4())
- {
- closesocket(hSocket);
- return error("Proxy destination is not IPv4");
- }
- char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
- struct sockaddr_in addr;
- socklen_t len = sizeof(addr);
- if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
- {
- closesocket(hSocket);
- return error("Cannot get proxy destination address");
- }
- memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
- memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
- char* pszSocks4 = pszSocks4IP;
- int nSize = sizeof(pszSocks4IP);
-
- int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
- if (ret != nSize)
- {
- closesocket(hSocket);
- return error("Error sending to proxy");
- }
- char pchRet[8];
- if (recv(hSocket, pchRet, 8, 0) != 8)
- {
- closesocket(hSocket);
- return error("Error reading proxy response");
- }
- if (pchRet[1] != 0x5a)
- {
- closesocket(hSocket);
- if (pchRet[1] != 0x5b)
- LogPrintf("ERROR: Proxy returned error %d\n", pchRet[1]);
- return false;
- }
- LogPrintf("SOCKS4 connected %s\n", addrDest.ToString());
- return true;
-}
-
bool static Socks5(string strDest, int port, SOCKET& hSocket)
{
LogPrintf("SOCKS5 connecting %s\n", strDest);
@@ -344,8 +350,9 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
+ int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
- if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
+ if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
@@ -363,7 +370,7 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
}
if (nRet == SOCKET_ERROR)
{
- LogPrintf("select() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
+ LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
closesocket(hSocket);
return false;
}
@@ -374,13 +381,13 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
- LogPrintf("getsockopt() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
+ LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
closesocket(hSocket);
return false;
}
if (nRet != 0)
{
- LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), strerror(nRet));
+ LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
closesocket(hSocket);
return false;
}
@@ -391,7 +398,7 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
else
#endif
{
- LogPrintf("connect() to %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
+ LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
closesocket(hSocket);
return false;
}
@@ -416,53 +423,49 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
return true;
}
-bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
+bool SetProxy(enum Network net, CService addrProxy) {
assert(net >= 0 && net < NET_MAX);
- if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
- return false;
- if (nSocksVersion != 0 && !addrProxy.IsValid())
+ if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
- proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
+ proxyInfo[net] = addrProxy;
return true;
}
bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
- if (!proxyInfo[net].second)
+ if (!proxyInfo[net].IsValid())
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
-bool SetNameProxy(CService addrProxy, int nSocksVersion) {
- if (nSocksVersion != 0 && nSocksVersion != 5)
- return false;
- if (nSocksVersion != 0 && !addrProxy.IsValid())
+bool SetNameProxy(CService addrProxy) {
+ if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
- nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
+ nameProxy = addrProxy;
return true;
}
-bool GetNameProxy(proxyType &nameproxyInfoOut) {
+bool GetNameProxy(CService &nameProxyOut) {
LOCK(cs_proxyInfos);
- if (!nameproxyInfo.second)
+ if(!nameProxy.IsValid())
return false;
- nameproxyInfoOut = nameproxyInfo;
+ nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy() {
LOCK(cs_proxyInfos);
- return nameproxyInfo.second != 0;
+ return nameProxy.IsValid();
}
bool IsProxy(const CNetAddr &addr) {
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
- if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
+ if (addr == (CNetAddr)proxyInfo[i])
return true;
}
return false;
@@ -471,31 +474,18 @@ bool IsProxy(const CNetAddr &addr) {
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
proxyType proxy;
-
- // no proxy needed
+ // no proxy needed (none set for target network)
if (!GetProxy(addrDest.GetNetwork(), proxy))
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
- if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
+ if (!ConnectSocketDirectly(proxy, hSocket, nTimeout))
return false;
-
// do socks negotiation
- switch (proxy.second) {
- case 4:
- if (!Socks4(addrDest, hSocket))
- return false;
- break;
- case 5:
- if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
- return false;
- break;
- default:
- closesocket(hSocket);
+ if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
return false;
- }
hSocketRet = hSocket;
return true;
@@ -509,30 +499,25 @@ bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest
SOCKET hSocket = INVALID_SOCKET;
- proxyType nameproxy;
- GetNameProxy(nameproxy);
+ CService nameProxy;
+ GetNameProxy(nameProxy);
- CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
+ CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
+
addr = CService("0.0.0.0:0");
- if (!nameproxy.second)
+
+ if (!HaveNameProxy())
return false;
- if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
+ // first connect to name proxy server
+ if (!ConnectSocketDirectly(nameProxy, hSocket, nTimeout))
+ return false;
+ // do socks negotiation
+ if (!Socks5(strDest, (unsigned short)port, hSocket))
return false;
-
- switch(nameproxy.second) {
- default:
- case 4:
- closesocket(hSocket);
- return false;
- case 5:
- if (!Socks5(strDest, port, hSocket))
- return false;
- break;
- }
hSocketRet = hSocket;
return true;
@@ -548,6 +533,22 @@ void CNetAddr::SetIP(const CNetAddr& ipIn)
memcpy(ip, ipIn.ip, sizeof(ip));
}
+void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
+{
+ switch(network)
+ {
+ case NET_IPV4:
+ memcpy(ip, pchIPv4, 12);
+ memcpy(ip+12, ip_in, 4);
+ break;
+ case NET_IPV6:
+ memcpy(ip, ip_in, 16);
+ break;
+ default:
+ assert(!"invalid network");
+ }
+}
+
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
bool CNetAddr::SetSpecial(const std::string &strName)
@@ -571,13 +572,12 @@ CNetAddr::CNetAddr()
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
- memcpy(ip, pchIPv4, 12);
- memcpy(ip+12, &ipv4Addr, 4);
+ SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
}
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
- memcpy(ip, &ipv6Addr, 16);
+ SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
}
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
@@ -1122,3 +1122,138 @@ void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
+
+CSubNet::CSubNet():
+ valid(false)
+{
+ memset(netmask, 0, sizeof(netmask));
+}
+
+CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
+{
+ size_t slash = strSubnet.find_last_of('/');
+ std::vector<CNetAddr> vIP;
+
+ valid = true;
+ // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
+ memset(netmask, 255, sizeof(netmask));
+
+ std::string strAddress = strSubnet.substr(0, slash);
+ if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
+ {
+ network = vIP[0];
+ if (slash != strSubnet.npos)
+ {
+ std::string strNetmask = strSubnet.substr(slash + 1);
+ int32_t n;
+ // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
+ int noffset = network.IsIPv4() ? (12 * 8) : 0;
+ if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
+ {
+ if(n >= 0 && n <= (128 - noffset)) // Only valid if in range of bits of address
+ {
+ n += noffset;
+ // Clear bits [n..127]
+ for (; n < 128; ++n)
+ netmask[n>>3] &= ~(1<<(n&7));
+ }
+ else
+ {
+ valid = false;
+ }
+ }
+ else // If not a valid number, try full netmask syntax
+ {
+ if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
+ {
+ // Remember: GetByte returns bytes in reversed order
+ // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
+ // we don't want pchIPv4 to be part of the mask.
+ int asize = network.IsIPv4() ? 4 : 16;
+ for(int x=0; x<asize; ++x)
+ netmask[15-x] = vIP[0].GetByte(x);
+ }
+ else
+ {
+ valid = false;
+ }
+ }
+ }
+ }
+ else
+ {
+ valid = false;
+ }
+}
+
+bool CSubNet::Match(const CNetAddr &addr) const
+{
+ if (!valid || !addr.IsValid())
+ return false;
+ for(int x=0; x<16; ++x)
+ if ((addr.GetByte(x) & netmask[15-x]) != network.GetByte(x))
+ return false;
+ return true;
+}
+
+std::string CSubNet::ToString() const
+{
+ std::string strNetmask;
+ if (network.IsIPv4())
+ strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
+ else
+ strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
+ netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
+ netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
+ netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
+ netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
+ return network.ToString() + "/" + strNetmask;
+}
+
+bool CSubNet::IsValid() const
+{
+ return valid;
+}
+
+bool operator==(const CSubNet& a, const CSubNet& b)
+{
+ return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
+}
+
+bool operator!=(const CSubNet& a, const CSubNet& b)
+{
+ return !(a==b);
+}
+
+#ifdef WIN32
+std::string NetworkErrorString(int err)
+{
+ char buf[256];
+ buf[0] = 0;
+ if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
+ NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ buf, sizeof(buf), NULL))
+ {
+ return strprintf("%s (%d)", buf, err);
+ }
+ else
+ {
+ return strprintf("Unknown error (%d)", err);
+ }
+}
+#else
+std::string NetworkErrorString(int err)
+{
+ char buf[256];
+ const char *s = buf;
+ buf[0] = 0;
+ /* Too bad there are two incompatible implementations of the
+ * thread-safe strerror. */
+#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
+ s = strerror_r(err, buf, sizeof(buf));
+#else /* POSIX variant always returns message in buffer */
+ (void) strerror_r(err, buf, sizeof(buf));
+#endif
+ return strprintf("%s (%d)", s, err);
+}
+#endif