Merge #9268: Fix rounding privacy leak introduced in #9260
[bitcoinplatinum.git] / src / netbase.cpp
blob9118584b80c4461462d71b184688607fa1cccec4
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 struct addrinfo aiHint;
98 memset(&aiHint, 0, sizeof(struct addrinfo));
100 aiHint.ai_socktype = SOCK_STREAM;
101 aiHint.ai_protocol = IPPROTO_TCP;
102 aiHint.ai_family = AF_UNSPEC;
103 #ifdef WIN32
104 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
105 #else
106 aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
107 #endif
108 struct addrinfo *aiRes = NULL;
109 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
110 if (nErr)
111 return false;
113 struct addrinfo *aiTrav = aiRes;
114 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
116 if (aiTrav->ai_family == AF_INET)
118 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
119 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
122 if (aiTrav->ai_family == AF_INET6)
124 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
125 struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr;
126 vIP.push_back(CNetAddr(s6->sin6_addr, s6->sin6_scope_id));
129 aiTrav = aiTrav->ai_next;
132 freeaddrinfo(aiRes);
134 return (vIP.size() > 0);
137 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
139 std::string strHost(pszName);
140 if (strHost.empty())
141 return false;
142 if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
144 strHost = strHost.substr(1, strHost.size() - 2);
147 return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
150 bool LookupHost(const char *pszName, CNetAddr& addr, bool fAllowLookup)
152 std::vector<CNetAddr> vIP;
153 LookupHost(pszName, vIP, 1, fAllowLookup);
154 if(vIP.empty())
155 return false;
156 addr = vIP.front();
157 return true;
160 bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
162 if (pszName[0] == 0)
163 return false;
164 int port = portDefault;
165 std::string hostname = "";
166 SplitHostPort(std::string(pszName), port, hostname);
168 std::vector<CNetAddr> vIP;
169 bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
170 if (!fRet)
171 return false;
172 vAddr.resize(vIP.size());
173 for (unsigned int i = 0; i < vIP.size(); i++)
174 vAddr[i] = CService(vIP[i], port);
175 return true;
178 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
180 std::vector<CService> vService;
181 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
182 if (!fRet)
183 return false;
184 addr = vService[0];
185 return true;
188 CService LookupNumeric(const char *pszName, int portDefault)
190 CService addr;
191 // "1.2:345" will fail to resolve the ip, but will still set the port.
192 // If the ip fails to resolve, re-init the result.
193 if(!Lookup(pszName, addr, portDefault, false))
194 addr = CService();
195 return addr;
198 struct timeval MillisToTimeval(int64_t nTimeout)
200 struct timeval timeout;
201 timeout.tv_sec = nTimeout / 1000;
202 timeout.tv_usec = (nTimeout % 1000) * 1000;
203 return timeout;
207 * Read bytes from socket. This will either read the full number of bytes requested
208 * or return False on error or timeout.
209 * This function can be interrupted by boost thread interrupt.
211 * @param data Buffer to receive into
212 * @param len Length of data to receive
213 * @param timeout Timeout in milliseconds for receive operation
215 * @note This function requires that hSocket is in non-blocking mode.
217 bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
219 int64_t curTime = GetTimeMillis();
220 int64_t endTime = curTime + timeout;
221 // Maximum time to wait in one select call. It will take up until this time (in millis)
222 // to break off in case of an interruption.
223 const int64_t maxWait = 1000;
224 while (len > 0 && curTime < endTime) {
225 ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
226 if (ret > 0) {
227 len -= ret;
228 data += ret;
229 } else if (ret == 0) { // Unexpected disconnection
230 return false;
231 } else { // Other error or blocking
232 int nErr = WSAGetLastError();
233 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
234 if (!IsSelectableSocket(hSocket)) {
235 return false;
237 struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
238 fd_set fdset;
239 FD_ZERO(&fdset);
240 FD_SET(hSocket, &fdset);
241 int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
242 if (nRet == SOCKET_ERROR) {
243 return false;
245 } else {
246 return false;
249 boost::this_thread::interruption_point();
250 curTime = GetTimeMillis();
252 return len == 0;
255 struct ProxyCredentials
257 std::string username;
258 std::string password;
261 std::string Socks5ErrorString(int err)
263 switch(err) {
264 case 0x01: return "general failure";
265 case 0x02: return "connection not allowed";
266 case 0x03: return "network unreachable";
267 case 0x04: return "host unreachable";
268 case 0x05: return "connection refused";
269 case 0x06: return "TTL expired";
270 case 0x07: return "protocol error";
271 case 0x08: return "address type not supported";
272 default: return "unknown";
276 /** Connect using SOCKS5 (as described in RFC1928) */
277 static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
279 LogPrint("net", "SOCKS5 connecting %s\n", strDest);
280 if (strDest.size() > 255) {
281 CloseSocket(hSocket);
282 return error("Hostname too long");
284 // Accepted authentication methods
285 std::vector<uint8_t> vSocks5Init;
286 vSocks5Init.push_back(0x05);
287 if (auth) {
288 vSocks5Init.push_back(0x02); // # METHODS
289 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
290 vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
291 } else {
292 vSocks5Init.push_back(0x01); // # METHODS
293 vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
295 ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
296 if (ret != (ssize_t)vSocks5Init.size()) {
297 CloseSocket(hSocket);
298 return error("Error sending to proxy");
300 char pchRet1[2];
301 if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
302 CloseSocket(hSocket);
303 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
304 return false;
306 if (pchRet1[0] != 0x05) {
307 CloseSocket(hSocket);
308 return error("Proxy failed to initialize");
310 if (pchRet1[1] == 0x02 && auth) {
311 // Perform username/password authentication (as described in RFC1929)
312 std::vector<uint8_t> vAuth;
313 vAuth.push_back(0x01);
314 if (auth->username.size() > 255 || auth->password.size() > 255)
315 return error("Proxy username or password too long");
316 vAuth.push_back(auth->username.size());
317 vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
318 vAuth.push_back(auth->password.size());
319 vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
320 ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
321 if (ret != (ssize_t)vAuth.size()) {
322 CloseSocket(hSocket);
323 return error("Error sending authentication to proxy");
325 LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
326 char pchRetA[2];
327 if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
328 CloseSocket(hSocket);
329 return error("Error reading proxy authentication response");
331 if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
332 CloseSocket(hSocket);
333 return error("Proxy authentication unsuccessful");
335 } else if (pchRet1[1] == 0x00) {
336 // Perform no authentication
337 } else {
338 CloseSocket(hSocket);
339 return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
341 std::vector<uint8_t> vSocks5;
342 vSocks5.push_back(0x05); // VER protocol version
343 vSocks5.push_back(0x01); // CMD CONNECT
344 vSocks5.push_back(0x00); // RSV Reserved
345 vSocks5.push_back(0x03); // ATYP DOMAINNAME
346 vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
347 vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
348 vSocks5.push_back((port >> 8) & 0xFF);
349 vSocks5.push_back((port >> 0) & 0xFF);
350 ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
351 if (ret != (ssize_t)vSocks5.size()) {
352 CloseSocket(hSocket);
353 return error("Error sending to proxy");
355 char pchRet2[4];
356 if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
357 CloseSocket(hSocket);
358 return error("Error reading proxy response");
360 if (pchRet2[0] != 0x05) {
361 CloseSocket(hSocket);
362 return error("Proxy failed to accept request");
364 if (pchRet2[1] != 0x00) {
365 // Failures to connect to a peer that are not proxy errors
366 CloseSocket(hSocket);
367 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
368 return false;
370 if (pchRet2[2] != 0x00) {
371 CloseSocket(hSocket);
372 return error("Error: malformed proxy response");
374 char pchRet3[256];
375 switch (pchRet2[3])
377 case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
378 case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
379 case 0x03:
381 ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
382 if (!ret) {
383 CloseSocket(hSocket);
384 return error("Error reading from proxy");
386 int nRecv = pchRet3[0];
387 ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
388 break;
390 default: CloseSocket(hSocket); return error("Error: malformed proxy response");
392 if (!ret) {
393 CloseSocket(hSocket);
394 return error("Error reading from proxy");
396 if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
397 CloseSocket(hSocket);
398 return error("Error reading from proxy");
400 LogPrint("net", "SOCKS5 connected %s\n", strDest);
401 return true;
404 bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
406 hSocketRet = INVALID_SOCKET;
408 struct sockaddr_storage sockaddr;
409 socklen_t len = sizeof(sockaddr);
410 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
411 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
412 return false;
415 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
416 if (hSocket == INVALID_SOCKET)
417 return false;
419 int set = 1;
420 #ifdef SO_NOSIGPIPE
421 // Different way of disabling SIGPIPE on BSD
422 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
423 #endif
425 //Disable Nagle's algorithm
426 #ifdef WIN32
427 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
428 #else
429 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
430 #endif
432 // Set to non-blocking
433 if (!SetSocketNonBlocking(hSocket, true))
434 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
436 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
438 int nErr = WSAGetLastError();
439 // WSAEINVAL is here because some legacy version of winsock uses it
440 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
442 struct timeval timeout = MillisToTimeval(nTimeout);
443 fd_set fdset;
444 FD_ZERO(&fdset);
445 FD_SET(hSocket, &fdset);
446 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
447 if (nRet == 0)
449 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
450 CloseSocket(hSocket);
451 return false;
453 if (nRet == SOCKET_ERROR)
455 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
456 CloseSocket(hSocket);
457 return false;
459 socklen_t nRetSize = sizeof(nRet);
460 #ifdef WIN32
461 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
462 #else
463 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
464 #endif
466 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
467 CloseSocket(hSocket);
468 return false;
470 if (nRet != 0)
472 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
473 CloseSocket(hSocket);
474 return false;
477 #ifdef WIN32
478 else if (WSAGetLastError() != WSAEISCONN)
479 #else
480 else
481 #endif
483 LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
484 CloseSocket(hSocket);
485 return false;
489 hSocketRet = hSocket;
490 return true;
493 bool SetProxy(enum Network net, const proxyType &addrProxy) {
494 assert(net >= 0 && net < NET_MAX);
495 if (!addrProxy.IsValid())
496 return false;
497 LOCK(cs_proxyInfos);
498 proxyInfo[net] = addrProxy;
499 return true;
502 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
503 assert(net >= 0 && net < NET_MAX);
504 LOCK(cs_proxyInfos);
505 if (!proxyInfo[net].IsValid())
506 return false;
507 proxyInfoOut = proxyInfo[net];
508 return true;
511 bool SetNameProxy(const proxyType &addrProxy) {
512 if (!addrProxy.IsValid())
513 return false;
514 LOCK(cs_proxyInfos);
515 nameProxy = addrProxy;
516 return true;
519 bool GetNameProxy(proxyType &nameProxyOut) {
520 LOCK(cs_proxyInfos);
521 if(!nameProxy.IsValid())
522 return false;
523 nameProxyOut = nameProxy;
524 return true;
527 bool HaveNameProxy() {
528 LOCK(cs_proxyInfos);
529 return nameProxy.IsValid();
532 bool IsProxy(const CNetAddr &addr) {
533 LOCK(cs_proxyInfos);
534 for (int i = 0; i < NET_MAX; i++) {
535 if (addr == (CNetAddr)proxyInfo[i].proxy)
536 return true;
538 return false;
541 static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
543 SOCKET hSocket = INVALID_SOCKET;
544 // first connect to proxy server
545 if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
546 if (outProxyConnectionFailed)
547 *outProxyConnectionFailed = true;
548 return false;
550 // do socks negotiation
551 if (proxy.randomize_credentials) {
552 ProxyCredentials random_auth;
553 static std::atomic_int counter;
554 random_auth.username = random_auth.password = strprintf("%i", counter++);
555 if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
556 return false;
557 } else {
558 if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
559 return false;
562 hSocketRet = hSocket;
563 return true;
566 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
568 proxyType proxy;
569 if (outProxyConnectionFailed)
570 *outProxyConnectionFailed = false;
572 if (GetProxy(addrDest.GetNetwork(), proxy))
573 return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
574 else // no proxy needed (none set for target network)
575 return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
578 bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
580 std::string strDest;
581 int port = portDefault;
583 if (outProxyConnectionFailed)
584 *outProxyConnectionFailed = false;
586 SplitHostPort(std::string(pszDest), port, strDest);
588 proxyType proxy;
589 GetNameProxy(proxy);
591 std::vector<CService> addrResolved;
592 if (Lookup(strDest.c_str(), addrResolved, port, fNameLookup && !HaveNameProxy(), 256)) {
593 if (addrResolved.size() > 0) {
594 addr = addrResolved[GetRand(addrResolved.size())];
595 return ConnectSocket(addr, hSocketRet, nTimeout);
599 addr = CService();
601 if (!HaveNameProxy())
602 return false;
603 return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
606 bool LookupSubNet(const char* pszName, CSubNet& ret)
608 std::string strSubnet(pszName);
609 size_t slash = strSubnet.find_last_of('/');
610 std::vector<CNetAddr> vIP;
612 std::string strAddress = strSubnet.substr(0, slash);
613 if (LookupHost(strAddress.c_str(), vIP, 1, false))
615 CNetAddr network = vIP[0];
616 if (slash != strSubnet.npos)
618 std::string strNetmask = strSubnet.substr(slash + 1);
619 int32_t n;
620 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
621 if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
622 ret = CSubNet(network, n);
623 return ret.IsValid();
625 else // If not a valid number, try full netmask syntax
627 // Never allow lookup for netmask
628 if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
629 ret = CSubNet(network, vIP[0]);
630 return ret.IsValid();
634 else
636 ret = CSubNet(network);
637 return ret.IsValid();
640 return false;
643 #ifdef WIN32
644 std::string NetworkErrorString(int err)
646 char buf[256];
647 buf[0] = 0;
648 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
649 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
650 buf, sizeof(buf), NULL))
652 return strprintf("%s (%d)", buf, err);
654 else
656 return strprintf("Unknown error (%d)", err);
659 #else
660 std::string NetworkErrorString(int err)
662 char buf[256];
663 const char *s = buf;
664 buf[0] = 0;
665 /* Too bad there are two incompatible implementations of the
666 * thread-safe strerror. */
667 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
668 s = strerror_r(err, buf, sizeof(buf));
669 #else /* POSIX variant always returns message in buffer */
670 if (strerror_r(err, buf, sizeof(buf)))
671 buf[0] = 0;
672 #endif
673 return strprintf("%s (%d)", s, err);
675 #endif
677 bool CloseSocket(SOCKET& hSocket)
679 if (hSocket == INVALID_SOCKET)
680 return false;
681 #ifdef WIN32
682 int ret = closesocket(hSocket);
683 #else
684 int ret = close(hSocket);
685 #endif
686 hSocket = INVALID_SOCKET;
687 return ret != SOCKET_ERROR;
690 bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
692 if (fNonBlocking) {
693 #ifdef WIN32
694 u_long nOne = 1;
695 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
696 #else
697 int fFlags = fcntl(hSocket, F_GETFL, 0);
698 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
699 #endif
700 CloseSocket(hSocket);
701 return false;
703 } else {
704 #ifdef WIN32
705 u_long nZero = 0;
706 if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
707 #else
708 int fFlags = fcntl(hSocket, F_GETFL, 0);
709 if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
710 #endif
711 CloseSocket(hSocket);
712 return false;
716 return true;