Merge #11854: Split up key and script metadata for better type safety
[bitcoinplatinum.git] / src / netbase.cpp
blobda3729b286cb349fdfa44aaa323ec52f4b8902f0
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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, SOCKET& hSocket)
318 IntrRecvError recvr;
319 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
320 if (strDest.size() > 255) {
321 CloseSocket(hSocket);
322 return error("Hostname too long");
324 // Accepted authentication methods
325 std::vector<uint8_t> vSocks5Init;
326 vSocks5Init.push_back(SOCKSVersion::SOCKS5);
327 if (auth) {
328 vSocks5Init.push_back(0x02); // Number of methods
329 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
330 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
331 } else {
332 vSocks5Init.push_back(0x01); // Number of methods
333 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
335 ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
336 if (ret != (ssize_t)vSocks5Init.size()) {
337 CloseSocket(hSocket);
338 return error("Error sending to proxy");
340 uint8_t pchRet1[2];
341 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
342 CloseSocket(hSocket);
343 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
344 return false;
346 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
347 CloseSocket(hSocket);
348 return error("Proxy failed to initialize");
350 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
351 // Perform username/password authentication (as described in RFC1929)
352 std::vector<uint8_t> vAuth;
353 vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
354 if (auth->username.size() > 255 || auth->password.size() > 255)
355 return error("Proxy username or password too long");
356 vAuth.push_back(auth->username.size());
357 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
358 vAuth.push_back(auth->password.size());
359 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
360 ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
361 if (ret != (ssize_t)vAuth.size()) {
362 CloseSocket(hSocket);
363 return error("Error sending authentication to proxy");
365 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
366 uint8_t pchRetA[2];
367 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
368 CloseSocket(hSocket);
369 return error("Error reading proxy authentication response");
371 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
372 CloseSocket(hSocket);
373 return error("Proxy authentication unsuccessful");
375 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
376 // Perform no authentication
377 } else {
378 CloseSocket(hSocket);
379 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
381 std::vector<uint8_t> vSocks5;
382 vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
383 vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
384 vSocks5.push_back(0x00); // RSV Reserved must be 0
385 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
386 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
387 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
388 vSocks5.push_back((port >> 8) & 0xFF);
389 vSocks5.push_back((port >> 0) & 0xFF);
390 ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
391 if (ret != (ssize_t)vSocks5.size()) {
392 CloseSocket(hSocket);
393 return error("Error sending to proxy");
395 uint8_t pchRet2[4];
396 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
397 CloseSocket(hSocket);
398 if (recvr == IntrRecvError::Timeout) {
399 /* If a timeout happens here, this effectively means we timed out while connecting
400 * to the remote node. This is very common for Tor, so do not print an
401 * error message. */
402 return false;
403 } else {
404 return error("Error while reading proxy response");
407 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
408 CloseSocket(hSocket);
409 return error("Proxy failed to accept request");
411 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
412 // Failures to connect to a peer that are not proxy errors
413 CloseSocket(hSocket);
414 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
415 return false;
417 if (pchRet2[2] != 0x00) { // Reserved field must be 0
418 CloseSocket(hSocket);
419 return error("Error: malformed proxy response");
421 uint8_t pchRet3[256];
422 switch (pchRet2[3])
424 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
425 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
426 case SOCKS5Atyp::DOMAINNAME:
428 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
429 if (recvr != IntrRecvError::OK) {
430 CloseSocket(hSocket);
431 return error("Error reading from proxy");
433 int nRecv = pchRet3[0];
434 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
435 break;
437 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
439 if (recvr != IntrRecvError::OK) {
440 CloseSocket(hSocket);
441 return error("Error reading from proxy");
443 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
444 CloseSocket(hSocket);
445 return error("Error reading from proxy");
447 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
448 return true;
451 bool ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
453 hSocketRet = INVALID_SOCKET;
455 struct sockaddr_storage sockaddr;
456 socklen_t len = sizeof(sockaddr);
457 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
458 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
459 return false;
462 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
463 if (hSocket == INVALID_SOCKET)
464 return false;
466 #ifdef SO_NOSIGPIPE
467 int set = 1;
468 // Different way of disabling SIGPIPE on BSD
469 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
470 #endif
472 //Disable Nagle's algorithm
473 SetSocketNoDelay(hSocket);
475 // Set to non-blocking
476 if (!SetSocketNonBlocking(hSocket, true)) {
477 CloseSocket(hSocket);
478 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
481 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
483 int nErr = WSAGetLastError();
484 // WSAEINVAL is here because some legacy version of winsock uses it
485 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
487 struct timeval timeout = MillisToTimeval(nTimeout);
488 fd_set fdset;
489 FD_ZERO(&fdset);
490 FD_SET(hSocket, &fdset);
491 int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
492 if (nRet == 0)
494 LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
495 CloseSocket(hSocket);
496 return false;
498 if (nRet == SOCKET_ERROR)
500 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
501 CloseSocket(hSocket);
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 CloseSocket(hSocket);
513 return false;
515 if (nRet != 0)
517 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
518 CloseSocket(hSocket);
519 return false;
522 #ifdef WIN32
523 else if (WSAGetLastError() != WSAEISCONN)
524 #else
525 else
526 #endif
528 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
529 CloseSocket(hSocket);
530 return false;
534 hSocketRet = hSocket;
535 return true;
538 bool SetProxy(enum Network net, const proxyType &addrProxy) {
539 assert(net >= 0 && net < NET_MAX);
540 if (!addrProxy.IsValid())
541 return false;
542 LOCK(cs_proxyInfos);
543 proxyInfo[net] = addrProxy;
544 return true;
547 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
548 assert(net >= 0 && net < NET_MAX);
549 LOCK(cs_proxyInfos);
550 if (!proxyInfo[net].IsValid())
551 return false;
552 proxyInfoOut = proxyInfo[net];
553 return true;
556 bool SetNameProxy(const proxyType &addrProxy) {
557 if (!addrProxy.IsValid())
558 return false;
559 LOCK(cs_proxyInfos);
560 nameProxy = addrProxy;
561 return true;
564 bool GetNameProxy(proxyType &nameProxyOut) {
565 LOCK(cs_proxyInfos);
566 if(!nameProxy.IsValid())
567 return false;
568 nameProxyOut = nameProxy;
569 return true;
572 bool HaveNameProxy() {
573 LOCK(cs_proxyInfos);
574 return nameProxy.IsValid();
577 bool IsProxy(const CNetAddr &addr) {
578 LOCK(cs_proxyInfos);
579 for (int i = 0; i < NET_MAX; i++) {
580 if (addr == (CNetAddr)proxyInfo[i].proxy)
581 return true;
583 return false;
586 bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
588 SOCKET hSocket = INVALID_SOCKET;
589 // first connect to proxy server
590 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
591 if (outProxyConnectionFailed)
592 *outProxyConnectionFailed = true;
593 return false;
595 // do socks negotiation
596 if (proxy.randomize_credentials) {
597 ProxyCredentials random_auth;
598 static std::atomic_int counter(0);
599 random_auth.username = random_auth.password = strprintf("%i", counter++);
600 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
601 return false;
602 } else {
603 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
604 return false;
607 hSocketRet = hSocket;
608 return true;
610 bool LookupSubNet(const char* pszName, CSubNet& ret)
612 std::string strSubnet(pszName);
613 size_t slash = strSubnet.find_last_of('/');
614 std::vector<CNetAddr> vIP;
616 std::string strAddress = strSubnet.substr(0, slash);
617 if (LookupHost(strAddress.c_str(), vIP, 1, false))
619 CNetAddr network = vIP[0];
620 if (slash != strSubnet.npos)
622 std::string strNetmask = strSubnet.substr(slash + 1);
623 int32_t n;
624 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
625 if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
626 ret = CSubNet(network, n);
627 return ret.IsValid();
629 else // If not a valid number, try full netmask syntax
631 // Never allow lookup for netmask
632 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
633 ret = CSubNet(network, vIP[0]);
634 return ret.IsValid();
638 else
640 ret = CSubNet(network);
641 return ret.IsValid();
644 return false;
647 #ifdef WIN32
648 std::string NetworkErrorString(int err)
650 char buf[256];
651 buf[0] = 0;
652 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
653 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
654 buf, sizeof(buf), nullptr))
656 return strprintf("%s (%d)", buf, err);
658 else
660 return strprintf("Unknown error (%d)", err);
663 #else
664 std::string NetworkErrorString(int err)
666 char buf[256];
667 buf[0] = 0;
668 /* Too bad there are two incompatible implementations of the
669 * thread-safe strerror. */
670 const char *s;
671 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
672 s = strerror_r(err, buf, sizeof(buf));
673 #else /* POSIX variant always returns message in buffer */
674 s = buf;
675 if (strerror_r(err, buf, sizeof(buf)))
676 buf[0] = 0;
677 #endif
678 return strprintf("%s (%d)", s, err);
680 #endif
682 bool CloseSocket(SOCKET& hSocket)
684 if (hSocket == INVALID_SOCKET)
685 return false;
686 #ifdef WIN32
687 int ret = closesocket(hSocket);
688 #else
689 int ret = close(hSocket);
690 #endif
691 hSocket = INVALID_SOCKET;
692 return ret != SOCKET_ERROR;
695 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
697 if (fNonBlocking) {
698 #ifdef WIN32
699 u_long nOne = 1;
700 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
701 #else
702 int fFlags = fcntl(hSocket, F_GETFL, 0);
703 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
704 #endif
705 return false;
707 } else {
708 #ifdef WIN32
709 u_long nZero = 0;
710 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
711 #else
712 int fFlags = fcntl(hSocket, F_GETFL, 0);
713 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
714 #endif
715 return false;
719 return true;
722 bool SetSocketNoDelay(const SOCKET& hSocket)
724 int set = 1;
725 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
726 return rc == 0;
729 void InterruptSocks5(bool interrupt)
731 interruptSocks5Recv = interrupt;