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