]> Git Repo - VerusCoin.git/blame - src/netbase.cpp
Auto merge of #1116 - ebfull:performance-check-valid-pour-fix, r=ebfull
[VerusCoin.git] / src / netbase.cpp
CommitLineData
67a42f92 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
78253fcb 3// Distributed under the MIT software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
67a42f92 5
caf6150e 6#ifdef HAVE_CONFIG_H
a53d16ac 7#include "config/bitcoin-config.h"
caf6150e
HL
8#endif
9
67a42f92 10#include "netbase.h"
51ed9ec9 11
0fb9073e 12#include "hash.h"
51ed9ec9
BD
13#include "sync.h"
14#include "uint256.h"
67a79493 15#include "random.h"
51ed9ec9 16#include "util.h"
ad49c256 17#include "utilstrencodings.h"
51ed9ec9 18
eaedb59e
PK
19#ifdef HAVE_GETADDRINFO_A
20#include <netdb.h>
21#endif
22
67a42f92 23#ifndef WIN32
afe380ef
WL
24#if HAVE_INET_PTON
25#include <arpa/inet.h>
26#endif
98148a71 27#include <fcntl.h>
67a42f92
PW
28#endif
29
ea933b03 30#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
6032e4f4 31#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
ad49c256 32#include <boost/thread.hpp>
67a42f92 33
51ed9ec9 34#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
35b8af92
CF
35#define MSG_NOSIGNAL 0
36#endif
37
67a42f92 38// Settings
587f929c 39static proxyType proxyInfo[NET_MAX];
67a79493 40static proxyType nameProxy;
81bbef26 41static CCriticalSection cs_proxyInfos;
de10efd1 42int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
587f929c 43bool fNameLookup = false;
67a42f92
PW
44
45static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
46
6050ab68
WL
47// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
48static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
49
090e5b40 50enum Network ParseNetwork(std::string net) {
ea933b03 51 boost::to_lower(net);
090e5b40
PW
52 if (net == "ipv4") return NET_IPV4;
53 if (net == "ipv6") return NET_IPV6;
60dc8e42 54 if (net == "tor" || net == "onion") return NET_TOR;
090e5b40
PW
55 return NET_UNROUTABLE;
56}
57
075cf49e
WL
58std::string GetNetworkName(enum Network net) {
59 switch(net)
60 {
61 case NET_IPV4: return "ipv4";
62 case NET_IPV6: return "ipv6";
63 case NET_TOR: return "onion";
64 default: return "";
65 }
66}
67
1e8aeae1
PW
68void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
69 size_t colon = in.find_last_of(':');
70 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
71 bool fHaveColon = colon != in.npos;
72 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
73 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
74 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
d8642752
WL
75 int32_t n;
76 if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
1e8aeae1 77 in = in.substr(0, colon);
d8642752 78 portOut = n;
1e8aeae1
PW
79 }
80 }
81 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
82 hostOut = in.substr(1, in.size()-2);
83 else
84 hostOut = in;
85}
86
3a78f82a 87bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
67a42f92
PW
88{
89 vIP.clear();
70f7f003
PW
90
91 {
92 CNetAddr addr;
93 if (addr.SetSpecial(std::string(pszName))) {
94 vIP.push_back(addr);
95 return true;
96 }
97 }
98
caf6150e
HL
99#ifdef HAVE_GETADDRINFO_A
100 struct in_addr ipv4_addr;
101#ifdef HAVE_INET_PTON
102 if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
103 vIP.push_back(CNetAddr(ipv4_addr));
104 return true;
105 }
106
107 struct in6_addr ipv6_addr;
108 if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
109 vIP.push_back(CNetAddr(ipv6_addr));
110 return true;
111 }
112#else
113 ipv4_addr.s_addr = inet_addr(pszName);
114 if (ipv4_addr.s_addr != INADDR_NONE) {
115 vIP.push_back(CNetAddr(ipv4_addr));
116 return true;
117 }
118#endif
119#endif
120
a1de57a0
GA
121 struct addrinfo aiHint;
122 memset(&aiHint, 0, sizeof(struct addrinfo));
67a42f92
PW
123 aiHint.ai_socktype = SOCK_STREAM;
124 aiHint.ai_protocol = IPPROTO_TCP;
67a42f92 125 aiHint.ai_family = AF_UNSPEC;
fe9e88cb 126#ifdef WIN32
4c6b210a 127 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
67a42f92 128#else
4c6b210a 129 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
67a42f92 130#endif
caf6150e 131
67a42f92 132 struct addrinfo *aiRes = NULL;
caf6150e
HL
133#ifdef HAVE_GETADDRINFO_A
134 struct gaicb gcb, *query = &gcb;
135 memset(query, 0, sizeof(struct gaicb));
136 gcb.ar_name = pszName;
137 gcb.ar_request = &aiHint;
138 int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
139 if (nErr)
140 return false;
141
142 do {
143 // Should set the timeout limit to a resonable value to avoid
144 // generating unnecessary checking call during the polling loop,
145 // while it can still response to stop request quick enough.
146 // 2 seconds looks fine in our situation.
147 struct timespec ts = { 2, 0 };
148 gai_suspend(&query, 1, &ts);
149 boost::this_thread::interruption_point();
150
151 nErr = gai_error(query);
152 if (0 == nErr)
153 aiRes = query->ar_result;
154 } while (nErr == EAI_INPROGRESS);
155#else
67a42f92 156 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
caf6150e 157#endif
67a42f92
PW
158 if (nErr)
159 return false;
160
161 struct addrinfo *aiTrav = aiRes;
162 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
163 {
164 if (aiTrav->ai_family == AF_INET)
165 {
166 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
167 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
168 }
169
67a42f92
PW
170 if (aiTrav->ai_family == AF_INET6)
171 {
172 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
173 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
174 }
67a42f92
PW
175
176 aiTrav = aiTrav->ai_next;
177 }
178
179 freeaddrinfo(aiRes);
180
181 return (vIP.size() > 0);
182}
183
3a78f82a 184bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
67a42f92 185{
fe9e88cb
WL
186 std::string strHost(pszName);
187 if (strHost.empty())
67a42f92 188 return false;
fe9e88cb 189 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
67a42f92 190 {
fe9e88cb 191 strHost = strHost.substr(1, strHost.size() - 2);
67a42f92
PW
192 }
193
6032e4f4 194 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
67a42f92
PW
195}
196
3a78f82a 197bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
67a42f92
PW
198{
199 if (pszName[0] == 0)
200 return false;
201 int port = portDefault;
1e8aeae1
PW
202 std::string hostname = "";
203 SplitHostPort(std::string(pszName), port, hostname);
67a42f92
PW
204
205 std::vector<CNetAddr> vIP;
1e8aeae1 206 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
b24e6e4d
MC
207 if (!fRet)
208 return false;
209 vAddr.resize(vIP.size());
c376ac35 210 for (unsigned int i = 0; i < vIP.size(); i++)
b24e6e4d
MC
211 vAddr[i] = CService(vIP[i], port);
212 return true;
213}
214
215bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
216{
217 std::vector<CService> vService;
218 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
67a42f92
PW
219 if (!fRet)
220 return false;
b24e6e4d 221 addr = vService[0];
67a42f92
PW
222 return true;
223}
224
225bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
226{
227 return Lookup(pszName, addr, portDefault, false);
228}
229
6050ab68
WL
230/**
231 * Convert milliseconds to a struct timeval for select.
232 */
233struct timeval static MillisToTimeval(int64_t nTimeout)
234{
235 struct timeval timeout;
236 timeout.tv_sec = nTimeout / 1000;
237 timeout.tv_usec = (nTimeout % 1000) * 1000;
238 return timeout;
239}
240
241/**
242 * Read bytes from socket. This will either read the full number of bytes requested
243 * or return False on error or timeout.
244 * This function can be interrupted by boost thread interrupt.
245 *
246 * @param data Buffer to receive into
247 * @param len Length of data to receive
248 * @param timeout Timeout in milliseconds for receive operation
249 *
250 * @note This function requires that hSocket is in non-blocking mode.
251 */
252bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
253{
254 int64_t curTime = GetTimeMillis();
255 int64_t endTime = curTime + timeout;
256 // Maximum time to wait in one select call. It will take up until this time (in millis)
257 // to break off in case of an interruption.
258 const int64_t maxWait = 1000;
259 while (len > 0 && curTime < endTime) {
260 ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
261 if (ret > 0) {
262 len -= ret;
263 data += ret;
264 } else if (ret == 0) { // Unexpected disconnection
265 return false;
266 } else { // Other error or blocking
267 int nErr = WSAGetLastError();
268 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
0095b9a1
PW
269 if (!IsSelectableSocket(hSocket)) {
270 return false;
271 }
6050ab68
WL
272 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
273 fd_set fdset;
274 FD_ZERO(&fdset);
275 FD_SET(hSocket, &fdset);
276 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
277 if (nRet == SOCKET_ERROR) {
278 return false;
279 }
280 } else {
281 return false;
282 }
283 }
284 boost::this_thread::interruption_point();
285 curTime = GetTimeMillis();
286 }
287 return len == 0;
288}
289
67a79493
WL
290struct ProxyCredentials
291{
292 std::string username;
293 std::string password;
294};
295
296/** Connect using SOCKS5 (as described in RFC1928) */
d1af89e6 297static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
60a87bce 298{
7d9d134b 299 LogPrintf("SOCKS5 connecting %s\n", strDest);
67a79493 300 if (strDest.size() > 255) {
43f510d3 301 CloseSocket(hSocket);
a012e2db
PW
302 return error("Hostname too long");
303 }
67a79493
WL
304 // Accepted authentication methods
305 std::vector<uint8_t> vSocks5Init;
306 vSocks5Init.push_back(0x05);
307 if (auth) {
308 vSocks5Init.push_back(0x02); // # METHODS
309 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
310 vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
311 } else {
312 vSocks5Init.push_back(0x01); // # METHODS
313 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
314 }
315 ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
316 if (ret != (ssize_t)vSocks5Init.size()) {
43f510d3 317 CloseSocket(hSocket);
60a87bce
PW
318 return error("Error sending to proxy");
319 }
320 char pchRet1[2];
67a79493 321 if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
43f510d3 322 CloseSocket(hSocket);
60a87bce
PW
323 return error("Error reading proxy response");
324 }
67a79493 325 if (pchRet1[0] != 0x05) {
43f510d3 326 CloseSocket(hSocket);
60a87bce
PW
327 return error("Proxy failed to initialize");
328 }
67a79493
WL
329 if (pchRet1[1] == 0x02 && auth) {
330 // Perform username/password authentication (as described in RFC1929)
331 std::vector<uint8_t> vAuth;
332 vAuth.push_back(0x01);
333 if (auth->username.size() > 255 || auth->password.size() > 255)
334 return error("Proxy username or password too long");
335 vAuth.push_back(auth->username.size());
336 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
337 vAuth.push_back(auth->password.size());
338 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
339 ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
340 if (ret != (ssize_t)vAuth.size()) {
341 CloseSocket(hSocket);
342 return error("Error sending authentication to proxy");
343 }
344 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
345 char pchRetA[2];
346 if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
347 CloseSocket(hSocket);
348 return error("Error reading proxy authentication response");
349 }
350 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
351 CloseSocket(hSocket);
45bfa137 352 return error("Proxy authentication unsuccessful");
67a79493
WL
353 }
354 } else if (pchRet1[1] == 0x00) {
355 // Perform no authentication
356 } else {
357 CloseSocket(hSocket);
358 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
359 }
360 std::vector<uint8_t> vSocks5;
361 vSocks5.push_back(0x05); // VER protocol version
362 vSocks5.push_back(0x01); // CMD CONNECT
363 vSocks5.push_back(0x00); // RSV Reserved
364 vSocks5.push_back(0x03); // ATYP DOMAINNAME
365 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
366 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
367 vSocks5.push_back((port >> 8) & 0xFF);
368 vSocks5.push_back((port >> 0) & 0xFF);
369 ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
370 if (ret != (ssize_t)vSocks5.size()) {
43f510d3 371 CloseSocket(hSocket);
60a87bce
PW
372 return error("Error sending to proxy");
373 }
374 char pchRet2[4];
67a79493 375 if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
43f510d3 376 CloseSocket(hSocket);
60a87bce
PW
377 return error("Error reading proxy response");
378 }
67a79493 379 if (pchRet2[0] != 0x05) {
43f510d3 380 CloseSocket(hSocket);
60a87bce
PW
381 return error("Proxy failed to accept request");
382 }
67a79493 383 if (pchRet2[1] != 0x00) {
43f510d3 384 CloseSocket(hSocket);
60a87bce
PW
385 switch (pchRet2[1])
386 {
387 case 0x01: return error("Proxy error: general failure");
388 case 0x02: return error("Proxy error: connection not allowed");
389 case 0x03: return error("Proxy error: network unreachable");
390 case 0x04: return error("Proxy error: host unreachable");
391 case 0x05: return error("Proxy error: connection refused");
392 case 0x06: return error("Proxy error: TTL expired");
393 case 0x07: return error("Proxy error: protocol error");
394 case 0x08: return error("Proxy error: address type not supported");
395 default: return error("Proxy error: unknown");
396 }
397 }
67a79493 398 if (pchRet2[2] != 0x00) {
43f510d3 399 CloseSocket(hSocket);
60a87bce
PW
400 return error("Error: malformed proxy response");
401 }
402 char pchRet3[256];
403 switch (pchRet2[3])
404 {
6050ab68
WL
405 case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
406 case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
60a87bce
PW
407 case 0x03:
408 {
6050ab68
WL
409 ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
410 if (!ret) {
43f510d3 411 CloseSocket(hSocket);
60a87bce 412 return error("Error reading from proxy");
0bd05b53 413 }
60a87bce 414 int nRecv = pchRet3[0];
6050ab68 415 ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
60a87bce
PW
416 break;
417 }
43f510d3 418 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
60a87bce 419 }
67a79493 420 if (!ret) {
43f510d3 421 CloseSocket(hSocket);
60a87bce
PW
422 return error("Error reading from proxy");
423 }
67a79493 424 if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
43f510d3 425 CloseSocket(hSocket);
60a87bce
PW
426 return error("Error reading from proxy");
427 }
7d9d134b 428 LogPrintf("SOCKS5 connected %s\n", strDest);
60a87bce
PW
429 return true;
430}
431
a012e2db 432bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
67a42f92
PW
433{
434 hSocketRet = INVALID_SOCKET;
435
8f10a288 436 struct sockaddr_storage sockaddr;
8f10a288
PW
437 socklen_t len = sizeof(sockaddr);
438 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
7d9d134b 439 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
23aa78c4
PW
440 return false;
441 }
442
8f10a288 443 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
67a42f92
PW
444 if (hSocket == INVALID_SOCKET)
445 return false;
eaedb59e 446
67a42f92 447 int set = 1;
95a50390 448#ifdef SO_NOSIGPIPE
efd6b878 449 // Different way of disabling SIGPIPE on BSD
67a42f92 450 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
95a50390
GM
451#endif
452
453 //Disable Nagle's algorithm
454#ifdef WIN32
455 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
456#else
457 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
67a42f92
PW
458#endif
459
eaedb59e
PK
460 // Set to non-blocking
461 if (!SetSocketNonBlocking(hSocket, true))
462 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
67a42f92 463
8f10a288 464 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
67a42f92 465 {
6dc90ed8 466 int nErr = WSAGetLastError();
67a42f92 467 // WSAEINVAL is here because some legacy version of winsock uses it
6dc90ed8 468 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
67a42f92 469 {
6050ab68 470 struct timeval timeout = MillisToTimeval(nTimeout);
67a42f92
PW
471 fd_set fdset;
472 FD_ZERO(&fdset);
473 FD_SET(hSocket, &fdset);
474 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
475 if (nRet == 0)
476 {
7d9d134b 477 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
43f510d3 478 CloseSocket(hSocket);
67a42f92
PW
479 return false;
480 }
481 if (nRet == SOCKET_ERROR)
482 {
a60838d0 483 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
43f510d3 484 CloseSocket(hSocket);
67a42f92
PW
485 return false;
486 }
487 socklen_t nRetSize = sizeof(nRet);
488#ifdef WIN32
489 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
490#else
491 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
492#endif
493 {
a60838d0 494 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
43f510d3 495 CloseSocket(hSocket);
67a42f92
PW
496 return false;
497 }
498 if (nRet != 0)
499 {
a60838d0 500 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
43f510d3 501 CloseSocket(hSocket);
67a42f92
PW
502 return false;
503 }
504 }
505#ifdef WIN32
506 else if (WSAGetLastError() != WSAEISCONN)
507#else
508 else
509#endif
510 {
a60838d0 511 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
43f510d3 512 CloseSocket(hSocket);
67a42f92
PW
513 return false;
514 }
515 }
516
a012e2db
PW
517 hSocketRet = hSocket;
518 return true;
519}
520
67a79493 521bool SetProxy(enum Network net, const proxyType &addrProxy) {
587f929c 522 assert(net >= 0 && net < NET_MAX);
0127a9be 523 if (!addrProxy.IsValid())
587f929c 524 return false;
81bbef26 525 LOCK(cs_proxyInfos);
0127a9be 526 proxyInfo[net] = addrProxy;
587f929c
PW
527 return true;
528}
529
81bbef26 530bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
587f929c 531 assert(net >= 0 && net < NET_MAX);
81bbef26 532 LOCK(cs_proxyInfos);
0127a9be 533 if (!proxyInfo[net].IsValid())
587f929c 534 return false;
81bbef26 535 proxyInfoOut = proxyInfo[net];
587f929c
PW
536 return true;
537}
538
67a79493 539bool SetNameProxy(const proxyType &addrProxy) {
0127a9be 540 if (!addrProxy.IsValid())
587f929c 541 return false;
81bbef26 542 LOCK(cs_proxyInfos);
0127a9be 543 nameProxy = addrProxy;
587f929c
PW
544 return true;
545}
546
67a79493 547bool GetNameProxy(proxyType &nameProxyOut) {
81bbef26 548 LOCK(cs_proxyInfos);
0127a9be 549 if(!nameProxy.IsValid())
81bbef26 550 return false;
0127a9be 551 nameProxyOut = nameProxy;
81bbef26
PK
552 return true;
553}
554
555bool HaveNameProxy() {
556 LOCK(cs_proxyInfos);
0127a9be 557 return nameProxy.IsValid();
587f929c
PW
558}
559
560bool IsProxy(const CNetAddr &addr) {
81bbef26
PK
561 LOCK(cs_proxyInfos);
562 for (int i = 0; i < NET_MAX; i++) {
67a79493 563 if (addr == (CNetAddr)proxyInfo[i].proxy)
587f929c
PW
564 return true;
565 }
566 return false;
567}
568
d1af89e6 569static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
a012e2db
PW
570{
571 SOCKET hSocket = INVALID_SOCKET;
587f929c 572 // first connect to proxy server
67a79493 573 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
35e408f8
WL
574 if (outProxyConnectionFailed)
575 *outProxyConnectionFailed = true;
587f929c 576 return false;
35e408f8 577 }
587f929c 578 // do socks negotiation
67a79493
WL
579 if (proxy.randomize_credentials) {
580 ProxyCredentials random_auth;
581 random_auth.username = strprintf("%i", insecure_rand());
582 random_auth.password = strprintf("%i", insecure_rand());
583 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
584 return false;
585 } else {
586 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
587 return false;
588 }
67a42f92
PW
589
590 hSocketRet = hSocket;
591 return true;
592}
593
67a79493
WL
594bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
595{
596 proxyType proxy;
597 if (outProxyConnectionFailed)
598 *outProxyConnectionFailed = false;
599
600 if (GetProxy(addrDest.GetNetwork(), proxy))
601 return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
602 else // no proxy needed (none set for target network)
603 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
604}
605
35e408f8 606bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
9bab521d 607{
d6922aad 608 std::string strDest;
9bab521d 609 int port = portDefault;
35e408f8
WL
610
611 if (outProxyConnectionFailed)
612 *outProxyConnectionFailed = false;
613
d6922aad 614 SplitHostPort(std::string(pszDest), port, strDest);
9bab521d 615
67a79493 616 proxyType nameProxy;
0127a9be 617 GetNameProxy(nameProxy);
81bbef26 618
0127a9be 619 CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
9bab521d
PW
620 if (addrResolved.IsValid()) {
621 addr = addrResolved;
622 return ConnectSocket(addr, hSocketRet, nTimeout);
623 }
0127a9be 624
9bab521d 625 addr = CService("0.0.0.0:0");
0127a9be
PK
626
627 if (!HaveNameProxy())
9bab521d 628 return false;
67a79493 629 return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
9bab521d
PW
630}
631
67a42f92
PW
632void CNetAddr::Init()
633{
0f8a6477 634 memset(ip, 0, sizeof(ip));
67a42f92
PW
635}
636
637void CNetAddr::SetIP(const CNetAddr& ipIn)
638{
639 memcpy(ip, ipIn.ip, sizeof(ip));
640}
641
e16be737
WL
642void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
643{
644 switch(network)
645 {
646 case NET_IPV4:
647 memcpy(ip, pchIPv4, 12);
648 memcpy(ip+12, ip_in, 4);
649 break;
650 case NET_IPV6:
651 memcpy(ip, ip_in, 16);
652 break;
653 default:
654 assert(!"invalid network");
655 }
656}
657
70f7f003 658static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
70f7f003
PW
659
660bool CNetAddr::SetSpecial(const std::string &strName)
661{
662 if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
663 std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
664 if (vchAddr.size() != 16-sizeof(pchOnionCat))
665 return false;
666 memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
667 for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
668 ip[i + sizeof(pchOnionCat)] = vchAddr[i];
669 return true;
670 }
70f7f003
PW
671 return false;
672}
673
67a42f92
PW
674CNetAddr::CNetAddr()
675{
676 Init();
677}
678
679CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
680{
e16be737 681 SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
67a42f92
PW
682}
683
67a42f92
PW
684CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
685{
e16be737 686 SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
67a42f92 687}
67a42f92
PW
688
689CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
690{
691 Init();
692 std::vector<CNetAddr> vIP;
693 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
694 *this = vIP[0];
695}
696
697CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
698{
699 Init();
700 std::vector<CNetAddr> vIP;
701 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
702 *this = vIP[0];
703}
704
463a1cab 705unsigned int CNetAddr::GetByte(int n) const
67a42f92
PW
706{
707 return ip[15-n];
708}
709
710bool CNetAddr::IsIPv4() const
711{
712 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
713}
714
23aa78c4
PW
715bool CNetAddr::IsIPv6() const
716{
4e882b79 717 return (!IsIPv4() && !IsTor());
23aa78c4
PW
718}
719
67a42f92
PW
720bool CNetAddr::IsRFC1918() const
721{
722 return IsIPv4() && (
ea0796bd
JG
723 GetByte(3) == 10 ||
724 (GetByte(3) == 192 && GetByte(2) == 168) ||
67a42f92
PW
725 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
726}
727
2d06c0fe
MC
728bool CNetAddr::IsRFC2544() const
729{
730 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
731}
732
67a42f92
PW
733bool CNetAddr::IsRFC3927() const
734{
735 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
736}
737
2d06c0fe
MC
738bool CNetAddr::IsRFC6598() const
739{
740 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
741}
742
743bool CNetAddr::IsRFC5737() const
744{
745 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
746 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
747 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
748}
749
67a42f92
PW
750bool CNetAddr::IsRFC3849() const
751{
752 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
753}
754
755bool CNetAddr::IsRFC3964() const
756{
757 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
758}
759
760bool CNetAddr::IsRFC6052() const
761{
762 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
763 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
764}
765
766bool CNetAddr::IsRFC4380() const
767{
768 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
769}
770
771bool CNetAddr::IsRFC4862() const
772{
773 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
774 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
775}
776
777bool CNetAddr::IsRFC4193() const
778{
779 return ((GetByte(15) & 0xFE) == 0xFC);
780}
781
782bool CNetAddr::IsRFC6145() const
783{
784 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
785 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
786}
787
788bool CNetAddr::IsRFC4843() const
789{
d3896211 790 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
67a42f92
PW
791}
792
70f7f003 793bool CNetAddr::IsTor() const
d3214856 794{
d3214856
PW
795 return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
796}
797
67a42f92
PW
798bool CNetAddr::IsLocal() const
799{
800 // IPv4 loopback
801 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
802 return true;
803
804 // IPv6 loopback (::1/128)
805 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
806 if (memcmp(ip, pchLocal, 16) == 0)
807 return true;
808
809 return false;
810}
811
812bool CNetAddr::IsMulticast() const
813{
814 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
815 || (GetByte(15) == 0xFF);
816}
817
818bool CNetAddr::IsValid() const
819{
814efd6f 820 // Cleanup 3-byte shifted addresses caused by garbage in size field
67a42f92
PW
821 // of addr messages from versions before 0.2.9 checksum.
822 // Two consecutive addr messages look like this:
823 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
824 // so if the first length field is garbled, it reads the second batch
825 // of addr misaligned by 3 bytes.
826 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
827 return false;
828
829 // unspecified IPv6 address (::/128)
830 unsigned char ipNone[16] = {};
831 if (memcmp(ip, ipNone, 16) == 0)
832 return false;
833
834 // documentation IPv6 address
835 if (IsRFC3849())
836 return false;
837
838 if (IsIPv4())
839 {
840 // INADDR_NONE
841 uint32_t ipNone = INADDR_NONE;
842 if (memcmp(ip+12, &ipNone, 4) == 0)
843 return false;
844
845 // 0
846 ipNone = 0;
847 if (memcmp(ip+12, &ipNone, 4) == 0)
848 return false;
849 }
850
851 return true;
852}
853
854bool CNetAddr::IsRoutable() const
855{
2d06c0fe 856 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
67a42f92
PW
857}
858
090e5b40
PW
859enum Network CNetAddr::GetNetwork() const
860{
861 if (!IsRoutable())
862 return NET_UNROUTABLE;
863
864 if (IsIPv4())
865 return NET_IPV4;
866
70f7f003 867 if (IsTor())
090e5b40
PW
868 return NET_TOR;
869
090e5b40
PW
870 return NET_IPV6;
871}
872
67a42f92
PW
873std::string CNetAddr::ToStringIP() const
874{
70f7f003
PW
875 if (IsTor())
876 return EncodeBase32(&ip[6], 10) + ".onion";
ca814646 877 CService serv(*this, 0);
ca814646 878 struct sockaddr_storage sockaddr;
ca814646
PW
879 socklen_t socklen = sizeof(sockaddr);
880 if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
881 char name[1025] = "";
882 if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
883 return std::string(name);
884 }
70f7f003 885 if (IsIPv4())
67a42f92
PW
886 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
887 else
888 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
889 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
890 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
891 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
892 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
893}
894
895std::string CNetAddr::ToString() const
896{
897 return ToStringIP();
898}
899
900bool operator==(const CNetAddr& a, const CNetAddr& b)
901{
902 return (memcmp(a.ip, b.ip, 16) == 0);
903}
904
905bool operator!=(const CNetAddr& a, const CNetAddr& b)
906{
907 return (memcmp(a.ip, b.ip, 16) != 0);
908}
909
910bool operator<(const CNetAddr& a, const CNetAddr& b)
911{
912 return (memcmp(a.ip, b.ip, 16) < 0);
913}
914
915bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
916{
917 if (!IsIPv4())
918 return false;
919 memcpy(pipv4Addr, ip+12, 4);
920 return true;
921}
922
67a42f92
PW
923bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
924{
925 memcpy(pipv6Addr, ip, 16);
926 return true;
927}
67a42f92
PW
928
929// get canonical identifier of an address' group
930// no two connections will be attempted to addresses with the same group
931std::vector<unsigned char> CNetAddr::GetGroup() const
932{
933 std::vector<unsigned char> vchRet;
c5b3ffd8 934 int nClass = NET_IPV6;
67a42f92
PW
935 int nStartByte = 0;
936 int nBits = 16;
937
5fee401f
PW
938 // all local addresses belong to the same group
939 if (IsLocal())
940 {
c5b3ffd8 941 nClass = 255;
5fee401f
PW
942 nBits = 0;
943 }
944
945 // all unroutable addresses belong to the same group
67a42f92
PW
946 if (!IsRoutable())
947 {
c5b3ffd8 948 nClass = NET_UNROUTABLE;
5fee401f 949 nBits = 0;
67a42f92
PW
950 }
951 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
952 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
953 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
954 {
c5b3ffd8 955 nClass = NET_IPV4;
67a42f92
PW
956 nStartByte = 12;
957 }
814efd6f 958 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
67a42f92
PW
959 else if (IsRFC3964())
960 {
c5b3ffd8 961 nClass = NET_IPV4;
67a42f92
PW
962 nStartByte = 2;
963 }
814efd6f 964 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
67a42f92
PW
965 else if (IsRFC4380())
966 {
c5b3ffd8 967 vchRet.push_back(NET_IPV4);
67a42f92
PW
968 vchRet.push_back(GetByte(3) ^ 0xFF);
969 vchRet.push_back(GetByte(2) ^ 0xFF);
970 return vchRet;
971 }
70f7f003
PW
972 else if (IsTor())
973 {
974 nClass = NET_TOR;
975 nStartByte = 6;
976 nBits = 4;
977 }
67a42f92 978 // for he.net, use /36 groups
a5e685bc 979 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
67a42f92
PW
980 nBits = 36;
981 // for the rest of the IPv6 network, use /32 groups
982 else
983 nBits = 32;
984
985 vchRet.push_back(nClass);
986 while (nBits >= 8)
987 {
988 vchRet.push_back(GetByte(15 - nStartByte));
989 nStartByte++;
990 nBits -= 8;
991 }
992 if (nBits > 0)
13642a50 993 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
67a42f92
PW
994
995 return vchRet;
996}
997
51ed9ec9 998uint64_t CNetAddr::GetHash() const
67a42f92
PW
999{
1000 uint256 hash = Hash(&ip[0], &ip[16]);
51ed9ec9 1001 uint64_t nRet;
67a42f92
PW
1002 memcpy(&nRet, &hash, sizeof(nRet));
1003 return nRet;
1004}
1005
d077dd2a
PW
1006// private extensions to enum Network, only returned by GetExtNetwork,
1007// and only used in GetReachabilityFrom
1008static const int NET_UNKNOWN = NET_MAX + 0;
1009static const int NET_TEREDO = NET_MAX + 1;
1010int static GetExtNetwork(const CNetAddr *addr)
1011{
1012 if (addr == NULL)
1013 return NET_UNKNOWN;
1014 if (addr->IsRFC4380())
1015 return NET_TEREDO;
1016 return addr->GetNetwork();
1017}
1018
1019/** Calculates a metric for how reachable (*this) is from a given partner */
39857190
PW
1020int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
1021{
d077dd2a
PW
1022 enum Reachability {
1023 REACH_UNREACHABLE,
1024 REACH_DEFAULT,
1025 REACH_TEREDO,
1026 REACH_IPV6_WEAK,
1027 REACH_IPV4,
1028 REACH_IPV6_STRONG,
1029 REACH_PRIVATE
1030 };
1031
1032 if (!IsRoutable())
1033 return REACH_UNREACHABLE;
1034
1035 int ourNet = GetExtNetwork(this);
1036 int theirNet = GetExtNetwork(paddrPartner);
1037 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
1038
1039 switch(theirNet) {
1040 case NET_IPV4:
1041 switch(ourNet) {
1042 default: return REACH_DEFAULT;
1043 case NET_IPV4: return REACH_IPV4;
1044 }
1045 case NET_IPV6:
1046 switch(ourNet) {
1047 default: return REACH_DEFAULT;
1048 case NET_TEREDO: return REACH_TEREDO;
1049 case NET_IPV4: return REACH_IPV4;
814efd6f 1050 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
d077dd2a
PW
1051 }
1052 case NET_TOR:
1053 switch(ourNet) {
1054 default: return REACH_DEFAULT;
1055 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
1056 case NET_TOR: return REACH_PRIVATE;
1057 }
d077dd2a
PW
1058 case NET_TEREDO:
1059 switch(ourNet) {
1060 default: return REACH_DEFAULT;
1061 case NET_TEREDO: return REACH_TEREDO;
1062 case NET_IPV6: return REACH_IPV6_WEAK;
1063 case NET_IPV4: return REACH_IPV4;
1064 }
1065 case NET_UNKNOWN:
1066 case NET_UNROUTABLE:
1067 default:
1068 switch(ourNet) {
1069 default: return REACH_DEFAULT;
1070 case NET_TEREDO: return REACH_TEREDO;
1071 case NET_IPV6: return REACH_IPV6_WEAK;
1072 case NET_IPV4: return REACH_IPV4;
4e882b79 1073 case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
d077dd2a
PW
1074 }
1075 }
39857190
PW
1076}
1077
67a42f92
PW
1078void CService::Init()
1079{
1080 port = 0;
1081}
1082
1083CService::CService()
1084{
1085 Init();
1086}
1087
1088CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
1089{
1090}
1091
1092CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
1093{
1094}
1095
67a42f92
PW
1096CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
1097{
1098}
67a42f92
PW
1099
1100CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
1101{
1102 assert(addr.sin_family == AF_INET);
1103}
1104
67a42f92
PW
1105CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1106{
1107 assert(addr.sin6_family == AF_INET6);
1108}
67a42f92 1109
8f10a288
PW
1110bool CService::SetSockAddr(const struct sockaddr *paddr)
1111{
1112 switch (paddr->sa_family) {
1113 case AF_INET:
1114 *this = CService(*(const struct sockaddr_in*)paddr);
1115 return true;
8f10a288
PW
1116 case AF_INET6:
1117 *this = CService(*(const struct sockaddr_in6*)paddr);
1118 return true;
8f10a288
PW
1119 default:
1120 return false;
1121 }
1122}
1123
67a42f92
PW
1124CService::CService(const char *pszIpPort, bool fAllowLookup)
1125{
1126 Init();
1127 CService ip;
1128 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1129 *this = ip;
1130}
1131
c981d768 1132CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
67a42f92 1133{
c981d768
PW
1134 Init();
1135 CService ip;
1136 if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1137 *this = ip;
67a42f92
PW
1138}
1139
1140CService::CService(const std::string &strIpPort, bool fAllowLookup)
1141{
1142 Init();
1143 CService ip;
1144 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
1145 *this = ip;
1146}
1147
c981d768 1148CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
67a42f92 1149{
c981d768
PW
1150 Init();
1151 CService ip;
1152 if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1153 *this = ip;
67a42f92
PW
1154}
1155
1156unsigned short CService::GetPort() const
1157{
1158 return port;
1159}
1160
1161bool operator==(const CService& a, const CService& b)
1162{
1163 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1164}
1165
1166bool operator!=(const CService& a, const CService& b)
1167{
1168 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1169}
1170
1171bool operator<(const CService& a, const CService& b)
1172{
1173 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1174}
1175
8f10a288 1176bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
67a42f92 1177{
8f10a288 1178 if (IsIPv4()) {
b69dd08a 1179 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
8f10a288
PW
1180 return false;
1181 *addrlen = sizeof(struct sockaddr_in);
1182 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
1183 memset(paddrin, 0, *addrlen);
1184 if (!GetInAddr(&paddrin->sin_addr))
1185 return false;
1186 paddrin->sin_family = AF_INET;
1187 paddrin->sin_port = htons(port);
1188 return true;
1189 }
8f10a288 1190 if (IsIPv6()) {
b69dd08a 1191 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
8f10a288
PW
1192 return false;
1193 *addrlen = sizeof(struct sockaddr_in6);
1194 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
1195 memset(paddrin6, 0, *addrlen);
1196 if (!GetIn6Addr(&paddrin6->sin6_addr))
1197 return false;
1198 paddrin6->sin6_family = AF_INET6;
1199 paddrin6->sin6_port = htons(port);
1200 return true;
1201 }
8f10a288
PW
1202 return false;
1203}
67a42f92
PW
1204
1205std::vector<unsigned char> CService::GetKey() const
1206{
1207 std::vector<unsigned char> vKey;
1208 vKey.resize(18);
1209 memcpy(&vKey[0], ip, 16);
1210 vKey[16] = port / 0x100;
1211 vKey[17] = port & 0x0FF;
1212 return vKey;
1213}
1214
1215std::string CService::ToStringPort() const
1216{
463a1cab 1217 return strprintf("%u", port);
67a42f92
PW
1218}
1219
1220std::string CService::ToStringIPPort() const
1221{
4e882b79 1222 if (IsIPv4() || IsTor()) {
23aa78c4
PW
1223 return ToStringIP() + ":" + ToStringPort();
1224 } else {
1225 return "[" + ToStringIP() + "]:" + ToStringPort();
1226 }
67a42f92
PW
1227}
1228
1229std::string CService::ToString() const
1230{
1231 return ToStringIPPort();
1232}
1233
67a42f92
PW
1234void CService::SetPort(unsigned short portIn)
1235{
1236 port = portIn;
1237}
e16be737
WL
1238
1239CSubNet::CSubNet():
1240 valid(false)
1241{
1242 memset(netmask, 0, sizeof(netmask));
1243}
1244
1245CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
1246{
1247 size_t slash = strSubnet.find_last_of('/');
1248 std::vector<CNetAddr> vIP;
1249
1250 valid = true;
1251 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
1252 memset(netmask, 255, sizeof(netmask));
1253
1254 std::string strAddress = strSubnet.substr(0, slash);
1255 if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
1256 {
1257 network = vIP[0];
1258 if (slash != strSubnet.npos)
1259 {
1260 std::string strNetmask = strSubnet.substr(slash + 1);
1261 int32_t n;
1262 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
19e8d7be 1263 const int astartofs = network.IsIPv4() ? 12 : 0;
e16be737
WL
1264 if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
1265 {
19e8d7be 1266 if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
e16be737 1267 {
19e8d7be 1268 n += astartofs*8;
e16be737
WL
1269 // Clear bits [n..127]
1270 for (; n < 128; ++n)
b45c50ce 1271 netmask[n>>3] &= ~(1<<(7-(n&7)));
e16be737
WL
1272 }
1273 else
1274 {
1275 valid = false;
1276 }
1277 }
1278 else // If not a valid number, try full netmask syntax
1279 {
1280 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
1281 {
e16be737
WL
1282 // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
1283 // we don't want pchIPv4 to be part of the mask.
19e8d7be
WL
1284 for(int x=astartofs; x<16; ++x)
1285 netmask[x] = vIP[0].ip[x];
e16be737
WL
1286 }
1287 else
1288 {
1289 valid = false;
1290 }
1291 }
1292 }
1293 }
1294 else
1295 {
1296 valid = false;
1297 }
b45c50ce
WL
1298
1299 // Normalize network according to netmask
1300 for(int x=0; x<16; ++x)
1301 network.ip[x] &= netmask[x];
e16be737
WL
1302}
1303
1304bool CSubNet::Match(const CNetAddr &addr) const
1305{
1306 if (!valid || !addr.IsValid())
1307 return false;
1308 for(int x=0; x<16; ++x)
19e8d7be 1309 if ((addr.ip[x] & netmask[x]) != network.ip[x])
e16be737
WL
1310 return false;
1311 return true;
1312}
1313
1314std::string CSubNet::ToString() const
1315{
1316 std::string strNetmask;
1317 if (network.IsIPv4())
1318 strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
1319 else
1320 strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
1321 netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
1322 netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
1323 netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
1324 netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
1325 return network.ToString() + "/" + strNetmask;
1326}
1327
1328bool CSubNet::IsValid() const
1329{
1330 return valid;
1331}
1332
1333bool operator==(const CSubNet& a, const CSubNet& b)
1334{
1335 return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1336}
1337
1338bool operator!=(const CSubNet& a, const CSubNet& b)
1339{
1340 return !(a==b);
1341}
a60838d0
WL
1342
1343#ifdef WIN32
1344std::string NetworkErrorString(int err)
1345{
1346 char buf[256];
1347 buf[0] = 0;
1348 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1349 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1350 buf, sizeof(buf), NULL))
1351 {
1352 return strprintf("%s (%d)", buf, err);
1353 }
1354 else
1355 {
1356 return strprintf("Unknown error (%d)", err);
1357 }
1358}
1359#else
1360std::string NetworkErrorString(int err)
1361{
1362 char buf[256];
1363 const char *s = buf;
1364 buf[0] = 0;
1365 /* Too bad there are two incompatible implementations of the
1366 * thread-safe strerror. */
1367#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
1368 s = strerror_r(err, buf, sizeof(buf));
1369#else /* POSIX variant always returns message in buffer */
109849e2
LD
1370 if (strerror_r(err, buf, sizeof(buf)))
1371 buf[0] = 0;
a60838d0
WL
1372#endif
1373 return strprintf("%s (%d)", s, err);
1374}
1375#endif
43f510d3
WL
1376
1377bool CloseSocket(SOCKET& hSocket)
1378{
1379 if (hSocket == INVALID_SOCKET)
1380 return false;
1381#ifdef WIN32
1382 int ret = closesocket(hSocket);
1383#else
1384 int ret = close(hSocket);
1385#endif
1386 hSocket = INVALID_SOCKET;
1387 return ret != SOCKET_ERROR;
1388}
eaedb59e
PK
1389
1390bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
1391{
1392 if (fNonBlocking) {
1393#ifdef WIN32
1394 u_long nOne = 1;
1395 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
1396#else
1397 int fFlags = fcntl(hSocket, F_GETFL, 0);
1398 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
1399#endif
1400 CloseSocket(hSocket);
1401 return false;
1402 }
1403 } else {
1404#ifdef WIN32
1405 u_long nZero = 0;
1406 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
1407#else
1408 int fFlags = fcntl(hSocket, F_GETFL, 0);
1409 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
1410#endif
1411 CloseSocket(hSocket);
1412 return false;
1413 }
1414 }
1415
1416 return true;
1417}
This page took 0.458734 seconds and 4 git commands to generate.