Fix a vs. an typo
[bitcoinplatinum.git] / src / netbase.cpp
blob82040605c550a02fada85e58e2f78f827ed2baf8
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 #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 #include <atomic>
21 #ifndef WIN32
22 #include <fcntl.h>
23 #endif
25 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
26 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
28 #if !defined(HAVE_MSG_NOSIGNAL)
29 #define MSG_NOSIGNAL 0
30 #endif
32 // Settings
33 static proxyType proxyInfo[NET_MAX];
34 static proxyType nameProxy;
35 static CCriticalSection cs_proxyInfos;
36 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
37 bool fNameLookup = DEFAULT_NAME_LOOKUP;
39 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
40 static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
41 static std::atomic<bool> interruptSocks5Recv(false);
43 enum Network ParseNetwork(std::string net) {
44 boost::to_lower(net);
45 if (net == "ipv4") return NET_IPV4;
46 if (net == "ipv6") return NET_IPV6;
47 if (net == "tor" || net == "onion") return NET_TOR;
48 return NET_UNROUTABLE;
51 std::string GetNetworkName(enum Network net) {
52 switch(net)
54 case NET_IPV4: return "ipv4";
55 case NET_IPV6: return "ipv6";
56 case NET_TOR: return "onion";
57 default: return "";
61 bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
63 vIP.clear();
66 CNetAddr addr;
67 if (addr.SetSpecial(std::string(pszName))) {
68 vIP.push_back(addr);
69 return true;
73 struct addrinfo aiHint;
74 memset(&aiHint, 0, sizeof(struct addrinfo));
76 aiHint.ai_socktype = SOCK_STREAM;
77 aiHint.ai_protocol = IPPROTO_TCP;
78 aiHint.ai_family = AF_UNSPEC;
79 #ifdef WIN32
80 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
81 #else
82 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
83 #endif
84 struct addrinfo *aiRes = nullptr;
85 int nErr = getaddrinfo(pszName, nullptr, &aiHint, &aiRes);
86 if (nErr)
87 return false;
89 struct addrinfo *aiTrav = aiRes;
90 while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
92 CNetAddr resolved;
93 if (aiTrav->ai_family == AF_INET)
95 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
96 resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr);
99 if (aiTrav->ai_family == AF_INET6)
101 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
102 struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
103 resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id);
105 /* Never allow resolving to an internal address. Consider any such result invalid */
106 if (!resolved.IsInternal()) {
107 vIP.push_back(resolved);
110 aiTrav = aiTrav->ai_next;
113 freeaddrinfo(aiRes);
115 return (vIP.size() > 0);
118 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
120 std::string strHost(pszName);
121 if (strHost.empty())
122 return false;
123 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
125 strHost = strHost.substr(1, strHost.size() - 2);
128 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
131 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
133 std::vector<CNetAddr> vIP;
134 LookupHost(pszName, vIP, 1, fAllowLookup);
135 if(vIP.empty())
136 return false;
137 addr = vIP.front();
138 return true;
141 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
143 if (pszName[0] == 0)
144 return false;
145 int port = portDefault;
146 std::string hostname = "";
147 SplitHostPort(std::string(pszName), port, hostname);
149 std::vector<CNetAddr> vIP;
150 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
151 if (!fRet)
152 return false;
153 vAddr.resize(vIP.size());
154 for (unsigned int i = 0; i < vIP.size(); i++)
155 vAddr[i] = CService(vIP[i], port);
156 return true;
159 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
161 std::vector<CService> vService;
162 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
163 if (!fRet)
164 return false;
165 addr = vService[0];
166 return true;
169 CService LookupNumeric(const char *pszName, int portDefault)
171 CService addr;
172 // "1.2:345" will fail to resolve the ip, but will still set the port.
173 // If the ip fails to resolve, re-init the result.
174 if(!Lookup(pszName, addr, portDefault, false))
175 addr = CService();
176 return addr;
179 struct timeval MillisToTimeval(int64_t nTimeout)
181 struct timeval timeout;
182 timeout.tv_sec = nTimeout / 1000;
183 timeout.tv_usec = (nTimeout % 1000) * 1000;
184 return timeout;
187 /** SOCKS version */
188 enum SOCKSVersion: uint8_t {
189 SOCKS4 = 0x04,
190 SOCKS5 = 0x05
193 /** Values defined for METHOD in RFC1928 */
194 enum SOCKS5Method: uint8_t {
195 NOAUTH = 0x00, //! No authentication required
196 GSSAPI = 0x01, //! GSSAPI
197 USER_PASS = 0x02, //! Username/password
198 NO_ACCEPTABLE = 0xff, //! No acceptable methods
201 /** Values defined for CMD in RFC1928 */
202 enum SOCKS5Command: uint8_t {
203 CONNECT = 0x01,
204 BIND = 0x02,
205 UDP_ASSOCIATE = 0x03
208 /** Values defined for REP in RFC1928 */
209 enum SOCKS5Reply: uint8_t {
210 SUCCEEDED = 0x00, //! Succeeded
211 GENFAILURE = 0x01, //! General failure
212 NOTALLOWED = 0x02, //! Connection not allowed by ruleset
213 NETUNREACHABLE = 0x03, //! Network unreachable
214 HOSTUNREACHABLE = 0x04, //! Network unreachable
215 CONNREFUSED = 0x05, //! Connection refused
216 TTLEXPIRED = 0x06, //! TTL expired
217 CMDUNSUPPORTED = 0x07, //! Command not supported
218 ATYPEUNSUPPORTED = 0x08, //! Address type not supported
221 /** Values defined for ATYPE in RFC1928 */
222 enum SOCKS5Atyp: uint8_t {
223 IPV4 = 0x01,
224 DOMAINNAME = 0x03,
225 IPV6 = 0x04,
228 /** Status codes that can be returned by InterruptibleRecv */
229 enum class IntrRecvError {
231 Timeout,
232 Disconnected,
233 NetworkError,
234 Interrupted
238 * Read bytes from socket. This will either read the full number of bytes requested
239 * or return False on error or timeout.
240 * This function can be interrupted by calling InterruptSocks5()
242 * @param data Buffer to receive into
243 * @param len Length of data to receive
244 * @param timeout Timeout in milliseconds for receive operation
246 * @note This function requires that hSocket is in non-blocking mode.
248 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket)
250 int64_t curTime = GetTimeMillis();
251 int64_t endTime = curTime + timeout;
252 // Maximum time to wait in one select call. It will take up until this time (in millis)
253 // to break off in case of an interruption.
254 const int64_t maxWait = 1000;
255 while (len > 0 && curTime < endTime) {
256 ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first
257 if (ret > 0) {
258 len -= ret;
259 data += ret;
260 } else if (ret == 0) { // Unexpected disconnection
261 return IntrRecvError::Disconnected;
262 } else { // Other error or blocking
263 int nErr = WSAGetLastError();
264 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
265 if (!IsSelectableSocket(hSocket)) {
266 return IntrRecvError::NetworkError;
268 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
269 fd_set fdset;
270 FD_ZERO(&fdset);
271 FD_SET(hSocket, &fdset);
272 int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval);
273 if (nRet == SOCKET_ERROR) {
274 return IntrRecvError::NetworkError;
276 } else {
277 return IntrRecvError::NetworkError;
280 if (interruptSocks5Recv)
281 return IntrRecvError::Interrupted;
282 curTime = GetTimeMillis();
284 return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
287 /** Credentials for proxy authentication */
288 struct ProxyCredentials
290 std::string username;
291 std::string password;
294 /** Convert SOCKS5 reply to an error message */
295 std::string Socks5ErrorString(uint8_t err)
297 switch(err) {
298 case SOCKS5Reply::GENFAILURE:
299 return "general failure";
300 case SOCKS5Reply::NOTALLOWED:
301 return "connection not allowed";
302 case SOCKS5Reply::NETUNREACHABLE:
303 return "network unreachable";
304 case SOCKS5Reply::HOSTUNREACHABLE:
305 return "host unreachable";
306 case SOCKS5Reply::CONNREFUSED:
307 return "connection refused";
308 case SOCKS5Reply::TTLEXPIRED:
309 return "TTL expired";
310 case SOCKS5Reply::CMDUNSUPPORTED:
311 return "protocol error";
312 case SOCKS5Reply::ATYPEUNSUPPORTED:
313 return "address type not supported";
314 default:
315 return "unknown";
319 /** Connect using SOCKS5 (as described in RFC1928) */
320 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
322 IntrRecvError recvr;
323 LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
324 if (strDest.size() > 255) {
325 CloseSocket(hSocket);
326 return error("Hostname too long");
328 // Accepted authentication methods
329 std::vector<uint8_t> vSocks5Init;
330 vSocks5Init.push_back(SOCKSVersion::SOCKS5);
331 if (auth) {
332 vSocks5Init.push_back(0x02); // Number of methods
333 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
334 vSocks5Init.push_back(SOCKS5Method::USER_PASS);
335 } else {
336 vSocks5Init.push_back(0x01); // Number of methods
337 vSocks5Init.push_back(SOCKS5Method::NOAUTH);
339 ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
340 if (ret != (ssize_t)vSocks5Init.size()) {
341 CloseSocket(hSocket);
342 return error("Error sending to proxy");
344 uint8_t pchRet1[2];
345 if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
346 CloseSocket(hSocket);
347 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
348 return false;
350 if (pchRet1[0] != SOCKSVersion::SOCKS5) {
351 CloseSocket(hSocket);
352 return error("Proxy failed to initialize");
354 if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
355 // Perform username/password authentication (as described in RFC1929)
356 std::vector<uint8_t> vAuth;
357 vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
358 if (auth->username.size() > 255 || auth->password.size() > 255)
359 return error("Proxy username or password too long");
360 vAuth.push_back(auth->username.size());
361 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
362 vAuth.push_back(auth->password.size());
363 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
364 ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
365 if (ret != (ssize_t)vAuth.size()) {
366 CloseSocket(hSocket);
367 return error("Error sending authentication to proxy");
369 LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
370 uint8_t pchRetA[2];
371 if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
372 CloseSocket(hSocket);
373 return error("Error reading proxy authentication response");
375 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
376 CloseSocket(hSocket);
377 return error("Proxy authentication unsuccessful");
379 } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
380 // Perform no authentication
381 } else {
382 CloseSocket(hSocket);
383 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
385 std::vector<uint8_t> vSocks5;
386 vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
387 vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
388 vSocks5.push_back(0x00); // RSV Reserved must be 0
389 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
390 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
391 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
392 vSocks5.push_back((port >> 8) & 0xFF);
393 vSocks5.push_back((port >> 0) & 0xFF);
394 ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
395 if (ret != (ssize_t)vSocks5.size()) {
396 CloseSocket(hSocket);
397 return error("Error sending to proxy");
399 uint8_t pchRet2[4];
400 if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
401 CloseSocket(hSocket);
402 if (recvr == IntrRecvError::Timeout) {
403 /* If a timeout happens here, this effectively means we timed out while connecting
404 * to the remote node. This is very common for Tor, so do not print an
405 * error message. */
406 return false;
407 } else {
408 return error("Error while reading proxy response");
411 if (pchRet2[0] != SOCKSVersion::SOCKS5) {
412 CloseSocket(hSocket);
413 return error("Proxy failed to accept request");
415 if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
416 // Failures to connect to a peer that are not proxy errors
417 CloseSocket(hSocket);
418 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
419 return false;
421 if (pchRet2[2] != 0x00) { // Reserved field must be 0
422 CloseSocket(hSocket);
423 return error("Error: malformed proxy response");
425 uint8_t pchRet3[256];
426 switch (pchRet2[3])
428 case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
429 case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
430 case SOCKS5Atyp::DOMAINNAME:
432 recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
433 if (recvr != IntrRecvError::OK) {
434 CloseSocket(hSocket);
435 return error("Error reading from proxy");
437 int nRecv = pchRet3[0];
438 recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
439 break;
441 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
443 if (recvr != IntrRecvError::OK) {
444 CloseSocket(hSocket);
445 return error("Error reading from proxy");
447 if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
448 CloseSocket(hSocket);
449 return error("Error reading from proxy");
451 LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
452 return true;
455 bool ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
457 hSocketRet = INVALID_SOCKET;
459 struct sockaddr_storage sockaddr;
460 socklen_t len = sizeof(sockaddr);
461 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
462 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
463 return false;
466 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
467 if (hSocket == INVALID_SOCKET)
468 return false;
470 #ifdef SO_NOSIGPIPE
471 int set = 1;
472 // Different way of disabling SIGPIPE on BSD
473 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
474 #endif
476 //Disable Nagle's algorithm
477 SetSocketNoDelay(hSocket);
479 // Set to non-blocking
480 if (!SetSocketNonBlocking(hSocket, true)) {
481 CloseSocket(hSocket);
482 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
485 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
487 int nErr = WSAGetLastError();
488 // WSAEINVAL is here because some legacy version of winsock uses it
489 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
491 struct timeval timeout = MillisToTimeval(nTimeout);
492 fd_set fdset;
493 FD_ZERO(&fdset);
494 FD_SET(hSocket, &fdset);
495 int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout);
496 if (nRet == 0)
498 LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
499 CloseSocket(hSocket);
500 return false;
502 if (nRet == SOCKET_ERROR)
504 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
505 CloseSocket(hSocket);
506 return false;
508 socklen_t nRetSize = sizeof(nRet);
509 #ifdef WIN32
510 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
511 #else
512 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
513 #endif
515 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
516 CloseSocket(hSocket);
517 return false;
519 if (nRet != 0)
521 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
522 CloseSocket(hSocket);
523 return false;
526 #ifdef WIN32
527 else if (WSAGetLastError() != WSAEISCONN)
528 #else
529 else
530 #endif
532 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
533 CloseSocket(hSocket);
534 return false;
538 hSocketRet = hSocket;
539 return true;
542 bool SetProxy(enum Network net, const proxyType &addrProxy) {
543 assert(net >= 0 && net < NET_MAX);
544 if (!addrProxy.IsValid())
545 return false;
546 LOCK(cs_proxyInfos);
547 proxyInfo[net] = addrProxy;
548 return true;
551 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
552 assert(net >= 0 && net < NET_MAX);
553 LOCK(cs_proxyInfos);
554 if (!proxyInfo[net].IsValid())
555 return false;
556 proxyInfoOut = proxyInfo[net];
557 return true;
560 bool SetNameProxy(const proxyType &addrProxy) {
561 if (!addrProxy.IsValid())
562 return false;
563 LOCK(cs_proxyInfos);
564 nameProxy = addrProxy;
565 return true;
568 bool GetNameProxy(proxyType &nameProxyOut) {
569 LOCK(cs_proxyInfos);
570 if(!nameProxy.IsValid())
571 return false;
572 nameProxyOut = nameProxy;
573 return true;
576 bool HaveNameProxy() {
577 LOCK(cs_proxyInfos);
578 return nameProxy.IsValid();
581 bool IsProxy(const CNetAddr &addr) {
582 LOCK(cs_proxyInfos);
583 for (int i = 0; i < NET_MAX; i++) {
584 if (addr == (CNetAddr)proxyInfo[i].proxy)
585 return true;
587 return false;
590 bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
592 SOCKET hSocket = INVALID_SOCKET;
593 // first connect to proxy server
594 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
595 if (outProxyConnectionFailed)
596 *outProxyConnectionFailed = true;
597 return false;
599 // do socks negotiation
600 if (proxy.randomize_credentials) {
601 ProxyCredentials random_auth;
602 static std::atomic_int counter(0);
603 random_auth.username = random_auth.password = strprintf("%i", counter++);
604 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
605 return false;
606 } else {
607 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
608 return false;
611 hSocketRet = hSocket;
612 return true;
614 bool LookupSubNet(const char* pszName, CSubNet& ret)
616 std::string strSubnet(pszName);
617 size_t slash = strSubnet.find_last_of('/');
618 std::vector<CNetAddr> vIP;
620 std::string strAddress = strSubnet.substr(0, slash);
621 if (LookupHost(strAddress.c_str(), vIP, 1, false))
623 CNetAddr network = vIP[0];
624 if (slash != strSubnet.npos)
626 std::string strNetmask = strSubnet.substr(slash + 1);
627 int32_t n;
628 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
629 if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
630 ret = CSubNet(network, n);
631 return ret.IsValid();
633 else // If not a valid number, try full netmask syntax
635 // Never allow lookup for netmask
636 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
637 ret = CSubNet(network, vIP[0]);
638 return ret.IsValid();
642 else
644 ret = CSubNet(network);
645 return ret.IsValid();
648 return false;
651 #ifdef WIN32
652 std::string NetworkErrorString(int err)
654 char buf[256];
655 buf[0] = 0;
656 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
657 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
658 buf, sizeof(buf), nullptr))
660 return strprintf("%s (%d)", buf, err);
662 else
664 return strprintf("Unknown error (%d)", err);
667 #else
668 std::string NetworkErrorString(int err)
670 char buf[256];
671 buf[0] = 0;
672 /* Too bad there are two incompatible implementations of the
673 * thread-safe strerror. */
674 const char *s;
675 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
676 s = strerror_r(err, buf, sizeof(buf));
677 #else /* POSIX variant always returns message in buffer */
678 s = buf;
679 if (strerror_r(err, buf, sizeof(buf)))
680 buf[0] = 0;
681 #endif
682 return strprintf("%s (%d)", s, err);
684 #endif
686 bool CloseSocket(SOCKET& hSocket)
688 if (hSocket == INVALID_SOCKET)
689 return false;
690 #ifdef WIN32
691 int ret = closesocket(hSocket);
692 #else
693 int ret = close(hSocket);
694 #endif
695 hSocket = INVALID_SOCKET;
696 return ret != SOCKET_ERROR;
699 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
701 if (fNonBlocking) {
702 #ifdef WIN32
703 u_long nOne = 1;
704 if (ioctlsocket(hSocket, FIONBIO, &nOne) == 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;
711 } else {
712 #ifdef WIN32
713 u_long nZero = 0;
714 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
715 #else
716 int fFlags = fcntl(hSocket, F_GETFL, 0);
717 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
718 #endif
719 return false;
723 return true;
726 bool SetSocketNoDelay(const SOCKET& hSocket)
728 int set = 1;
729 int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
730 return rc == 0;
733 void InterruptSocks5(bool interrupt)
735 interruptSocks5Recv = interrupt;