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