zcashd/src/netbase.cpp

1470 lines
43 KiB
C++
Raw Normal View History

// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2017-2023 The Zcash developers
2014-12-12 20:09:33 -08:00
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php .
#ifdef HAVE_CONFIG_H
#include "config/bitcoin-config.h"
#endif
#include "netbase.h"
2012-12-18 11:56:21 -08:00
#include "hash.h"
#include "sync.h"
#include "uint256.h"
#include "random.h"
scripted-diff: Move util files to separate directory. -BEGIN VERIFY SCRIPT- mkdir -p src/util git mv src/util.h src/util/system.h git mv src/util.cpp src/util/system.cpp git mv src/utilmoneystr.h src/util/moneystr.h git mv src/utilmoneystr.cpp src/util/moneystr.cpp git mv src/utilstrencodings.h src/util/strencodings.h git mv src/utilstrencodings.cpp src/util/strencodings.cpp git mv src/utiltime.h src/util/time.h git mv src/utiltime.cpp src/util/time.cpp sed -i -e 's/"util\.h"/"util\/system\.h"/g' $(git ls-files 'src/*.h' 'src/*.cpp') git checkout HEAD -- src/secp256k1 # exclude secp256k1, which has its own "util.h" sed -i -e 's/"utilmoneystr\.h"/"util\/moneystr\.h"/g' $(git ls-files 'src/*.h' 'src/*.cpp') sed -i -e 's/"utilstrencodings\.h"/"util\/strencodings\.h"/g' $(git ls-files 'src/*.h' 'src/*.cpp') sed -i -e 's/<utilstrencodings\.h>/<util\/strencodings\.h>/g' $(git ls-files 'src/*.h' 'src/*.cpp') sed -i -e 's/"utiltime\.h"/"util\/time\.h"/g' $(git ls-files 'src/*.h' 'src/*.cpp') sed -i -e 's/BITCOIN_UTIL_H/BITCOIN_UTIL_SYSTEM_H/g' src/util/system.h sed -i -e 's/BITCOIN_UTILMONEYSTR_H/BITCOIN_UTIL_MONEYSTR_H/g' src/util/moneystr.h sed -i -e 's/BITCOIN_UTILSTRENCODINGS_H/BITCOIN_UTIL_STRENCODINGS_H/g' src/util/strencodings.h sed -i -e 's/BITCOIN_UTILTIME_H/BITCOIN_UTIL_TIME_H/g' src/util/time.h sed -i -e 's/ util\.\(h\|cpp\)/ util\/system\.\1/g' src/Makefile.am sed -i -e 's/utilmoneystr\.\(h\|cpp\)/util\/moneystr\.\1/g' src/Makefile.am sed -i -e 's/utilstrencodings\.\(h\|cpp\)/util\/strencodings\.\1/g' src/Makefile.am sed -i -e 's/utiltime\.\(h\|cpp\)/util\/time\.\1/g' src/Makefile.am sed -i -e 's/src\/util\.cpp/src\/util\/system\.cpp/g' test/lint/lint-locale-dependence.sh sed -i -e 's/src\/utilmoneystr\.cpp/src\/util\/moneystr\.cpp/g' test/lint/lint-locale-dependence.sh sed -i -e 's/src\/utilstrencodings\.\(h\|cpp\)/src\/util\/strencodings\.\1/g' test/lint/lint-locale-dependence.sh -END VERIFY SCRIPT-
2018-10-22 15:51:11 -07:00
#include "util/system.h"
#include "util/strencodings.h"
#ifdef HAVE_GETADDRINFO_A
#include <netdb.h>
#endif
#ifndef WIN32
#if HAVE_INET_PTON
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/thread.hpp>
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Settings
2012-05-24 10:02:21 -07:00
static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = DEFAULT_NAME_LOOKUP;
static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
enum Network ParseNetwork(std::string net) {
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor" || net == "onion") return NET_TOR;
return NET_UNROUTABLE;
}
std::string GetNetworkName(enum Network net) {
switch(net)
{
case NET_IPV4: return "ipv4";
case NET_IPV6: return "ipv6";
case NET_TOR: return "onion";
default: return "";
}
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
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)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
#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;
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
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 {
Squashed commit of the following: commit 5e7222e4bc0401ef8c6d8049b12a62d4854ac85c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:20:51 2018 +0200 Cleanup commit 2e1bc7a7cd6c72e7c3d2ff74cb30f7a56515006c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:19:53 2018 +0200 Cleanup commit edd7fa87fb2c839c17457ff004d258a049df832f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:18:57 2018 +0200 Cleanup commit ee34e1433806655a7123f0617802aa4771507dff Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:18:10 2018 +0200 Cleanup commit 20779e4021b8ab95a87289d2741ad2f0fbc7fb39 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Thu Mar 1 21:16:52 2018 +0200 Cleanup commit 084e1aa563807f5625ad3aaff376b598e139f2a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:42:49 2018 +0200 Fix typo commit c61a7c2319d3b9b96d1b5ad52ecf9d4f2fd92658 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:37:43 2018 +0200 Cleanup commit e435c0229b0cbe3f4a77f43b01ca87ed0552d405 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 18:17:58 2018 +0200 Fix typos commit e05bff3fea8915e95a473fe3266b2b1f727deca0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:59:32 2018 +0200 Fix typo commit 8c55c7840232cef7fa4389a12f6f220e86f5f581 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:46:33 2018 +0200 Fix typos commit a1edfcc5cc29d815ba7e8c4baaf14c23ef93af64 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:39:41 2018 +0200 Fix typos commit 2ce2c4d180e936ccc5c10745a6430fda5de38a9b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:14:10 2018 +0200 Fix typo commit 5bdc6cd5bc9cff93aa48fbdeda36d4d9774bfa18 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 17:12:14 2018 +0200 Fix typo commit d08749f549575efc6f44a7f80850bc439c12ad5c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:54:06 2018 +0200 Revert one change commit a734bb1191c692f09f58bcc8e85160ce7c839905 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:52:45 2018 +0200 Fix typo commit 95fbc8d94bbefc0db989c83d0f053111bfed45e7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:51:33 2018 +0200 Fix typos commit d17d540a83d035cf9a200f9a8b19f0fab6084728 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:49:36 2018 +0200 Fix typo commit c4bf4402210bcb926ccfb3928afeb3a8a7490b42 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:48:09 2018 +0200 Fix typo commit 25e7990848a1d723702e2d041c04bc68a6c1275f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:47:01 2018 +0200 Fix typo commit d72ffb5b0253e0d7b992ffe13c40695421378dc3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:45:20 2018 +0200 Fix typo commit 705e6f271192a575cc99d794545b0efe75d964c4 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:41:19 2018 +0200 Revert one change commit 4fd26cd29e21c42b027e37da2616761ebc399d16 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:39:41 2018 +0200 Revert commit commit 8a5cc627b1048368fe8807973d1f542bab2e045f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:28:56 2018 +0200 Fix typo commit 0a24baa7258c0ae0f244d82af8d0831b148ab012 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 16:15:45 2018 +0200 Fix typo commit 38f93ecd90171fb881243f0de55b3452daccff20 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:56:49 2018 +0200 Fix typos commit 15446fd62400c36c2a51f7e6f13725cc8adfd924 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:48:00 2018 +0200 Fix typos commit 76533b41986bbc5826070a1e644215a74757c1db Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 15:04:38 2018 +0200 Fix typo commit aea330c2b0bf76975ec69142a732288cc8b192bd Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:46:29 2018 +0200 Fix typo commit 8b1b1d0be1dc44f36c22c54d1a3d56d84d456b92 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:40:23 2018 +0200 Fix typo commit 46ea76785a26cf20a664ed211c8f3fb9a283e127 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:14:17 2018 +0200 Fix typo commit e0d7c5748545dd0975507ad603623072fcc6bdea Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 14:08:24 2018 +0200 Fix typo commit 604d5a244323b17ba596b12d245407e1cf63a375 Merge: 6c081ca 1c65b2b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:03:23 2018 +0200 Merge pull request #36 from rex4539/patch-36 Fix typo commit 6c081caf28b7cef9e62ed523284dff90e4add16d Merge: 899e5d2 88fa2d9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:02:49 2018 +0200 Merge pull request #35 from rex4539/patch-35 Fix typo commit 899e5d2c343ac7ea5069b8548e5df86c8e963e21 Merge: 6380c7f 40e73e2 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:02:16 2018 +0200 Merge pull request #34 from rex4539/patch-34 Fix typo commit 6380c7f740246474c69d8145bde61688551efe83 Merge: f592274 4567667 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:01:47 2018 +0200 Merge pull request #33 from rex4539/patch-33 Fix typos commit f592274a713162da0083bd6d22fb47cb1afcdba9 Merge: d86ef7e 4aeaa3a Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:01:14 2018 +0200 Merge pull request #32 from rex4539/patch-32 Fix typo commit d86ef7e5e4f7e9c2014358ec5b647d1815eb304d Merge: fe0b432 5cdd1b2 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:00:41 2018 +0200 Merge pull request #31 from rex4539/patch-31 Fix typo commit fe0b432ee125ae0b876af2c26139dfc979005a3b Merge: 6fd6d0d 70130d0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 09:00:12 2018 +0200 Merge pull request #30 from rex4539/patch-30 Fix typos commit 6fd6d0dcf3714118a623c0d8d84aabb4578410a8 Merge: 389660f 3377426 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:59:42 2018 +0200 Merge pull request #29 from rex4539/patch-29 Fix typo commit 389660f856cb60ff475a8757aad3873b99213cc0 Merge: a0b85ce 40643eb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:59:15 2018 +0200 Merge pull request #28 from rex4539/patch-28 Fix typo commit a0b85ce3b4d2e6596da0727e05c1fe15c289b1e7 Merge: 6f9a1c7 23ead80 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:58:42 2018 +0200 Merge pull request #27 from rex4539/patch-27 Fix typo commit 6f9a1c71a680bb3ed1c249dd42bf0a54663d0af3 Merge: b880547 3612eab Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:58:06 2018 +0200 Merge pull request #26 from rex4539/patch-26 Patch 26 commit b880547415afeae36bd19867388e60a3040a15ca Merge: a3b7da2 5c3177f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:57:24 2018 +0200 Merge pull request #25 from rex4539/patch-25 Fix typo commit a3b7da2c6d6691f38751292e1aea63498a325788 Merge: edd8586 60026ef Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:56:52 2018 +0200 Merge pull request #24 from rex4539/patch-24 Fix typo commit edd8586fdf8c112f4c513804610c237d7e2e80ef Merge: 0c28eb7 f979c00 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:56:12 2018 +0200 Merge pull request #23 from rex4539/patch-23 Fix typo commit 0c28eb7717821b1d68016f40911d07f2a7231b4f Merge: 775beb6 c900722 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:55:42 2018 +0200 Merge pull request #22 from rex4539/patch-22 Fix typo commit 775beb625beb1fc5f72388c076b295de4b8ff039 Merge: a0cf889 1027543 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:55:16 2018 +0200 Merge pull request #21 from rex4539/patch-21 Fix typo commit a0cf88971e756c37c406bab3066c11d6fc7f6d74 Merge: 4504b48 f3fa89b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:54:44 2018 +0200 Merge pull request #20 from rex4539/patch-20 Fix typo commit 4504b4824b3438e931ca8d24a56b1887657e87cd Merge: dd0bcbf 2699eca Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:54:20 2018 +0200 Merge pull request #19 from rex4539/patch-19 Fix typo commit dd0bcbfc89293e9760156d5534f3a558451e1f29 Merge: abfb65a f02ef2e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:53:46 2018 +0200 Merge pull request #18 from rex4539/patch-18 Fix typos commit abfb65afaed49c34b9875df79f6fe6eb2b7bf769 Merge: 68b46b7 6485c90 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:53:08 2018 +0200 Merge pull request #17 from rex4539/patch-17 Fix typo commit 68b46b75d2e5b7ae97e83fc5541c46b4907a7899 Merge: a131e84 fcc0828 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:52:39 2018 +0200 Merge pull request #16 from rex4539/patch-16 Fix typo commit a131e844652e58aff78fa8952e7547a9ba82b8a1 Merge: 8487c0e 8a688ff Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:54 2018 +0200 Merge pull request #15 from rex4539/patch-15 Fix typo commit 8487c0e39092b74e977c7a60f4a07a27606756a8 Merge: bcc4cb4 bb60b83 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:28 2018 +0200 Merge pull request #14 from rex4539/patch-14 Fix typos commit bcc4cb46130e789faa9adae9b159ca818f67ec52 Merge: 23e66e9 53539bb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:51:00 2018 +0200 Merge pull request #13 from rex4539/patch-13 Fix typos commit 23e66e956bff2d6935c7a4dd570d457294018a77 Merge: 56956cf 0808445 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:50:27 2018 +0200 Merge pull request #12 from rex4539/patch-12 Fix typo commit 56956cf23ba1208aa39cb3ab1ef60375c6630263 Merge: 77007d4 7a4f064 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:49:59 2018 +0200 Merge pull request #11 from rex4539/patch-11 Fix typo commit 77007d49fa1d8cb80aef02bea1dd15e522a47c90 Merge: e78ad0c 48c33fb Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:49:16 2018 +0200 Merge pull request #10 from rex4539/patch-10 Fix typo commit e78ad0cf0d91955a848f5e953a042eabdcdac198 Merge: 38a3e08 809f01c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:48:33 2018 +0200 Merge pull request #9 from rex4539/patch-9 Fix typo commit 38a3e08699fe4c4ec715b1783dba18bff6b829fb Merge: eee3c28 fec279c Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:48:05 2018 +0200 Merge pull request #8 from rex4539/patch-8 Fix typo commit eee3c286eb84f994310142a9e7fdbd36a671e593 Merge: 702635b cf81b4e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:47:33 2018 +0200 Merge pull request #7 from rex4539/patch-7 Fix typo commit 702635bb34abb2f83ded27ae95deefd5b6e7df93 Merge: d7497ea 3bbcc3d Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:47:01 2018 +0200 Merge pull request #6 from rex4539/patch-6 Fix typo commit d7497ea070e03380cf1d4f533b7dc4b881f724f8 Merge: bfcc1e8 f639727 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:45:33 2018 +0200 Merge pull request #5 from rex4539/patch-5 Fix typos commit bfcc1e8ae2094ca4e9837f623999705f538aff04 Merge: f4440ec 55262fe Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:45:05 2018 +0200 Merge pull request #4 from rex4539/patch-4 Remove space for word "backup" commit f4440ecd4a7367e6bc4a5f75bea112290017ed2b Merge: f8b487f 61d5279 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:44:31 2018 +0200 Merge pull request #3 from rex4539/patch-3 Fix typos in zmq.md commit f8b487f5699990fabc7fc383d02bc728db3cb9aa Merge: 60104a7 f2ce50f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:42:51 2018 +0200 Merge pull request #2 from rex4539/patch-2 Fix typo in security-warnings.md commit 60104a7034f55284afb814e81a1430a8b2b0d8d1 Merge: be262f0 af7dfe0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 08:41:48 2018 +0200 Merge pull request #1 from rex4539/patch-1 Fix typos commit 1c65b2bd0c49f7f392d0e3a2db14ce1366a87171 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:35:26 2018 +0200 Fix typo commit 88fa2d966a3b462ed34a9a4659fc390711cc0276 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:21:00 2018 +0200 Fix typo commit 40e73e258671f21d2b2205509e9cae1f50294752 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 07:14:21 2018 +0200 Fix typo commit 4567667fcc8b4197dfd51da34fe82b0f2fb78127 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 06:44:40 2018 +0200 Fix typos commit 4aeaa3a3d6335302c53c0f5f4ef81de05e266479 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:55:25 2018 +0200 Fix typo commit 5cdd1b29b4c90492aa15fed7940984e1d675052f Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:36:46 2018 +0200 Fix typo commit 70130d05f1646c8b9fb1f33c4efbe2a5fcf7138b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:28:21 2018 +0200 Fix typos commit 33774261b1c63e5640aa1dd251edb67892ed7a5b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 05:00:56 2018 +0200 Fix typo commit 40643ebfcd85ee257a4576e85d2fb6c73dad17b5 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:51:57 2018 +0200 Fix typo commit 23ead80e05116ebfeaac0a00d5bd4a158fbeb54e Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:29:53 2018 +0200 Fix typo commit 3612eaba2dcf273e94cac9ad889723776ce55108 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:19:36 2018 +0200 Fix typos commit 5c3177f5d191d1f4e4d9f78ae4b75381010f7768 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:13:03 2018 +0200 Fix typo commit 60026efe27a39300e428879ad8dba94f19934870 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:08:09 2018 +0200 Fix typo commit f979c0074efd66804f229c8b3cc6e812d7f26406 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 04:01:44 2018 +0200 Fix typo commit c9007220a8a727c1cfe3b25b453c178eacd431f3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:52:33 2018 +0200 Fix typo commit 1027543bd30701c4b09aa66226281a10563db910 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:36:19 2018 +0200 Fix typo commit f3fa89bcd30e0cb45ff4391e78d02452c9227be0 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:34:37 2018 +0200 Fix typo commit 2699eca938f1e413a29d4408a271aaafd27969cc Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:30:29 2018 +0200 Fix typo commit f02ef2e495fe43142d305f5c4f40dcfa3d2cb423 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:22:36 2018 +0200 Fix typos commit 6485c908433bb91fd70d7e18cf3611c9a96115a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:10:06 2018 +0200 Fix typo commit fcc082850564b14b86b1932dfc5a099816c72ef1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:06:26 2018 +0200 Fix typo commit 8a688ff7405d67bd4c77b0aa0ebdd4b4a8a9a6a7 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 03:02:50 2018 +0200 Fix typo commit bb60b83853ed0a82ca47dd58d55f1849ddcf23ab Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 02:59:25 2018 +0200 Fix typos commit 53539bb720c7676b9d37e25dde3423db3aa7bfa1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 02:50:55 2018 +0200 Fix typos commit 080844581d6488ab797ac188acae9c4b2e1d0c59 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 01:05:54 2018 +0200 Fix typo commit 7a4f0649ac5e71f39f0bef7f2e1fcb6fafad0291 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:16:31 2018 +0200 Fix typo commit 48c33fb3f9ab1ad287987d147ee4bbe186f7ade1 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:07:42 2018 +0200 Fix typo commit 809f01ca4f785a7b5bc9cc2c388e0ae814ecaa95 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Tue Feb 27 00:02:34 2018 +0200 Fix typo commit fec279cac89aa917be929447c81177811728361a Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:55:27 2018 +0200 Fix typo commit cf81b4e12399570545372d4c9daceca8e70142d5 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:48:43 2018 +0200 Fix typo commit 3bbcc3d9986caf8df99bec5d8a18d0f0c8990e06 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:28:52 2018 +0200 Fix typo commit f639727525dbd23f5f2d0f89e7be13d868e984c3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 23:13:12 2018 +0200 Fix typos commit 55262fe9c5e1e127c6b817a0c2ab3f9db3ac35b9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:46:52 2018 +0200 Remove space for word "backup" commit 61d52797d4d26a90dcc15e2bcd6f19a5f36faac3 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:23:31 2018 +0200 Fix typos in zmq.md commit f2ce50f10e67b4265e559a432681bc44828ae59b Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 22:12:58 2018 +0200 Fix typo in security-warnings.md commit af7dfe046c12109e44ddc18dff07ede8755cf4f9 Author: Dimitris Apostolou <dimitris.apostolou@icloud.com> Date: Mon Feb 26 21:59:24 2018 +0200 Fix typos Signed-off-by: Daira Hopwood <daira@jacaranda.org>
2018-03-02 03:45:05 -08:00
// Should set the timeout limit to a reasonable 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;
struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{
if (aiTrav->ai_family == AF_INET)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
if (aiTrav->ai_family == AF_INET6)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
{
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
struct timeval MillisToTimeval(int64_t nTimeout)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
/**
* Read bytes from socket. This will either read the full number of bytes requested
* or return False on error or timeout.
* This function can be interrupted by boost thread interrupt.
*
* @param data Buffer to receive into
* @param len Length of data to receive
* @param timeout Timeout in milliseconds for receive operation
*
* @note This function requires that hSocket is in non-blocking mode.
*/
bool static InterruptibleRecv(uint8_t* data, size_t len, int timeout, SOCKET& hSocket)
{
int64_t curTime = GetTimeMillis();
int64_t endTime = curTime + timeout;
// Maximum time to wait in one select call. It will take up until this time (in millis)
// to break off in case of an interruption.
const int64_t maxWait = 1000;
while (len > 0 && curTime < endTime) {
// Optimistically try the recv first.
//
// POSIX recv() does not require a cast, as it takes a void *buf:
// ssize_t recv(int sockfd, void *buf, size_t len, int flags);
// However Windows explicitly requires a char *buf:
// int recv(SOCKET s, char *buf, int len, int flags);
ssize_t ret = recv(hSocket, reinterpret_cast<char*>(data), len, 0);
if (ret > 0) {
len -= ret;
data += ret;
} else if (ret == 0) { // Unexpected disconnection
return false;
} else { // Other error or blocking
int nErr = WSAGetLastError();
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
if (!IsSelectableSocket(hSocket)) {
return false;
}
struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
if (nRet == SOCKET_ERROR) {
return false;
}
} else {
return false;
}
}
boost::this_thread::interruption_point();
curTime = GetTimeMillis();
}
return len == 0;
}
struct ProxyCredentials
{
std::string username;
std::string password;
};
/** Connect using SOCKS5 (as described in RFC1928) */
static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
{
LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255) {
CloseSocket(hSocket);
2012-04-19 08:02:21 -07:00
return error("Hostname too long");
}
// Accepted authentication methods
std::vector<uint8_t> vSocks5Init;
vSocks5Init.push_back(0x05);
if (auth) {
vSocks5Init.push_back(0x02); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
} else {
vSocks5Init.push_back(0x01); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
}
ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5Init.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
uint8_t pchRet1[2];
if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to initialize");
}
if (pchRet1[1] == 0x02 && auth) {
// Perform username/password authentication (as described in RFC1929)
std::vector<uint8_t> vAuth;
vAuth.push_back(0x01);
if (auth->username.size() > 255 || auth->password.size() > 255)
return error("Proxy username or password too long");
vAuth.push_back(auth->username.size());
vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
vAuth.push_back(auth->password.size());
vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vAuth.size()) {
CloseSocket(hSocket);
return error("Error sending authentication to proxy");
}
LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
uint8_t pchRetA[2];
if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy authentication response");
}
if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
CloseSocket(hSocket);
return error("Proxy authentication unsuccessful");
}
} else if (pchRet1[1] == 0x00) {
// Perform no authentication
} else {
CloseSocket(hSocket);
return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
}
std::vector<uint8_t> vSocks5;
vSocks5.push_back(0x05); // VER protocol version
vSocks5.push_back(0x01); // CMD CONNECT
vSocks5.push_back(0x00); // RSV Reserved
vSocks5.push_back(0x03); // ATYP DOMAINNAME
vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
vSocks5.push_back((port >> 8) & 0xFF);
vSocks5.push_back((port >> 0) & 0xFF);
ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
uint8_t pchRet2[4];
if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00) {
CloseSocket(hSocket);
switch (pchRet2[1])
{
case 0x01: return error("Proxy error: general failure");
case 0x02: return error("Proxy error: connection not allowed");
case 0x03: return error("Proxy error: network unreachable");
case 0x04: return error("Proxy error: host unreachable");
case 0x05: return error("Proxy error: connection refused");
case 0x06: return error("Proxy error: TTL expired");
case 0x07: return error("Proxy error: protocol error");
case 0x08: return error("Proxy error: address type not supported");
default: return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00) {
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
uint8_t pchRet3[256];
switch (pchRet2[3])
{
case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
case 0x03:
{
ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
size_t nRecv = pchRet3[0];
ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
break;
}
default: CloseSocket(hSocket); return error("Error: malformed proxy response");
}
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
2012-04-19 08:02:21 -07:00
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
int set = 1;
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
//Disable Nagle's algorithm
#ifdef WIN32
setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
#else
setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
#endif
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true))
return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
{
struct timeval timeout = MillisToTimeval(nTimeout);
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
CloseSocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
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(), NetworkErrorString(nRet));
CloseSocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
}
2012-04-19 08:02:21 -07:00
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, const proxyType &addrProxy) {
2012-05-24 10:02:21 -07:00
assert(net >= 0 && net < NET_MAX);
if (!addrProxy.IsValid())
2012-05-24 10:02:21 -07:00
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = addrProxy;
2012-05-24 10:02:21 -07:00
return true;
}
bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
2012-05-24 10:02:21 -07:00
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].IsValid())
2012-05-24 10:02:21 -07:00
return false;
proxyInfoOut = proxyInfo[net];
2012-05-24 10:02:21 -07:00
return true;
}
bool SetNameProxy(const proxyType &addrProxy) {
if (!addrProxy.IsValid())
2012-05-24 10:02:21 -07:00
return false;
LOCK(cs_proxyInfos);
nameProxy = addrProxy;
2012-05-24 10:02:21 -07:00
return true;
}
bool GetNameProxy(proxyType &nameProxyOut) {
LOCK(cs_proxyInfos);
if(!nameProxy.IsValid())
return false;
nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy() {
LOCK(cs_proxyInfos);
return nameProxy.IsValid();
2012-05-24 10:02:21 -07:00
}
bool IsProxy(const CNetAddr &addr) {
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
2012-05-24 10:02:21 -07:00
return true;
}
return false;
}
static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
2012-04-19 08:02:21 -07:00
{
SOCKET hSocket = INVALID_SOCKET;
2012-05-24 10:02:21 -07:00
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
if (outProxyConnectionFailed)
*outProxyConnectionFailed = true;
2012-05-24 10:02:21 -07:00
return false;
}
2012-05-24 10:02:21 -07:00
// do socks negotiation
if (proxy.randomize_credentials) {
ProxyCredentials random_auth;
Kill insecure_random and associated global state There are only a few uses of `insecure_random` outside the tests. This PR replaces uses of insecure_random (and its accompanying global state) in the core code with an FastRandomContext that is automatically seeded on creation. This is meant to be used for inner loops. The FastRandomContext can be in the outer scope, or the class itself, then rand32() is used inside the loop. Useful e.g. for pushing addresses in CNode or the fee rounding, or randomization for coin selection. As a context is created per purpose, thus it gets rid of cross-thread unprotected shared usage of a single set of globals, this should also get rid of the potential race conditions. - I'd say TxMempool::check is not called enough to warrant using a special fast random context, this is switched to GetRand() (open for discussion...) - The use of `insecure_rand` in ConnectThroughProxy has been replaced by an atomic integer counter. The only goal here is to have a different credentials pair for each connection to go on a different Tor circuit, it does not need to be random nor unpredictable. - To avoid having a FastRandomContext on every CNode, the context is passed into PushAddress as appropriate. There remains an insecure_random for test usage in `test_random.h`. Zcash: Resolved conflicts with the following files src/addrman.cpp src/main.cpp src/net.cpp src/net.h src/policy/fees.cpp src/policy/fees.h src/random.cpp src/test/merkle_tests.cpp src/test/net_tests.cpp src/test/prevector_tests.cpp src/test/sighash_tests.cpp src/test/skiplist_tests.cpp src/test/test_bitcoin.cpp src/test/versionbits_tests.cpp src/wallet/test/crypto_tests.cpp
2016-10-13 07:19:20 -07:00
static std::atomic_int counter;
random_auth.username = random_auth.password = strprintf("%i", counter++);
if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
return false;
} else {
if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
proxyType proxy;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
if (GetProxy(addrDest.GetNetwork(), proxy))
return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
else // no proxy needed (none set for target network)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
}
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
{
std::string strDest;
int port = portDefault;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
SplitHostPort(std::string(pszDest), port, strDest);
proxyType nameProxy;
GetNameProxy(nameProxy);
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 (!HaveNameProxy())
return false;
return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
}
void CNetAddr::Init()
{
memset(ip, 0, sizeof(ip));
}
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)
{
if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
}
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
}
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
unsigned int CNetAddr::GetByte(int n) const
{
return ip[15-n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (
GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
2014-10-28 23:54:06 -07:00
bool CNetAddr::IsRFC2544() const
{
return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
2014-10-28 23:54:06 -07:00
bool CNetAddr::IsRFC6598() const
{
return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
}
bool CNetAddr::IsRFC5737() const
{
return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
(GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
(GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
|| (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
2012-07-25 17:48:39 -07:00
// Cleanup 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4())
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
2014-10-28 23:54:06 -07:00
return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
CService serv(*this, 0);
struct sockaddr_storage sockaddr;
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
return true;
}
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal())
{
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable())
{
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052())
{
nClass = NET_IPV4;
nStartByte = 12;
}
2012-07-25 17:48:39 -07:00
// for 6to4 tunnelled addresses, use the encapsulated IPv4 address
else if (IsRFC3964())
{
nClass = NET_IPV4;
nStartByte = 2;
}
2012-07-25 17:48:39 -07:00
// for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380())
{
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
}
else if (IsTor())
{
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8)
{
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
return vchRet;
}
uint64_t CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64_t nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
2012-02-12 04:45:24 -08:00
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch(theirNet) {
case NET_IPV4:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4;
}
case NET_IPV6:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV4: return REACH_IPV4;
2012-07-25 17:48:39 -07:00
case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
}
case NET_TOR:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR: return REACH_PRIVATE;
}
case NET_TEREDO:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
}
}
2012-02-12 04:45:24 -08:00
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
default:
return false;
}
}
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
2012-01-16 17:12:35 -08:00
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
{
2012-01-16 17:12:35 -08:00
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
2012-01-16 17:12:35 -08:00
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
{
2012-01-16 17:12:35 -08:00
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%u", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
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
const int astartofs = network.IsIPv4() ? 12 : 0;
if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
{
if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
{
n += astartofs*8;
// Clear bits [n..127]
for (; n < 128; ++n)
netmask[n>>3] &= ~(1<<(7-(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
{
// 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.
for(int x=astartofs; x<16; ++x)
netmask[x] = vIP[0].ip[x];
}
else
{
valid = false;
}
}
}
}
else
{
valid = false;
}
// Normalize network according to netmask
for(int x=0; x<16; ++x)
network.ip[x] &= netmask[x];
}
CSubNet::CSubNet(const CNetAddr &addr):
valid(addr.IsValid())
{
memset(netmask, 255, sizeof(netmask));
network = addr;
}
bool CSubNet::Match(const CNetAddr &addr) const
{
if (!valid || !addr.IsValid())
return false;
for(int x=0; x<16; ++x)
if ((addr.ip[x] & netmask[x]) != network.ip[x])
return false;
return true;
}
static inline int NetmaskBits(uint8_t x)
{
switch(x) {
case 0x00: return 0; break;
case 0x80: return 1; break;
case 0xc0: return 2; break;
case 0xe0: return 3; break;
case 0xf0: return 4; break;
case 0xf8: return 5; break;
case 0xfc: return 6; break;
case 0xfe: return 7; break;
case 0xff: return 8; break;
default: return -1; break;
}
}
std::string CSubNet::ToString() const
{
/* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
int cidr = 0;
bool valid_cidr = true;
int n = network.IsIPv4() ? 12 : 0;
for (; n < 16 && netmask[n] == 0xff; ++n)
cidr += 8;
if (n < 16) {
int bits = NetmaskBits(netmask[n]);
if (bits < 0)
valid_cidr = false;
else
cidr += bits;
++n;
}
for (; n < 16 && valid_cidr; ++n)
if (netmask[n] != 0x00)
valid_cidr = false;
/* Format output */
std::string strNetmask;
if (valid_cidr) {
strNetmask = strprintf("%u", cidr);
} else {
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);
}
2015-05-25 11:03:51 -07:00
bool operator<(const CSubNet& a, const CSubNet& b)
{
2015-06-12 10:51:50 -07:00
return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
2015-05-25 11:03:51 -07:00
}
#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 */
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
#endif
bool CloseSocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
return false;
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret != SOCKET_ERROR;
}
bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
{
if (fNonBlocking) {
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
} else {
#ifdef WIN32
u_long nZero = 0;
if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
}
return true;
}