Merge #12001: [RPC] Adding ::minRelayTxFee amount to getmempoolinfo and updating...
[bitcoinplatinum.git] / src / netbase.cpp
blob276b2f4dc2582d6de7d540c748a56fe0ac3c636e
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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 #include <netbase.h>
8 #include <hash.h>
9 #include <sync.h>
10 #include <uint256.h>
11 #include <random.h>
12 #include <util.h>
13 #include <utilstrencodings.h>
15 #include <atomic>
17 #ifndef WIN32
18 #include <fcntl.h>
19 #endif
21 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
22 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
24 #if !defined(HAVE_MSG_NOSIGNAL)
25 #define MSG_NOSIGNAL 0
26 #endif
28 // Settings
29 static proxyType proxyInfo[NET_MAX];
30 static proxyType nameProxy;
31 static CCriticalSection cs_proxyInfos;
32 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
33 bool fNameLookup = DEFAULT_NAME_LOOKUP;
35 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
36 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
37 static std::atomic<bool> interruptSocks5Recv(false);
39 enum Network ParseNetwork(std::string net) {
40 boost::to_lower(net);
41 if (net == "ipv4") return NET_IPV4;
42 if (net == "ipv6") return NET_IPV6;
43 if (net == "tor" || net == "onion") return NET_TOR;
44 return NET_UNROUTABLE;
47 std::string GetNetworkName(enum Network net) {
48 switch(net)
50 case NET_IPV4: return "ipv4";
51 case NET_IPV6: return "ipv6";
52 case NET_TOR: return "onion";
53 default: return "";
57 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
59 vIP.clear();
62 CNetAddr addr;
63 if (addr.SetSpecial(std::string(pszName))) {
64 vIP.push_back(addr);
65 return true;
69 struct addrinfo aiHint;
70 memset(&aiHint, 0, sizeof(struct addrinfo));
72 aiHint.ai_socktype = SOCK_STREAM;
73 aiHint.ai_protocol = IPPROTO_TCP;
74 aiHint.ai_family = AF_UNSPEC;
75 #ifdef WIN32
76 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
77 #else
78 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
79 #endif
80 struct addrinfo *aiRes = nullptr;
81 int nErr = getaddrinfo(pszName, nullptr, &aiHint, &aiRes);
82 if (nErr)
83 return false;
85 struct addrinfo *aiTrav = aiRes;
86 while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
88 CNetAddr resolved;
89 if (aiTrav->ai_family == AF_INET)
91 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
92 resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
95 if (aiTrav->ai_family == AF_INET6)
97 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
98 struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
99 resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
101 /* Never allow resolving to an internal address. Consider any such result invalid */
102 if (!resolved.IsInternal()) {
103 vIP.push_back(resolved);
106 aiTrav = aiTrav->ai_next;
109 freeaddrinfo(aiRes);
111 return (vIP.size() > 0);
114 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
116 std::string strHost(pszName);
117 if (strHost.empty())
118 return false;
119 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
121 strHost = strHost.substr(1, strHost.size() - 2);
124 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
127 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
129 std::vector<CNetAddr> vIP;
130 LookupHost(pszName, vIP, 1, fAllowLookup);
131 if(vIP.empty())
132 return false;
133 addr = vIP.front();
134 return true;
137 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
139 if (pszName[0] == 0)
140 return false;
141 int port = portDefault;
142 std::string hostname = "";
143 SplitHostPort(std::string(pszName), port, hostname);
145 std::vector<CNetAddr> vIP;
146 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
147 if (!fRet)
148 return false;
149 vAddr.resize(vIP.size());
150 for (unsigned int i = 0; i < vIP.size(); i++)
151 vAddr[i] = CService(vIP[i], port);
152 return true;
155 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
157 std::vector<CService> vService;
158 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
159 if (!fRet)
160 return false;
161 addr = vService[0];
162 return true;
165 CService LookupNumeric(const char *pszName, int portDefault)
167 CService addr;
168 // "1.2:345" will fail to resolve the ip, but will still set the port.
169 // If the ip fails to resolve, re-init the result.
170 if(!Lookup(pszName, addr, portDefault, false))
171 addr = CService();
172 return addr;
175 struct timeval MillisToTimeval(int64_t nTimeout)
177 struct timeval timeout;
178 timeout.tv_sec = nTimeout / 1000;
179 timeout.tv_usec = (nTimeout % 1000) * 1000;
180 return timeout;
183 /** SOCKS version */
184 enum SOCKSVersion: uint8_t {
185 SOCKS4 = 0x04,
186 SOCKS5 = 0x05
189 /** Values defined for METHOD in RFC1928 */
190 enum SOCKS5Method: uint8_t {
191 NOAUTH = 0x00, //! No authentication required
192 GSSAPI = 0x01, //! GSSAPI
193 USER_PASS = 0x02, //! Username/password
194 NO_ACCEPTABLE = 0xff, //! No acceptable methods
197 /** Values defined for CMD in RFC1928 */
198 enum SOCKS5Command: uint8_t {
199 CONNECT = 0x01,
200 BIND = 0x02,
201 UDP_ASSOCIATE = 0x03
204 /** Values defined for REP in RFC1928 */
205 enum SOCKS5Reply: uint8_t {
206 SUCCEEDED = 0x00, //! Succeeded
207 GENFAILURE = 0x01, //! General failure
208 NOTALLOWED = 0x02, //! Connection not allowed by ruleset
209 NETUNREACHABLE = 0x03, //! Network unreachable
210 HOSTUNREACHABLE = 0x04, //! Network unreachable
211 CONNREFUSED = 0x05, //! Connection refused
212 TTLEXPIRED = 0x06, //! TTL expired
213 CMDUNSUPPORTED = 0x07, //! Command not supported
214 ATYPEUNSUPPORTED = 0x08, //! Address type not supported
217 /** Values defined for ATYPE in RFC1928 */
218 enum SOCKS5Atyp: uint8_t {
219 IPV4 = 0x01,
220 DOMAINNAME = 0x03,
221 IPV6 = 0x04,
224 /** Status codes that can be returned by InterruptibleRecv */
225 enum class IntrRecvError {
227 Timeout,
228 Disconnected,
229 NetworkError,
230 Interrupted
234 * Read bytes from socket. This will either read the full number of bytes requested
235 * or return False on error or timeout.
236 * This function can be interrupted by calling InterruptSocks5()
238 * @param data Buffer to receive into
239 * @param len Length of data to receive
240 * @param timeout Timeout in milliseconds for receive operation
242 * @note This function requires that hSocket is in non-blocking mode.
244 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket)
246 int64_t curTime = GetTimeMillis();
247 int64_t endTime = curTime + timeout;
248 // Maximum time to wait in one select call. It will take up until this time (in millis)
249 // to break off in case of an interruption.
250 const int64_t maxWait = 1000;
251 while (len > 0 && curTime < endTime) {
252 ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first
253 if (ret > 0) {
254 len -= ret;
255 data += ret;
256 } else if (ret == 0) { // Unexpected disconnection
257 return IntrRecvError::Disconnected;
258 } else { // Other error or blocking
259 int nErr = WSAGetLastError();
260 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
261 if (!IsSelectableSocket(hSocket)) {
262 return IntrRecvError::NetworkError;
264 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
265 fd_set fdset;
266 FD_ZERO(&fdset);
267 FD_SET(hSocket, &fdset);
268 int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval);
269 if (nRet == SOCKET_ERROR) {
270 return IntrRecvError::NetworkError;
272 } else {
273 return IntrRecvError::NetworkError;
276 if (interruptSocks5Recv)
277 return IntrRecvError::Interrupted;
278 curTime = GetTimeMillis();
280 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
283 /** Credentials for proxy authentication */
284 struct ProxyCredentials
286 std::string username;
287 std::string password;
290 /** Convert SOCKS5 reply to an error message */
291 std::string Socks5ErrorString(uint8_t err)
293 switch(err) {
294 case SOCKS5Reply::GENFAILURE:
295 return "general failure";
296 case SOCKS5Reply::NOTALLOWED:
297 return "connection not allowed";
298 case SOCKS5Reply::NETUNREACHABLE:
299 return "network unreachable";
300 case SOCKS5Reply::HOSTUNREACHABLE:
301 return "host unreachable";
302 case SOCKS5Reply::CONNREFUSED:
303 return "connection refused";
304 case SOCKS5Reply::TTLEXPIRED:
305 return "TTL expired";
306 case SOCKS5Reply::CMDUNSUPPORTED:
307 return "protocol error";
308 case SOCKS5Reply::ATYPEUNSUPPORTED:
309 return "address type not supported";
310 default:
311 return "unknown";
315 /** Connect using SOCKS5 (as described in RFC1928) */
316 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, const SOCKET& hSocket)
318 IntrRecvError recvr;
319 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
320 if (strDest.size() > 255) {
321 return error("Hostname too long");
323 // Accepted authentication methods
324 std::vector<uint8_t> vSocks5Init;
325 vSocks5Init.push_back(SOCKSVersion::SOCKS5);
326 if (auth) {
327 vSocks5Init.push_back(0x02); // Number of methods
328 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
329 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
330 } else {
331 vSocks5Init.push_back(0x01); // Number of methods
332 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
334 ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
335 if (ret != (ssize_t)vSocks5Init.size()) {
336 return error("Error sending to proxy");
338 uint8_t pchRet1[2];
339 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
340 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
341 return false;
343 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
344 return error("Proxy failed to initialize");
346 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
347 // Perform username/password authentication (as described in RFC1929)
348 std::vector<uint8_t> vAuth;
349 vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
350 if (auth->username.size() > 255 || auth->password.size() > 255)
351 return error("Proxy username or password too long");
352 vAuth.push_back(auth->username.size());
353 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
354 vAuth.push_back(auth->password.size());
355 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
356 ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
357 if (ret != (ssize_t)vAuth.size()) {
358 return error("Error sending authentication to proxy");
360 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
361 uint8_t pchRetA[2];
362 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
363 return error("Error reading proxy authentication response");
365 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
366 return error("Proxy authentication unsuccessful");
368 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
369 // Perform no authentication
370 } else {
371 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
373 std::vector<uint8_t> vSocks5;
374 vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
375 vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
376 vSocks5.push_back(0x00); // RSV Reserved must be 0
377 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
378 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
379 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
380 vSocks5.push_back((port >> 8) & 0xFF);
381 vSocks5.push_back((port >> 0) & 0xFF);
382 ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
383 if (ret != (ssize_t)vSocks5.size()) {
384 return error("Error sending to proxy");
386 uint8_t pchRet2[4];
387 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
388 if (recvr == IntrRecvError::Timeout) {
389 /* If a timeout happens here, this effectively means we timed out while connecting
390 * to the remote node. This is very common for Tor, so do not print an
391 * error message. */
392 return false;
393 } else {
394 return error("Error while reading proxy response");
397 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
398 return error("Proxy failed to accept request");
400 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
401 // Failures to connect to a peer that are not proxy errors
402 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
403 return false;
405 if (pchRet2[2] != 0x00) { // Reserved field must be 0
406 return error("Error: malformed proxy response");
408 uint8_t pchRet3[256];
409 switch (pchRet2[3])
411 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
412 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
413 case SOCKS5Atyp::DOMAINNAME:
415 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
416 if (recvr != IntrRecvError::OK) {
417 return error("Error reading from proxy");
419 int nRecv = pchRet3[0];
420 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
421 break;
423 default: return error("Error: malformed proxy response");
425 if (recvr != IntrRecvError::OK) {
426 return error("Error reading from proxy");
428 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
429 return error("Error reading from proxy");
431 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
432 return true;
435 SOCKET CreateSocket(const CService &addrConnect)
437 struct sockaddr_storage sockaddr;
438 socklen_t len = sizeof(sockaddr);
439 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
440 LogPrintf("Cannot create socket for %s: unsupported network\n", addrConnect.ToString());
441 return INVALID_SOCKET;
444 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
445 if (hSocket == INVALID_SOCKET)
446 return INVALID_SOCKET;
448 if (!IsSelectableSocket(hSocket)) {
449 CloseSocket(hSocket);
450 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
451 return INVALID_SOCKET;
454 #ifdef SO_NOSIGPIPE
455 int set = 1;
456 // Different way of disabling SIGPIPE on BSD
457 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
458 #endif
460 //Disable Nagle's algorithm
461 SetSocketNoDelay(hSocket);
463 // Set to non-blocking
464 if (!SetSocketNonBlocking(hSocket, true)) {
465 CloseSocket(hSocket);
466 LogPrintf("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
468 return hSocket;
471 bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET& hSocket, int nTimeout)
473 struct sockaddr_storage sockaddr;
474 socklen_t len = sizeof(sockaddr);
475 if (hSocket == INVALID_SOCKET) {
476 LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
477 return false;
479 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
480 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
481 return false;
483 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
485 int nErr = WSAGetLastError();
486 // WSAEINVAL is here because some legacy version of winsock uses it
487 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
489 struct timeval timeout = MillisToTimeval(nTimeout);
490 fd_set fdset;
491 FD_ZERO(&fdset);
492 FD_SET(hSocket, &fdset);
493 int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
494 if (nRet == 0)
496 LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
497 return false;
499 if (nRet == SOCKET_ERROR)
501 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
502 return false;
504 socklen_t nRetSize = sizeof(nRet);
505 #ifdef WIN32
506 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
507 #else
508 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
509 #endif
511 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
512 return false;
514 if (nRet != 0)
516 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
517 return false;
520 #ifdef WIN32
521 else if (WSAGetLastError() != WSAEISCONN)
522 #else
523 else
524 #endif
526 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
527 return false;
530 return true;
533 bool SetProxy(enum Network net, const proxyType &addrProxy) {
534 assert(net >= 0 && net < NET_MAX);
535 if (!addrProxy.IsValid())
536 return false;
537 LOCK(cs_proxyInfos);
538 proxyInfo[net] = addrProxy;
539 return true;
542 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
543 assert(net >= 0 && net < NET_MAX);
544 LOCK(cs_proxyInfos);
545 if (!proxyInfo[net].IsValid())
546 return false;
547 proxyInfoOut = proxyInfo[net];
548 return true;
551 bool SetNameProxy(const proxyType &addrProxy) {
552 if (!addrProxy.IsValid())
553 return false;
554 LOCK(cs_proxyInfos);
555 nameProxy = addrProxy;
556 return true;
559 bool GetNameProxy(proxyType &nameProxyOut) {
560 LOCK(cs_proxyInfos);
561 if(!nameProxy.IsValid())
562 return false;
563 nameProxyOut = nameProxy;
564 return true;
567 bool HaveNameProxy() {
568 LOCK(cs_proxyInfos);
569 return nameProxy.IsValid();
572 bool IsProxy(const CNetAddr &addr) {
573 LOCK(cs_proxyInfos);
574 for (int i = 0; i < NET_MAX; i++) {
575 if (addr == (CNetAddr)proxyInfo[i].proxy)
576 return true;
578 return false;
581 bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, const SOCKET& hSocket, int nTimeout, bool *outProxyConnectionFailed)
583 // first connect to proxy server
584 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
585 if (outProxyConnectionFailed)
586 *outProxyConnectionFailed = true;
587 return false;
589 // do socks negotiation
590 if (proxy.randomize_credentials) {
591 ProxyCredentials random_auth;
592 static std::atomic_int counter(0);
593 random_auth.username = random_auth.password = strprintf("%i", counter++);
594 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) {
595 return false;
597 } else {
598 if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) {
599 return false;
602 return true;
604 bool LookupSubNet(const char* pszName, CSubNet& ret)
606 std::string strSubnet(pszName);
607 size_t slash = strSubnet.find_last_of('/');
608 std::vector<CNetAddr> vIP;
610 std::string strAddress = strSubnet.substr(0, slash);
611 if (LookupHost(strAddress.c_str(), vIP, 1, false))
613 CNetAddr network = vIP[0];
614 if (slash != strSubnet.npos)
616 std::string strNetmask = strSubnet.substr(slash + 1);
617 int32_t n;
618 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
619 if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
620 ret = CSubNet(network, n);
621 return ret.IsValid();
623 else // If not a valid number, try full netmask syntax
625 // Never allow lookup for netmask
626 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
627 ret = CSubNet(network, vIP[0]);
628 return ret.IsValid();
632 else
634 ret = CSubNet(network);
635 return ret.IsValid();
638 return false;
641 #ifdef WIN32
642 std::string NetworkErrorString(int err)
644 char buf[256];
645 buf[0] = 0;
646 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
647 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
648 buf, sizeof(buf), nullptr))
650 return strprintf("%s (%d)", buf, err);
652 else
654 return strprintf("Unknown error (%d)", err);
657 #else
658 std::string NetworkErrorString(int err)
660 char buf[256];
661 buf[0] = 0;
662 /* Too bad there are two incompatible implementations of the
663 * thread-safe strerror. */
664 const char *s;
665 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
666 s = strerror_r(err, buf, sizeof(buf));
667 #else /* POSIX variant always returns message in buffer */
668 s = buf;
669 if (strerror_r(err, buf, sizeof(buf)))
670 buf[0] = 0;
671 #endif
672 return strprintf("%s (%d)", s, err);
674 #endif
676 bool CloseSocket(SOCKET& hSocket)
678 if (hSocket == INVALID_SOCKET)
679 return false;
680 #ifdef WIN32
681 int ret = closesocket(hSocket);
682 #else
683 int ret = close(hSocket);
684 #endif
685 hSocket = INVALID_SOCKET;
686 return ret != SOCKET_ERROR;
689 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
691 if (fNonBlocking) {
692 #ifdef WIN32
693 u_long nOne = 1;
694 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
695 #else
696 int fFlags = fcntl(hSocket, F_GETFL, 0);
697 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
698 #endif
699 return false;
701 } else {
702 #ifdef WIN32
703 u_long nZero = 0;
704 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
705 #else
706 int fFlags = fcntl(hSocket, F_GETFL, 0);
707 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
708 #endif
709 return false;
713 return true;
716 bool SetSocketNoDelay(const SOCKET& hSocket)
718 int set = 1;
719 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
720 return rc == 0;
723 void InterruptSocks5(bool interrupt)
725 interruptSocks5Recv = interrupt;