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.
7 #include "config/bitcoin-config.h"
17 #include "utilstrencodings.h"
19 #ifdef HAVE_GETADDRINFO_A
25 #include <arpa/inet.h>
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
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
) {
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
) {
59 case NET_IPV4
: return "ipv4";
60 case NET_IPV6
: return "ipv6";
61 case NET_TOR
: return "onion";
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
)) {
74 if (ParseInt32(in
.substr(colon
+ 1), &n
) && n
> 0 && n
< 0x10000) {
75 in
= in
.substr(0, colon
);
79 if (in
.size()>0 && in
[0] == '[' && in
[in
.size()-1] == ']')
80 hostOut
= in
.substr(1, in
.size()-2);
85 bool static LookupIntern(const char *pszName
, std::vector
<CNetAddr
>& vIP
, unsigned int nMaxSolutions
, bool fAllowLookup
)
91 if (addr
.SetSpecial(std::string(pszName
))) {
97 #ifdef HAVE_GETADDRINFO_A
98 struct in_addr ipv4_addr
;
100 if (inet_pton(AF_INET
, pszName
, &ipv4_addr
) > 0) {
101 vIP
.push_back(CNetAddr(ipv4_addr
));
105 struct in6_addr ipv6_addr
;
106 if (inet_pton(AF_INET6
, pszName
, &ipv6_addr
) > 0) {
107 vIP
.push_back(CNetAddr(ipv6_addr
));
111 ipv4_addr
.s_addr
= inet_addr(pszName
);
112 if (ipv4_addr
.s_addr
!= INADDR_NONE
) {
113 vIP
.push_back(CNetAddr(ipv4_addr
));
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
;
125 aiHint
.ai_flags
= fAllowLookup
? 0 : AI_NUMERICHOST
;
127 aiHint
.ai_flags
= fAllowLookup
? AI_ADDRCONFIG
: AI_NUMERICHOST
;
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
);
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
);
151 aiRes
= query
->ar_result
;
152 } while (nErr
== EAI_INPROGRESS
);
154 int nErr
= getaddrinfo(pszName
, NULL
, &aiHint
, &aiRes
);
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
;
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
);
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
);
206 bool Lookup(const char *pszName
, std::vector
<CService
>& vAddr
, int portDefault
, bool fAllowLookup
, unsigned int nMaxSolutions
)
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
);
218 vAddr
.resize(vIP
.size());
219 for (unsigned int i
= 0; i
< vIP
.size(); i
++)
220 vAddr
[i
] = CService(vIP
[i
], port
);
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);
234 CService
LookupNumeric(const char *pszName
, int portDefault
)
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))
244 struct timeval
MillisToTimeval(int64_t nTimeout
)
246 struct timeval timeout
;
247 timeout
.tv_sec
= nTimeout
/ 1000;
248 timeout
.tv_usec
= (nTimeout
% 1000) * 1000;
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
275 } else if (ret
== 0) { // Unexpected disconnection
277 } else { // Other error or blocking
278 int nErr
= WSAGetLastError();
279 if (nErr
== WSAEINPROGRESS
|| nErr
== WSAEWOULDBLOCK
|| nErr
== WSAEINVAL
) {
280 if (!IsSelectableSocket(hSocket
)) {
283 struct timeval tval
= MillisToTimeval(std::min(endTime
- curTime
, maxWait
));
286 FD_SET(hSocket
, &fdset
);
287 int nRet
= select(hSocket
+ 1, &fdset
, NULL
, NULL
, &tval
);
288 if (nRet
== SOCKET_ERROR
) {
295 boost::this_thread::interruption_point();
296 curTime
= GetTimeMillis();
301 struct ProxyCredentials
303 std::string username
;
304 std::string password
;
307 std::string
Socks5ErrorString(int 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);
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)
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");
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
);
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
);
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
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");
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]));
416 if (pchRet2
[2] != 0x00) {
417 CloseSocket(hSocket
);
418 return error("Error: malformed proxy response");
423 case 0x01: ret
= InterruptibleRecv(pchRet3
, 4, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
424 case 0x04: ret
= InterruptibleRecv(pchRet3
, 16, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
427 ret
= InterruptibleRecv(pchRet3
, 1, SOCKS5_RECV_TIMEOUT
, hSocket
);
429 CloseSocket(hSocket
);
430 return error("Error reading from proxy");
432 int nRecv
= pchRet3
[0];
433 ret
= InterruptibleRecv(pchRet3
, nRecv
, SOCKS5_RECV_TIMEOUT
, hSocket
);
436 default: CloseSocket(hSocket
); return error("Error: malformed proxy response");
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
);
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());
461 SOCKET hSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
462 if (hSocket
== INVALID_SOCKET
)
467 // Different way of disabling SIGPIPE on BSD
468 setsockopt(hSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&set
, sizeof(int));
471 //Disable Nagle's algorithm
473 setsockopt(hSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&set
, sizeof(int));
475 setsockopt(hSocket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&set
, sizeof(int));
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
);
491 FD_SET(hSocket
, &fdset
);
492 int nRet
= select(hSocket
+ 1, NULL
, &fdset
, NULL
, &timeout
);
495 LogPrint("net", "connection to %s timeout\n", addrConnect
.ToString());
496 CloseSocket(hSocket
);
499 if (nRet
== SOCKET_ERROR
)
501 LogPrintf("select() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
502 CloseSocket(hSocket
);
505 socklen_t nRetSize
= sizeof(nRet
);
507 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, (char*)(&nRet
), &nRetSize
) == SOCKET_ERROR
)
509 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, &nRet
, &nRetSize
) == SOCKET_ERROR
)
512 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
513 CloseSocket(hSocket
);
518 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect
.ToString(), NetworkErrorString(nRet
));
519 CloseSocket(hSocket
);
524 else if (WSAGetLastError() != WSAEISCONN
)
529 LogPrintf("connect() to %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
530 CloseSocket(hSocket
);
535 hSocketRet
= hSocket
;
539 bool SetProxy(enum Network net
, const proxyType
&addrProxy
) {
540 assert(net
>= 0 && net
< NET_MAX
);
541 if (!addrProxy
.IsValid())
544 proxyInfo
[net
] = addrProxy
;
548 bool GetProxy(enum Network net
, proxyType
&proxyInfoOut
) {
549 assert(net
>= 0 && net
< NET_MAX
);
551 if (!proxyInfo
[net
].IsValid())
553 proxyInfoOut
= proxyInfo
[net
];
557 bool SetNameProxy(const proxyType
&addrProxy
) {
558 if (!addrProxy
.IsValid())
561 nameProxy
= addrProxy
;
565 bool GetNameProxy(proxyType
&nameProxyOut
) {
567 if(!nameProxy
.IsValid())
569 nameProxyOut
= nameProxy
;
573 bool HaveNameProxy() {
575 return nameProxy
.IsValid();
578 bool IsProxy(const CNetAddr
&addr
) {
580 for (int i
= 0; i
< NET_MAX
; i
++) {
581 if (addr
== (CNetAddr
)proxyInfo
[i
].proxy
)
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;
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
))
604 if (!Socks5(strDest
, (unsigned short)port
, 0, hSocket
))
608 hSocketRet
= hSocket
;
612 bool ConnectSocket(const CService
&addrDest
, SOCKET
& hSocketRet
, int nTimeout
, bool *outProxyConnectionFailed
)
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
)
627 int port
= portDefault
;
629 if (outProxyConnectionFailed
)
630 *outProxyConnectionFailed
= false;
632 SplitHostPort(std::string(pszDest
), port
, strDest
);
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
);
647 if (!HaveNameProxy())
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);
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();
682 ret
= CSubNet(network
);
683 return ret
.IsValid();
690 std::string
NetworkErrorString(int err
)
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
);
702 return strprintf("Unknown error (%d)", err
);
706 std::string
NetworkErrorString(int err
)
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
)))
719 return strprintf("%s (%d)", s
, err
);
723 bool CloseSocket(SOCKET
& hSocket
)
725 if (hSocket
== INVALID_SOCKET
)
728 int ret
= closesocket(hSocket
);
730 int ret
= close(hSocket
);
732 hSocket
= INVALID_SOCKET
;
733 return ret
!= SOCKET_ERROR
;
736 bool SetSocketNonBlocking(SOCKET
& hSocket
, bool fNonBlocking
)
741 if (ioctlsocket(hSocket
, FIONBIO
, &nOne
) == SOCKET_ERROR
) {
743 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
744 if (fcntl(hSocket
, F_SETFL
, fFlags
| O_NONBLOCK
) == SOCKET_ERROR
) {
746 CloseSocket(hSocket
);
752 if (ioctlsocket(hSocket
, FIONBIO
, &nZero
) == SOCKET_ERROR
) {
754 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
755 if (fcntl(hSocket
, F_SETFL
, fFlags
& ~O_NONBLOCK
) == SOCKET_ERROR
) {
757 CloseSocket(hSocket
);