Merge #9226: Remove fNetworkNode and pnodeLocalHost.
[bitcoinplatinum.git] / src / netbase.cpp
blob9fe34108f57d1f67cb27eb38272086fb31c31ceb
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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.
6 #ifdef HAVE_CONFIG_H
7 #include "config/bitcoin-config.h"
8 #endif
10 #include "netbase.h"
12 #include "hash.h"
13 #include "sync.h"
14 #include "uint256.h"
15 #include "random.h"
16 #include "util.h"
17 #include "utilstrencodings.h"
19 #ifdef HAVE_GETADDRINFO_A
20 #include <netdb.h>
21 #endif
23 #ifndef WIN32
24 #if HAVE_INET_PTON
25 #include <arpa/inet.h>
26 #endif
27 #include <fcntl.h>
28 #endif
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>
34 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
35 #define MSG_NOSIGNAL 0
36 #endif
38 // Settings
39 static proxyType proxyInfo[NET_MAX];
40 static proxyType nameProxy;
41 static CCriticalSection cs_proxyInfos;
42 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
43 bool fNameLookup = DEFAULT_NAME_LOOKUP;
45 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
46 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
48 enum Network ParseNetwork(std::string net) {
49 boost::to_lower(net);
50 if (net == "ipv4") return NET_IPV4;
51 if (net == "ipv6") return NET_IPV6;
52 if (net == "tor" || net == "onion") return NET_TOR;
53 return NET_UNROUTABLE;
56 std::string GetNetworkName(enum Network net) {
57 switch(net)
59 case NET_IPV4: return "ipv4";
60 case NET_IPV6: return "ipv6";
61 case NET_TOR: return "onion";
62 default: return "";
66 void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
67 size_t colon = in.find_last_of(':');
68 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
69 bool fHaveColon = colon != in.npos;
70 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
71 bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
72 if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
73 int32_t n;
74 if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
75 in = in.substr(0, colon);
76 portOut = n;
79 if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
80 hostOut = in.substr(1, in.size()-2);
81 else
82 hostOut = in;
85 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
87 vIP.clear();
90 CNetAddr addr;
91 if (addr.SetSpecial(std::string(pszName))) {
92 vIP.push_back(addr);
93 return true;
97 #ifdef HAVE_GETADDRINFO_A
98 struct in_addr ipv4_addr;
99 #ifdef HAVE_INET_PTON
100 if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
101 vIP.push_back(CNetAddr(ipv4_addr));
102 return true;
105 struct in6_addr ipv6_addr;
106 if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
107 vIP.push_back(CNetAddr(ipv6_addr));
108 return true;
110 #else
111 ipv4_addr.s_addr = inet_addr(pszName);
112 if (ipv4_addr.s_addr != INADDR_NONE) {
113 vIP.push_back(CNetAddr(ipv4_addr));
114 return true;
116 #endif
117 #endif
119 struct addrinfo aiHint;
120 memset(&aiHint, 0, sizeof(struct addrinfo));
121 aiHint.ai_socktype = SOCK_STREAM;
122 aiHint.ai_protocol = IPPROTO_TCP;
123 aiHint.ai_family = AF_UNSPEC;
124 #ifdef WIN32
125 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
126 #else
127 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
128 #endif
130 struct addrinfo *aiRes = NULL;
131 #ifdef HAVE_GETADDRINFO_A
132 struct gaicb gcb, *query = &gcb;
133 memset(query, 0, sizeof(struct gaicb));
134 gcb.ar_name = pszName;
135 gcb.ar_request = &aiHint;
136 int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
137 if (nErr)
138 return false;
140 do {
141 // Should set the timeout limit to a reasonable value to avoid
142 // generating unnecessary checking call during the polling loop,
143 // while it can still response to stop request quick enough.
144 // 2 seconds looks fine in our situation.
145 struct timespec ts = { 2, 0 };
146 gai_suspend(&query, 1, &ts);
147 boost::this_thread::interruption_point();
149 nErr = gai_error(query);
150 if (0 == nErr)
151 aiRes = query->ar_result;
152 } while (nErr == EAI_INPROGRESS);
153 #else
154 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
155 #endif
156 if (nErr)
157 return false;
159 struct addrinfo *aiTrav = aiRes;
160 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
162 if (aiTrav->ai_family == AF_INET)
164 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
165 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
168 if (aiTrav->ai_family == AF_INET6)
170 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
171 struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
172 vIP.push_back(CNetAddr(s6->sin6_addr, s6->sin6_scope_id));
175 aiTrav = aiTrav->ai_next;
178 freeaddrinfo(aiRes);
180 return (vIP.size() > 0);
183 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
185 std::string strHost(pszName);
186 if (strHost.empty())
187 return false;
188 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
190 strHost = strHost.substr(1, strHost.size() - 2);
193 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
196 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
198 std::vector<CNetAddr> vIP;
199 LookupHost(pszName, vIP, 1, fAllowLookup);
200 if(vIP.empty())
201 return false;
202 addr = vIP.front();
203 return true;
206 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
208 if (pszName[0] == 0)
209 return false;
210 int port = portDefault;
211 std::string hostname = "";
212 SplitHostPort(std::string(pszName), port, hostname);
214 std::vector<CNetAddr> vIP;
215 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
216 if (!fRet)
217 return false;
218 vAddr.resize(vIP.size());
219 for (unsigned int i = 0; i < vIP.size(); i++)
220 vAddr[i] = CService(vIP[i], port);
221 return true;
224 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
226 std::vector<CService> vService;
227 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
228 if (!fRet)
229 return false;
230 addr = vService[0];
231 return true;
234 CService LookupNumeric(const char *pszName, int portDefault)
236 CService addr;
237 // "1.2:345" will fail to resolve the ip, but will still set the port.
238 // If the ip fails to resolve, re-init the result.
239 if(!Lookup(pszName, addr, portDefault, false))
240 addr = CService();
241 return addr;
244 struct timeval MillisToTimeval(int64_t nTimeout)
246 struct timeval timeout;
247 timeout.tv_sec = nTimeout / 1000;
248 timeout.tv_usec = (nTimeout % 1000) * 1000;
249 return timeout;
253 * Read bytes from socket. This will either read the full number of bytes requested
254 * or return False on error or timeout.
255 * This function can be interrupted by boost thread interrupt.
257 * @param data Buffer to receive into
258 * @param len Length of data to receive
259 * @param timeout Timeout in milliseconds for receive operation
261 * @note This function requires that hSocket is in non-blocking mode.
263 bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
265 int64_t curTime = GetTimeMillis();
266 int64_t endTime = curTime + timeout;
267 // Maximum time to wait in one select call. It will take up until this time (in millis)
268 // to break off in case of an interruption.
269 const int64_t maxWait = 1000;
270 while (len > 0 && curTime < endTime) {
271 ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
272 if (ret > 0) {
273 len -= ret;
274 data += ret;
275 } else if (ret == 0) { // Unexpected disconnection
276 return false;
277 } else { // Other error or blocking
278 int nErr = WSAGetLastError();
279 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
280 if (!IsSelectableSocket(hSocket)) {
281 return false;
283 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
284 fd_set fdset;
285 FD_ZERO(&fdset);
286 FD_SET(hSocket, &fdset);
287 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
288 if (nRet == SOCKET_ERROR) {
289 return false;
291 } else {
292 return false;
295 boost::this_thread::interruption_point();
296 curTime = GetTimeMillis();
298 return len == 0;
301 struct ProxyCredentials
303 std::string username;
304 std::string password;
307 std::string Socks5ErrorString(int err)
309 switch(err) {
310 case 0x01: return "general failure";
311 case 0x02: return "connection not allowed";
312 case 0x03: return "network unreachable";
313 case 0x04: return "host unreachable";
314 case 0x05: return "connection refused";
315 case 0x06: return "TTL expired";
316 case 0x07: return "protocol error";
317 case 0x08: return "address type not supported";
318 default: return "unknown";
322 /** Connect using SOCKS5 (as described in RFC1928) */
323 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
325 LogPrint("net", "SOCKS5 connecting %s\n", strDest);
326 if (strDest.size() > 255) {
327 CloseSocket(hSocket);
328 return error("Hostname too long");
330 // Accepted authentication methods
331 std::vector<uint8_t> vSocks5Init;
332 vSocks5Init.push_back(0x05);
333 if (auth) {
334 vSocks5Init.push_back(0x02); // # METHODS
335 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
336 vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
337 } else {
338 vSocks5Init.push_back(0x01); // # METHODS
339 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
341 ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
342 if (ret != (ssize_t)vSocks5Init.size()) {
343 CloseSocket(hSocket);
344 return error("Error sending to proxy");
346 char pchRet1[2];
347 if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
348 CloseSocket(hSocket);
349 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
350 return false;
352 if (pchRet1[0] != 0x05) {
353 CloseSocket(hSocket);
354 return error("Proxy failed to initialize");
356 if (pchRet1[1] == 0x02 && auth) {
357 // Perform username/password authentication (as described in RFC1929)
358 std::vector<uint8_t> vAuth;
359 vAuth.push_back(0x01);
360 if (auth->username.size() > 255 || auth->password.size() > 255)
361 return error("Proxy username or password too long");
362 vAuth.push_back(auth->username.size());
363 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
364 vAuth.push_back(auth->password.size());
365 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
366 ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
367 if (ret != (ssize_t)vAuth.size()) {
368 CloseSocket(hSocket);
369 return error("Error sending authentication to proxy");
371 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
372 char pchRetA[2];
373 if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
374 CloseSocket(hSocket);
375 return error("Error reading proxy authentication response");
377 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
378 CloseSocket(hSocket);
379 return error("Proxy authentication unsuccessful");
381 } else if (pchRet1[1] == 0x00) {
382 // Perform no authentication
383 } else {
384 CloseSocket(hSocket);
385 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
387 std::vector<uint8_t> vSocks5;
388 vSocks5.push_back(0x05); // VER protocol version
389 vSocks5.push_back(0x01); // CMD CONNECT
390 vSocks5.push_back(0x00); // RSV Reserved
391 vSocks5.push_back(0x03); // ATYP DOMAINNAME
392 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
393 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
394 vSocks5.push_back((port >> 8) & 0xFF);
395 vSocks5.push_back((port >> 0) & 0xFF);
396 ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
397 if (ret != (ssize_t)vSocks5.size()) {
398 CloseSocket(hSocket);
399 return error("Error sending to proxy");
401 char pchRet2[4];
402 if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
403 CloseSocket(hSocket);
404 return error("Error reading proxy response");
406 if (pchRet2[0] != 0x05) {
407 CloseSocket(hSocket);
408 return error("Proxy failed to accept request");
410 if (pchRet2[1] != 0x00) {
411 // Failures to connect to a peer that are not proxy errors
412 CloseSocket(hSocket);
413 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
414 return false;
416 if (pchRet2[2] != 0x00) {
417 CloseSocket(hSocket);
418 return error("Error: malformed proxy response");
420 char pchRet3[256];
421 switch (pchRet2[3])
423 case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
424 case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
425 case 0x03:
427 ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
428 if (!ret) {
429 CloseSocket(hSocket);
430 return error("Error reading from proxy");
432 int nRecv = pchRet3[0];
433 ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
434 break;
436 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
438 if (!ret) {
439 CloseSocket(hSocket);
440 return error("Error reading from proxy");
442 if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
443 CloseSocket(hSocket);
444 return error("Error reading from proxy");
446 LogPrint("net", "SOCKS5 connected %s\n", strDest);
447 return true;
450 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
452 hSocketRet = INVALID_SOCKET;
454 struct sockaddr_storage sockaddr;
455 socklen_t len = sizeof(sockaddr);
456 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
457 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
458 return false;
461 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
462 if (hSocket == INVALID_SOCKET)
463 return false;
465 int set = 1;
466 #ifdef SO_NOSIGPIPE
467 // Different way of disabling SIGPIPE on BSD
468 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
469 #endif
471 //Disable Nagle's algorithm
472 #ifdef WIN32
473 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
474 #else
475 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
476 #endif
478 // Set to non-blocking
479 if (!SetSocketNonBlocking(hSocket, true))
480 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
482 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
484 int nErr = WSAGetLastError();
485 // WSAEINVAL is here because some legacy version of winsock uses it
486 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
488 struct timeval timeout = MillisToTimeval(nTimeout);
489 fd_set fdset;
490 FD_ZERO(&fdset);
491 FD_SET(hSocket, &fdset);
492 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
493 if (nRet == 0)
495 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
496 CloseSocket(hSocket);
497 return false;
499 if (nRet == SOCKET_ERROR)
501 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
502 CloseSocket(hSocket);
503 return false;
505 socklen_t nRetSize = sizeof(nRet);
506 #ifdef WIN32
507 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
508 #else
509 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
510 #endif
512 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
513 CloseSocket(hSocket);
514 return false;
516 if (nRet != 0)
518 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
519 CloseSocket(hSocket);
520 return false;
523 #ifdef WIN32
524 else if (WSAGetLastError() != WSAEISCONN)
525 #else
526 else
527 #endif
529 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
530 CloseSocket(hSocket);
531 return false;
535 hSocketRet = hSocket;
536 return true;
539 bool SetProxy(enum Network net, const proxyType &addrProxy) {
540 assert(net >= 0 && net < NET_MAX);
541 if (!addrProxy.IsValid())
542 return false;
543 LOCK(cs_proxyInfos);
544 proxyInfo[net] = addrProxy;
545 return true;
548 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
549 assert(net >= 0 && net < NET_MAX);
550 LOCK(cs_proxyInfos);
551 if (!proxyInfo[net].IsValid())
552 return false;
553 proxyInfoOut = proxyInfo[net];
554 return true;
557 bool SetNameProxy(const proxyType &addrProxy) {
558 if (!addrProxy.IsValid())
559 return false;
560 LOCK(cs_proxyInfos);
561 nameProxy = addrProxy;
562 return true;
565 bool GetNameProxy(proxyType &nameProxyOut) {
566 LOCK(cs_proxyInfos);
567 if(!nameProxy.IsValid())
568 return false;
569 nameProxyOut = nameProxy;
570 return true;
573 bool HaveNameProxy() {
574 LOCK(cs_proxyInfos);
575 return nameProxy.IsValid();
578 bool IsProxy(const CNetAddr &addr) {
579 LOCK(cs_proxyInfos);
580 for (int i = 0; i < NET_MAX; i++) {
581 if (addr == (CNetAddr)proxyInfo[i].proxy)
582 return true;
584 return false;
587 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
589 SOCKET hSocket = INVALID_SOCKET;
590 // first connect to proxy server
591 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
592 if (outProxyConnectionFailed)
593 *outProxyConnectionFailed = true;
594 return false;
596 // do socks negotiation
597 if (proxy.randomize_credentials) {
598 ProxyCredentials random_auth;
599 static std::atomic_int counter;
600 random_auth.username = random_auth.password = strprintf("%i", counter++);
601 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
602 return false;
603 } else {
604 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
605 return false;
608 hSocketRet = hSocket;
609 return true;
612 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
614 proxyType proxy;
615 if (outProxyConnectionFailed)
616 *outProxyConnectionFailed = false;
618 if (GetProxy(addrDest.GetNetwork(), proxy))
619 return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
620 else // no proxy needed (none set for target network)
621 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
624 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
626 std::string strDest;
627 int port = portDefault;
629 if (outProxyConnectionFailed)
630 *outProxyConnectionFailed = false;
632 SplitHostPort(std::string(pszDest), port, strDest);
634 proxyType proxy;
635 GetNameProxy(proxy);
637 std::vector<CService> addrResolved;
638 if (Lookup(strDest.c_str(), addrResolved, port, fNameLookup && !HaveNameProxy(), 256)) {
639 if (addrResolved.size() > 0) {
640 addr = addrResolved[GetRand(addrResolved.size())];
641 return ConnectSocket(addr, hSocketRet, nTimeout);
645 addr = CService();
647 if (!HaveNameProxy())
648 return false;
649 return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
652 bool LookupSubNet(const char* pszName, CSubNet& ret)
654 std::string strSubnet(pszName);
655 size_t slash = strSubnet.find_last_of('/');
656 std::vector<CNetAddr> vIP;
658 std::string strAddress = strSubnet.substr(0, slash);
659 if (LookupHost(strAddress.c_str(), vIP, 1, false))
661 CNetAddr network = vIP[0];
662 if (slash != strSubnet.npos)
664 std::string strNetmask = strSubnet.substr(slash + 1);
665 int32_t n;
666 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
667 if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
668 ret = CSubNet(network, n);
669 return ret.IsValid();
671 else // If not a valid number, try full netmask syntax
673 // Never allow lookup for netmask
674 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
675 ret = CSubNet(network, vIP[0]);
676 return ret.IsValid();
680 else
682 ret = CSubNet(network);
683 return ret.IsValid();
686 return false;
689 #ifdef WIN32
690 std::string NetworkErrorString(int err)
692 char buf[256];
693 buf[0] = 0;
694 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
695 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
696 buf, sizeof(buf), NULL))
698 return strprintf("%s (%d)", buf, err);
700 else
702 return strprintf("Unknown error (%d)", err);
705 #else
706 std::string NetworkErrorString(int err)
708 char buf[256];
709 const char *s = buf;
710 buf[0] = 0;
711 /* Too bad there are two incompatible implementations of the
712 * thread-safe strerror. */
713 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
714 s = strerror_r(err, buf, sizeof(buf));
715 #else /* POSIX variant always returns message in buffer */
716 if (strerror_r(err, buf, sizeof(buf)))
717 buf[0] = 0;
718 #endif
719 return strprintf("%s (%d)", s, err);
721 #endif
723 bool CloseSocket(SOCKET& hSocket)
725 if (hSocket == INVALID_SOCKET)
726 return false;
727 #ifdef WIN32
728 int ret = closesocket(hSocket);
729 #else
730 int ret = close(hSocket);
731 #endif
732 hSocket = INVALID_SOCKET;
733 return ret != SOCKET_ERROR;
736 bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
738 if (fNonBlocking) {
739 #ifdef WIN32
740 u_long nOne = 1;
741 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
742 #else
743 int fFlags = fcntl(hSocket, F_GETFL, 0);
744 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
745 #endif
746 CloseSocket(hSocket);
747 return false;
749 } else {
750 #ifdef WIN32
751 u_long nZero = 0;
752 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
753 #else
754 int fFlags = fcntl(hSocket, F_GETFL, 0);
755 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
756 #endif
757 CloseSocket(hSocket);
758 return false;
762 return true;