]> Git Repo - VerusCoin.git/blob - src/netbase.cpp
test
[VerusCoin.git] / src / netbase.cpp
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 __APPLE__
20 #ifdef HAVE_GETADDRINFO_A
21 #undef HAVE_GETADDRINFO_A
22 #endif
23 #endif
24
25 #ifdef HAVE_GETADDRINFO_A
26 #include <netdb.h>
27 #endif
28
29 #ifndef WIN32
30 #if HAVE_INET_PTON
31 #include <arpa/inet.h>
32 #endif
33 #include <fcntl.h>
34 #endif
35
36 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
37 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
38 #include <boost/thread.hpp>
39
40 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
41 #define MSG_NOSIGNAL 0
42 #endif
43
44 // Settings
45 static proxyType proxyInfo[NET_MAX];
46 static proxyType nameProxy;
47 static CCriticalSection cs_proxyInfos;
48 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
49 bool fNameLookup = false;
50
51 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
52
53 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
54 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
55
56 enum Network ParseNetwork(std::string net) {
57     boost::to_lower(net);
58     if (net == "ipv4") return NET_IPV4;
59     if (net == "ipv6") return NET_IPV6;
60     if (net == "tor" || net == "onion")  return NET_TOR;
61     return NET_UNROUTABLE;
62 }
63
64 std::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
74 void 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)) {
81         int32_t n;
82         if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
83             in = in.substr(0, colon);
84             portOut = n;
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
93 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
94 {
95     vIP.clear();
96
97     {
98         CNetAddr addr;
99         if (addr.SetSpecial(std::string(pszName))) {
100             vIP.push_back(addr);
101             return true;
102         }
103     }
104
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
127     struct addrinfo aiHint;
128     memset(&aiHint, 0, sizeof(struct addrinfo));
129     aiHint.ai_socktype = SOCK_STREAM;
130     aiHint.ai_protocol = IPPROTO_TCP;
131     aiHint.ai_family = AF_UNSPEC;
132 #ifdef WIN32
133     aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
134 #else
135     aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
136 #endif
137
138     struct addrinfo *aiRes = NULL;
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
162     int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
163 #endif
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
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         }
181
182         aiTrav = aiTrav->ai_next;
183     }
184
185     freeaddrinfo(aiRes);
186
187     return (vIP.size() > 0);
188 }
189
190 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
191 {
192     std::string strHost(pszName);
193     if (strHost.empty())
194         return false;
195     if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
196     {
197         strHost = strHost.substr(1, strHost.size() - 2);
198     }
199
200     return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
201 }
202
203 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
204 {
205     if (pszName[0] == 0)
206         return false;
207     int port = portDefault;
208     std::string hostname = "";
209     SplitHostPort(std::string(pszName), port, hostname);
210
211     std::vector<CNetAddr> vIP;
212     bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
213     if (!fRet)
214         return false;
215     vAddr.resize(vIP.size());
216     for (unsigned int i = 0; i < vIP.size(); i++)
217         vAddr[i] = CService(vIP[i], port);
218     return true;
219 }
220
221 bool 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);
225     if (!fRet)
226         return false;
227     addr = vService[0];
228     return true;
229 }
230
231 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
232 {
233     return Lookup(pszName, addr, portDefault, false);
234 }
235
236 /**
237  * Convert milliseconds to a struct timeval for select.
238  */
239 struct 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  */
258 bool 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) {
275                 if (!IsSelectableSocket(hSocket)) {
276                     return false;
277                 }
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
296 struct ProxyCredentials
297 {
298     std::string username;
299     std::string password;
300 };
301
302 /** Connect using SOCKS5 (as described in RFC1928) */
303 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
304 {
305     LogPrintf("SOCKS5 connecting %s\n", strDest);
306     if (strDest.size() > 255) {
307         CloseSocket(hSocket);
308         return error("Hostname too long");
309     }
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()) {
323         CloseSocket(hSocket);
324         return error("Error sending to proxy");
325     }
326     char pchRet1[2];
327     if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
328         CloseSocket(hSocket);
329         return error("Error reading proxy response");
330     }
331     if (pchRet1[0] != 0x05) {
332         CloseSocket(hSocket);
333         return error("Proxy failed to initialize");
334     }
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);
358             return error("Proxy authentication unsuccessful");
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()) {
377         CloseSocket(hSocket);
378         return error("Error sending to proxy");
379     }
380     char pchRet2[4];
381     if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
382         CloseSocket(hSocket);
383         return error("Error reading proxy response");
384     }
385     if (pchRet2[0] != 0x05) {
386         CloseSocket(hSocket);
387         return error("Proxy failed to accept request");
388     }
389     if (pchRet2[1] != 0x00) {
390         CloseSocket(hSocket);
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     }
404     if (pchRet2[2] != 0x00) {
405         CloseSocket(hSocket);
406         return error("Error: malformed proxy response");
407     }
408     char pchRet3[256];
409     switch (pchRet2[3])
410     {
411         case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
412         case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
413         case 0x03:
414         {
415             ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
416             if (!ret) {
417                 CloseSocket(hSocket);
418                 return error("Error reading from proxy");
419             }
420             int nRecv = pchRet3[0];
421             ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
422             break;
423         }
424         default: CloseSocket(hSocket); return error("Error: malformed proxy response");
425     }
426     if (!ret) {
427         CloseSocket(hSocket);
428         return error("Error reading from proxy");
429     }
430     if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
431         CloseSocket(hSocket);
432         return error("Error reading from proxy");
433     }
434     LogPrintf("SOCKS5 connected %s\n", strDest);
435     return true;
436 }
437
438 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
439 {
440     hSocketRet = INVALID_SOCKET;
441
442     struct sockaddr_storage sockaddr;
443     socklen_t len = sizeof(sockaddr);
444     if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
445         LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
446         return false;
447     }
448
449     SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
450     if (hSocket == INVALID_SOCKET)
451         return false;
452
453     int set = 1;
454 #ifdef SO_NOSIGPIPE
455     // Different way of disabling SIGPIPE on BSD
456     setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
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));
464 #endif
465
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()));
469
470     if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
471     {
472         int nErr = WSAGetLastError();
473         // WSAEINVAL is here because some legacy version of winsock uses it
474         if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
475         {
476             struct timeval timeout = MillisToTimeval(nTimeout);
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             {
483                 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
484                 CloseSocket(hSocket);
485                 return false;
486             }
487             if (nRet == SOCKET_ERROR)
488             {
489                 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
490                 CloseSocket(hSocket);
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             {
500                 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
501                 CloseSocket(hSocket);
502                 return false;
503             }
504             if (nRet != 0)
505             {
506                 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
507                 CloseSocket(hSocket);
508                 return false;
509             }
510         }
511 #ifdef WIN32
512         else if (WSAGetLastError() != WSAEISCONN)
513 #else
514         else
515 #endif
516         {
517             LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
518             CloseSocket(hSocket);
519             return false;
520         }
521     }
522
523     hSocketRet = hSocket;
524     return true;
525 }
526
527 bool SetProxy(enum Network net, const proxyType &addrProxy) {
528     assert(net >= 0 && net < NET_MAX);
529     if (!addrProxy.IsValid())
530         return false;
531     LOCK(cs_proxyInfos);
532     proxyInfo[net] = addrProxy;
533     return true;
534 }
535
536 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
537     assert(net >= 0 && net < NET_MAX);
538     LOCK(cs_proxyInfos);
539     if (!proxyInfo[net].IsValid())
540         return false;
541     proxyInfoOut = proxyInfo[net];
542     return true;
543 }
544
545 bool SetNameProxy(const proxyType &addrProxy) {
546     if (!addrProxy.IsValid())
547         return false;
548     LOCK(cs_proxyInfos);
549     nameProxy = addrProxy;
550     return true;
551 }
552
553 bool GetNameProxy(proxyType &nameProxyOut) {
554     LOCK(cs_proxyInfos);
555     if(!nameProxy.IsValid())
556         return false;
557     nameProxyOut = nameProxy;
558     return true;
559 }
560
561 bool HaveNameProxy() {
562     LOCK(cs_proxyInfos);
563     return nameProxy.IsValid();
564 }
565
566 bool IsProxy(const CNetAddr &addr) {
567     LOCK(cs_proxyInfos);
568     for (int i = 0; i < NET_MAX; i++) {
569         if (addr == (CNetAddr)proxyInfo[i].proxy)
570             return true;
571     }
572     return false;
573 }
574
575 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
576 {
577     SOCKET hSocket = INVALID_SOCKET;
578     // first connect to proxy server
579     if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
580         if (outProxyConnectionFailed)
581             *outProxyConnectionFailed = true;
582         return false;
583     }
584     // do socks negotiation
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     }
595
596     hSocketRet = hSocket;
597     return true;
598 }
599
600 bool 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
612 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
613 {
614     std::string strDest;
615     int port = portDefault;
616
617     if (outProxyConnectionFailed)
618         *outProxyConnectionFailed = false;
619
620     SplitHostPort(std::string(pszDest), port, strDest);
621
622     proxyType nameProxy;
623     GetNameProxy(nameProxy);
624
625     CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
626     if (addrResolved.IsValid()) {
627         addr = addrResolved;
628         return ConnectSocket(addr, hSocketRet, nTimeout);
629     }
630
631     addr = CService("0.0.0.0:0");
632
633     if (!HaveNameProxy())
634         return false;
635     return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
636 }
637
638 void CNetAddr::Init()
639 {
640     memset(ip, 0, sizeof(ip));
641 }
642
643 void CNetAddr::SetIP(const CNetAddr& ipIn)
644 {
645     memcpy(ip, ipIn.ip, sizeof(ip));
646 }
647
648 void 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
664 static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
665
666 bool 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     }
677     return false;
678 }
679
680 CNetAddr::CNetAddr()
681 {
682     Init();
683 }
684
685 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
686 {
687     SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
688 }
689
690 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
691 {
692     SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
693 }
694
695 CNetAddr::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
703 CNetAddr::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
711 unsigned int CNetAddr::GetByte(int n) const
712 {
713     return ip[15-n];
714 }
715
716 bool CNetAddr::IsIPv4() const
717 {
718     return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
719 }
720
721 bool CNetAddr::IsIPv6() const
722 {
723     return (!IsIPv4() && !IsTor());
724 }
725
726 bool CNetAddr::IsRFC1918() const
727 {
728     return IsIPv4() && (
729         GetByte(3) == 10 ||
730         (GetByte(3) == 192 && GetByte(2) == 168) ||
731         (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
732 }
733
734 bool CNetAddr::IsRFC2544() const
735 {
736     return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
737 }
738
739 bool CNetAddr::IsRFC3927() const
740 {
741     return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
742 }
743
744 bool CNetAddr::IsRFC6598() const
745 {
746     return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
747 }
748
749 bool 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
756 bool CNetAddr::IsRFC3849() const
757 {
758     return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
759 }
760
761 bool CNetAddr::IsRFC3964() const
762 {
763     return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
764 }
765
766 bool 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
772 bool CNetAddr::IsRFC4380() const
773 {
774     return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
775 }
776
777 bool 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
783 bool CNetAddr::IsRFC4193() const
784 {
785     return ((GetByte(15) & 0xFE) == 0xFC);
786 }
787
788 bool 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
794 bool CNetAddr::IsRFC4843() const
795 {
796     return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
797 }
798
799 bool CNetAddr::IsTor() const
800 {
801     return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
802 }
803
804 bool 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
818 bool CNetAddr::IsMulticast() const
819 {
820     return    (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
821            || (GetByte(15) == 0xFF);
822 }
823
824 bool CNetAddr::IsValid() const
825 {
826     // Cleanup 3-byte shifted addresses caused by garbage in size field
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
860 bool CNetAddr::IsRoutable() const
861 {
862     return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
863 }
864
865 enum Network CNetAddr::GetNetwork() const
866 {
867     if (!IsRoutable())
868         return NET_UNROUTABLE;
869
870     if (IsIPv4())
871         return NET_IPV4;
872
873     if (IsTor())
874         return NET_TOR;
875
876     return NET_IPV6;
877 }
878
879 std::string CNetAddr::ToStringIP() const
880 {
881     if (IsTor())
882         return EncodeBase32(&ip[6], 10) + ".onion";
883     CService serv(*this, 0);
884     struct sockaddr_storage sockaddr;
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     }
891     if (IsIPv4())
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
901 std::string CNetAddr::ToString() const
902 {
903     return ToStringIP();
904 }
905
906 bool operator==(const CNetAddr& a, const CNetAddr& b)
907 {
908     return (memcmp(a.ip, b.ip, 16) == 0);
909 }
910
911 bool operator!=(const CNetAddr& a, const CNetAddr& b)
912 {
913     return (memcmp(a.ip, b.ip, 16) != 0);
914 }
915
916 bool operator<(const CNetAddr& a, const CNetAddr& b)
917 {
918     return (memcmp(a.ip, b.ip, 16) < 0);
919 }
920
921 bool 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
929 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
930 {
931     memcpy(pipv6Addr, ip, 16);
932     return true;
933 }
934
935 // get canonical identifier of an address' group
936 // no two connections will be attempted to addresses with the same group
937 std::vector<unsigned char> CNetAddr::GetGroup() const
938 {
939     std::vector<unsigned char> vchRet;
940     int nClass = NET_IPV6;
941     int nStartByte = 0;
942     int nBits = 16;
943
944     // all local addresses belong to the same group
945     if (IsLocal())
946     {
947         nClass = 255;
948         nBits = 0;
949     }
950
951     // all unroutable addresses belong to the same group
952     if (!IsRoutable())
953     {
954         nClass = NET_UNROUTABLE;
955         nBits = 0;
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     {
961         nClass = NET_IPV4;
962         nStartByte = 12;
963     }
964     // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
965     else if (IsRFC3964())
966     {
967         nClass = NET_IPV4;
968         nStartByte = 2;
969     }
970     // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
971     else if (IsRFC4380())
972     {
973         vchRet.push_back(NET_IPV4);
974         vchRet.push_back(GetByte(3) ^ 0xFF);
975         vchRet.push_back(GetByte(2) ^ 0xFF);
976         return vchRet;
977     }
978     else if (IsTor())
979     {
980         nClass = NET_TOR;
981         nStartByte = 6;
982         nBits = 4;
983     }
984     // for he.net, use /36 groups
985     else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
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)
999         vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
1000
1001     return vchRet;
1002 }
1003
1004 uint64_t CNetAddr::GetHash() const
1005 {
1006     uint256 hash = Hash(&ip[0], &ip[16]);
1007     uint64_t nRet;
1008     memcpy(&nRet, &hash, sizeof(nRet));
1009     return nRet;
1010 }
1011
1012 // private extensions to enum Network, only returned by GetExtNetwork,
1013 // and only used in GetReachabilityFrom
1014 static const int NET_UNKNOWN = NET_MAX + 0;
1015 static const int NET_TEREDO  = NET_MAX + 1;
1016 int 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 */
1026 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
1027 {
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;
1056         case NET_IPV6:   return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
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         }
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;
1079         case NET_TOR:     return REACH_PRIVATE; // either from Tor, or don't care about our address
1080         }
1081     }
1082 }
1083
1084 void CService::Init()
1085 {
1086     port = 0;
1087 }
1088
1089 CService::CService()
1090 {
1091     Init();
1092 }
1093
1094 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
1095 {
1096 }
1097
1098 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
1099 {
1100 }
1101
1102 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
1103 {
1104 }
1105
1106 CService::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
1111 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
1112 {
1113    assert(addr.sin6_family == AF_INET6);
1114 }
1115
1116 bool 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;
1122     case AF_INET6:
1123         *this = CService(*(const struct sockaddr_in6*)paddr);
1124         return true;
1125     default:
1126         return false;
1127     }
1128 }
1129
1130 CService::CService(const char *pszIpPort, bool fAllowLookup)
1131 {
1132     Init();
1133     CService ip;
1134     if (Lookup(pszIpPort, ip, 0, fAllowLookup))
1135         *this = ip;
1136 }
1137
1138 CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
1139 {
1140     Init();
1141     CService ip;
1142     if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
1143         *this = ip;
1144 }
1145
1146 CService::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
1154 CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
1155 {
1156     Init();
1157     CService ip;
1158     if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
1159         *this = ip;
1160 }
1161
1162 unsigned short CService::GetPort() const
1163 {
1164     return port;
1165 }
1166
1167 bool operator==(const CService& a, const CService& b)
1168 {
1169     return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
1170 }
1171
1172 bool operator!=(const CService& a, const CService& b)
1173 {
1174     return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
1175 }
1176
1177 bool operator<(const CService& a, const CService& b)
1178 {
1179     return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
1180 }
1181
1182 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
1183 {
1184     if (IsIPv4()) {
1185         if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
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     }
1196     if (IsIPv6()) {
1197         if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
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     }
1208     return false;
1209 }
1210
1211 std::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
1221 std::string CService::ToStringPort() const
1222 {
1223     return strprintf("%u", port);
1224 }
1225
1226 std::string CService::ToStringIPPort() const
1227 {
1228     if (IsIPv4() || IsTor()) {
1229         return ToStringIP() + ":" + ToStringPort();
1230     } else {
1231         return "[" + ToStringIP() + "]:" + ToStringPort();
1232     }
1233 }
1234
1235 std::string CService::ToString() const
1236 {
1237     return ToStringIPPort();
1238 }
1239
1240 void CService::SetPort(unsigned short portIn)
1241 {
1242     port = portIn;
1243 }
1244
1245 CSubNet::CSubNet():
1246     valid(false)
1247 {
1248     memset(netmask, 0, sizeof(netmask));
1249 }
1250
1251 CSubNet::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
1269             const int astartofs = network.IsIPv4() ? 12 : 0;
1270             if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
1271             {
1272                 if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
1273                 {
1274                     n += astartofs*8;
1275                     // Clear bits [n..127]
1276                     for (; n < 128; ++n)
1277                         netmask[n>>3] &= ~(1<<(7-(n&7)));
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                 {
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.
1290                     for(int x=astartofs; x<16; ++x)
1291                         netmask[x] = vIP[0].ip[x];
1292                 }
1293                 else
1294                 {
1295                     valid = false;
1296                 }
1297             }
1298         }
1299     }
1300     else
1301     {
1302         valid = false;
1303     }
1304
1305     // Normalize network according to netmask
1306     for(int x=0; x<16; ++x)
1307         network.ip[x] &= netmask[x];
1308 }
1309
1310 bool CSubNet::Match(const CNetAddr &addr) const
1311 {
1312     if (!valid || !addr.IsValid())
1313         return false;
1314     for(int x=0; x<16; ++x)
1315         if ((addr.ip[x] & netmask[x]) != network.ip[x])
1316             return false;
1317     return true;
1318 }
1319
1320 std::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
1334 bool CSubNet::IsValid() const
1335 {
1336     return valid;
1337 }
1338
1339 bool 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
1344 bool operator!=(const CSubNet& a, const CSubNet& b)
1345 {
1346     return !(a==b);
1347 }
1348
1349 #ifdef WIN32
1350 std::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
1366 std::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 */
1376     if (strerror_r(err, buf, sizeof(buf)))
1377         buf[0] = 0;
1378 #endif
1379     return strprintf("%s (%d)", s, err);
1380 }
1381 #endif
1382
1383 bool 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 }
1395
1396 bool 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.100949 seconds and 4 git commands to generate.