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.
7 #include "config/bitcoin-config.h"
17 #include "utilstrencodings.h"
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
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
) {
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
) {
54 case NET_IPV4
: return "ipv4";
55 case NET_IPV6
: return "ipv6";
56 case NET_TOR
: return "onion";
61 void SplitHostPort(std::string in
, int &portOut
, std::string
&hostOut
) {
62 size_t colon
= in
.find_last_of(':');
63 // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
64 bool fHaveColon
= colon
!= in
.npos
;
65 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
66 bool fMultiColon
= fHaveColon
&& (in
.find_last_of(':',colon
-1) != in
.npos
);
67 if (fHaveColon
&& (colon
==0 || fBracketed
|| !fMultiColon
)) {
69 if (ParseInt32(in
.substr(colon
+ 1), &n
) && n
> 0 && n
< 0x10000) {
70 in
= in
.substr(0, colon
);
74 if (in
.size()>0 && in
[0] == '[' && in
[in
.size()-1] == ']')
75 hostOut
= in
.substr(1, in
.size()-2);
80 bool static LookupIntern(const char *pszName
, std::vector
<CNetAddr
>& vIP
, unsigned int nMaxSolutions
, bool fAllowLookup
)
86 if (addr
.SetSpecial(std::string(pszName
))) {
92 struct addrinfo aiHint
;
93 memset(&aiHint
, 0, sizeof(struct addrinfo
));
95 aiHint
.ai_socktype
= SOCK_STREAM
;
96 aiHint
.ai_protocol
= IPPROTO_TCP
;
97 aiHint
.ai_family
= AF_UNSPEC
;
99 aiHint
.ai_flags
= fAllowLookup
? 0 : AI_NUMERICHOST
;
101 aiHint
.ai_flags
= fAllowLookup
? AI_ADDRCONFIG
: AI_NUMERICHOST
;
103 struct addrinfo
*aiRes
= NULL
;
104 int nErr
= getaddrinfo(pszName
, NULL
, &aiHint
, &aiRes
);
108 struct addrinfo
*aiTrav
= aiRes
;
109 while (aiTrav
!= NULL
&& (nMaxSolutions
== 0 || vIP
.size() < nMaxSolutions
))
111 if (aiTrav
->ai_family
== AF_INET
)
113 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in
));
114 vIP
.push_back(CNetAddr(((struct sockaddr_in
*)(aiTrav
->ai_addr
))->sin_addr
));
117 if (aiTrav
->ai_family
== AF_INET6
)
119 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in6
));
120 struct sockaddr_in6
* s6
= (struct sockaddr_in6
*) aiTrav
->ai_addr
;
121 vIP
.push_back(CNetAddr(s6
->sin6_addr
, s6
->sin6_scope_id
));
124 aiTrav
= aiTrav
->ai_next
;
129 return (vIP
.size() > 0);
132 bool LookupHost(const char *pszName
, std::vector
<CNetAddr
>& vIP
, unsigned int nMaxSolutions
, bool fAllowLookup
)
134 std::string
strHost(pszName
);
137 if (boost::algorithm::starts_with(strHost
, "[") && boost::algorithm::ends_with(strHost
, "]"))
139 strHost
= strHost
.substr(1, strHost
.size() - 2);
142 return LookupIntern(strHost
.c_str(), vIP
, nMaxSolutions
, fAllowLookup
);
145 bool LookupHost(const char *pszName
, CNetAddr
& addr
, bool fAllowLookup
)
147 std::vector
<CNetAddr
> vIP
;
148 LookupHost(pszName
, vIP
, 1, fAllowLookup
);
155 bool Lookup(const char *pszName
, std::vector
<CService
>& vAddr
, int portDefault
, bool fAllowLookup
, unsigned int nMaxSolutions
)
159 int port
= portDefault
;
160 std::string hostname
= "";
161 SplitHostPort(std::string(pszName
), port
, hostname
);
163 std::vector
<CNetAddr
> vIP
;
164 bool fRet
= LookupIntern(hostname
.c_str(), vIP
, nMaxSolutions
, fAllowLookup
);
167 vAddr
.resize(vIP
.size());
168 for (unsigned int i
= 0; i
< vIP
.size(); i
++)
169 vAddr
[i
] = CService(vIP
[i
], port
);
173 bool Lookup(const char *pszName
, CService
& addr
, int portDefault
, bool fAllowLookup
)
175 std::vector
<CService
> vService
;
176 bool fRet
= Lookup(pszName
, vService
, portDefault
, fAllowLookup
, 1);
183 CService
LookupNumeric(const char *pszName
, int portDefault
)
186 // "1.2:345" will fail to resolve the ip, but will still set the port.
187 // If the ip fails to resolve, re-init the result.
188 if(!Lookup(pszName
, addr
, portDefault
, false))
193 struct timeval
MillisToTimeval(int64_t nTimeout
)
195 struct timeval timeout
;
196 timeout
.tv_sec
= nTimeout
/ 1000;
197 timeout
.tv_usec
= (nTimeout
% 1000) * 1000;
201 enum class IntrRecvError
{
210 * Read bytes from socket. This will either read the full number of bytes requested
211 * or return False on error or timeout.
212 * This function can be interrupted by calling InterruptSocks5()
214 * @param data Buffer to receive into
215 * @param len Length of data to receive
216 * @param timeout Timeout in milliseconds for receive operation
218 * @note This function requires that hSocket is in non-blocking mode.
220 static IntrRecvError
InterruptibleRecv(char* data
, size_t len
, int timeout
, SOCKET
& hSocket
)
222 int64_t curTime
= GetTimeMillis();
223 int64_t endTime
= curTime
+ timeout
;
224 // Maximum time to wait in one select call. It will take up until this time (in millis)
225 // to break off in case of an interruption.
226 const int64_t maxWait
= 1000;
227 while (len
> 0 && curTime
< endTime
) {
228 ssize_t ret
= recv(hSocket
, data
, len
, 0); // Optimistically try the recv first
232 } else if (ret
== 0) { // Unexpected disconnection
233 return IntrRecvError::Disconnected
;
234 } else { // Other error or blocking
235 int nErr
= WSAGetLastError();
236 if (nErr
== WSAEINPROGRESS
|| nErr
== WSAEWOULDBLOCK
|| nErr
== WSAEINVAL
) {
237 if (!IsSelectableSocket(hSocket
)) {
238 return IntrRecvError::NetworkError
;
240 struct timeval tval
= MillisToTimeval(std::min(endTime
- curTime
, maxWait
));
243 FD_SET(hSocket
, &fdset
);
244 int nRet
= select(hSocket
+ 1, &fdset
, NULL
, NULL
, &tval
);
245 if (nRet
== SOCKET_ERROR
) {
246 return IntrRecvError::NetworkError
;
249 return IntrRecvError::NetworkError
;
252 if (interruptSocks5Recv
)
253 return IntrRecvError::Interrupted
;
254 curTime
= GetTimeMillis();
256 return len
== 0 ? IntrRecvError::OK
: IntrRecvError::Timeout
;
259 struct ProxyCredentials
261 std::string username
;
262 std::string password
;
265 std::string
Socks5ErrorString(int err
)
268 case 0x01: return "general failure";
269 case 0x02: return "connection not allowed";
270 case 0x03: return "network unreachable";
271 case 0x04: return "host unreachable";
272 case 0x05: return "connection refused";
273 case 0x06: return "TTL expired";
274 case 0x07: return "protocol error";
275 case 0x08: return "address type not supported";
276 default: return "unknown";
280 /** Connect using SOCKS5 (as described in RFC1928) */
281 static bool Socks5(const std::string
& strDest
, int port
, const ProxyCredentials
*auth
, SOCKET
& hSocket
)
284 LogPrint(BCLog::NET
, "SOCKS5 connecting %s\n", strDest
);
285 if (strDest
.size() > 255) {
286 CloseSocket(hSocket
);
287 return error("Hostname too long");
289 // Accepted authentication methods
290 std::vector
<uint8_t> vSocks5Init
;
291 vSocks5Init
.push_back(0x05);
293 vSocks5Init
.push_back(0x02); // # METHODS
294 vSocks5Init
.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
295 vSocks5Init
.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
297 vSocks5Init
.push_back(0x01); // # METHODS
298 vSocks5Init
.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
300 ssize_t ret
= send(hSocket
, (const char*)vSocks5Init
.data(), vSocks5Init
.size(), MSG_NOSIGNAL
);
301 if (ret
!= (ssize_t
)vSocks5Init
.size()) {
302 CloseSocket(hSocket
);
303 return error("Error sending to proxy");
306 if ((recvr
= InterruptibleRecv(pchRet1
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) != IntrRecvError::OK
) {
307 CloseSocket(hSocket
);
308 LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest
, port
);
311 if (pchRet1
[0] != 0x05) {
312 CloseSocket(hSocket
);
313 return error("Proxy failed to initialize");
315 if (pchRet1
[1] == 0x02 && auth
) {
316 // Perform username/password authentication (as described in RFC1929)
317 std::vector
<uint8_t> vAuth
;
318 vAuth
.push_back(0x01);
319 if (auth
->username
.size() > 255 || auth
->password
.size() > 255)
320 return error("Proxy username or password too long");
321 vAuth
.push_back(auth
->username
.size());
322 vAuth
.insert(vAuth
.end(), auth
->username
.begin(), auth
->username
.end());
323 vAuth
.push_back(auth
->password
.size());
324 vAuth
.insert(vAuth
.end(), auth
->password
.begin(), auth
->password
.end());
325 ret
= send(hSocket
, (const char*)vAuth
.data(), vAuth
.size(), MSG_NOSIGNAL
);
326 if (ret
!= (ssize_t
)vAuth
.size()) {
327 CloseSocket(hSocket
);
328 return error("Error sending authentication to proxy");
330 LogPrint(BCLog::PROXY
, "SOCKS5 sending proxy authentication %s:%s\n", auth
->username
, auth
->password
);
332 if ((recvr
= InterruptibleRecv(pchRetA
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) != IntrRecvError::OK
) {
333 CloseSocket(hSocket
);
334 return error("Error reading proxy authentication response");
336 if (pchRetA
[0] != 0x01 || pchRetA
[1] != 0x00) {
337 CloseSocket(hSocket
);
338 return error("Proxy authentication unsuccessful");
340 } else if (pchRet1
[1] == 0x00) {
341 // Perform no authentication
343 CloseSocket(hSocket
);
344 return error("Proxy requested wrong authentication method %02x", pchRet1
[1]);
346 std::vector
<uint8_t> vSocks5
;
347 vSocks5
.push_back(0x05); // VER protocol version
348 vSocks5
.push_back(0x01); // CMD CONNECT
349 vSocks5
.push_back(0x00); // RSV Reserved
350 vSocks5
.push_back(0x03); // ATYP DOMAINNAME
351 vSocks5
.push_back(strDest
.size()); // Length<=255 is checked at beginning of function
352 vSocks5
.insert(vSocks5
.end(), strDest
.begin(), strDest
.end());
353 vSocks5
.push_back((port
>> 8) & 0xFF);
354 vSocks5
.push_back((port
>> 0) & 0xFF);
355 ret
= send(hSocket
, (const char*)vSocks5
.data(), vSocks5
.size(), MSG_NOSIGNAL
);
356 if (ret
!= (ssize_t
)vSocks5
.size()) {
357 CloseSocket(hSocket
);
358 return error("Error sending to proxy");
361 if ((recvr
= InterruptibleRecv(pchRet2
, 4, SOCKS5_RECV_TIMEOUT
, hSocket
)) != IntrRecvError::OK
) {
362 CloseSocket(hSocket
);
363 if (recvr
== IntrRecvError::Timeout
) {
364 /* If a timeout happens here, this effectively means we timed out while connecting
365 * to the remote node. This is very common for Tor, so do not print an
369 return error("Error while reading proxy response");
372 if (pchRet2
[0] != 0x05) {
373 CloseSocket(hSocket
);
374 return error("Proxy failed to accept request");
376 if (pchRet2
[1] != 0x00) {
377 // Failures to connect to a peer that are not proxy errors
378 CloseSocket(hSocket
);
379 LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest
, port
, Socks5ErrorString(pchRet2
[1]));
382 if (pchRet2
[2] != 0x00) {
383 CloseSocket(hSocket
);
384 return error("Error: malformed proxy response");
389 case 0x01: recvr
= InterruptibleRecv(pchRet3
, 4, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
390 case 0x04: recvr
= InterruptibleRecv(pchRet3
, 16, SOCKS5_RECV_TIMEOUT
, hSocket
); break;
393 recvr
= InterruptibleRecv(pchRet3
, 1, SOCKS5_RECV_TIMEOUT
, hSocket
);
394 if (recvr
!= IntrRecvError::OK
) {
395 CloseSocket(hSocket
);
396 return error("Error reading from proxy");
398 int nRecv
= pchRet3
[0];
399 recvr
= InterruptibleRecv(pchRet3
, nRecv
, SOCKS5_RECV_TIMEOUT
, hSocket
);
402 default: CloseSocket(hSocket
); return error("Error: malformed proxy response");
404 if (recvr
!= IntrRecvError::OK
) {
405 CloseSocket(hSocket
);
406 return error("Error reading from proxy");
408 if ((recvr
= InterruptibleRecv(pchRet3
, 2, SOCKS5_RECV_TIMEOUT
, hSocket
)) != IntrRecvError::OK
) {
409 CloseSocket(hSocket
);
410 return error("Error reading from proxy");
412 LogPrint(BCLog::NET
, "SOCKS5 connected %s\n", strDest
);
416 bool static ConnectSocketDirectly(const CService
&addrConnect
, SOCKET
& hSocketRet
, int nTimeout
)
418 hSocketRet
= INVALID_SOCKET
;
420 struct sockaddr_storage sockaddr
;
421 socklen_t len
= sizeof(sockaddr
);
422 if (!addrConnect
.GetSockAddr((struct sockaddr
*)&sockaddr
, &len
)) {
423 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect
.ToString());
427 SOCKET hSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
428 if (hSocket
== INVALID_SOCKET
)
433 // Different way of disabling SIGPIPE on BSD
434 setsockopt(hSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&set
, sizeof(int));
437 //Disable Nagle's algorithm
438 SetSocketNoDelay(hSocket
);
440 // Set to non-blocking
441 if (!SetSocketNonBlocking(hSocket
, true))
442 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
444 if (connect(hSocket
, (struct sockaddr
*)&sockaddr
, len
) == SOCKET_ERROR
)
446 int nErr
= WSAGetLastError();
447 // WSAEINVAL is here because some legacy version of winsock uses it
448 if (nErr
== WSAEINPROGRESS
|| nErr
== WSAEWOULDBLOCK
|| nErr
== WSAEINVAL
)
450 struct timeval timeout
= MillisToTimeval(nTimeout
);
453 FD_SET(hSocket
, &fdset
);
454 int nRet
= select(hSocket
+ 1, NULL
, &fdset
, NULL
, &timeout
);
457 LogPrint(BCLog::NET
, "connection to %s timeout\n", addrConnect
.ToString());
458 CloseSocket(hSocket
);
461 if (nRet
== SOCKET_ERROR
)
463 LogPrintf("select() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
464 CloseSocket(hSocket
);
467 socklen_t nRetSize
= sizeof(nRet
);
469 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, (char*)(&nRet
), &nRetSize
) == SOCKET_ERROR
)
471 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, &nRet
, &nRetSize
) == SOCKET_ERROR
)
474 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
475 CloseSocket(hSocket
);
480 LogPrintf("connect() to %s failed after select(): %s\n", addrConnect
.ToString(), NetworkErrorString(nRet
));
481 CloseSocket(hSocket
);
486 else if (WSAGetLastError() != WSAEISCONN
)
491 LogPrintf("connect() to %s failed: %s\n", addrConnect
.ToString(), NetworkErrorString(WSAGetLastError()));
492 CloseSocket(hSocket
);
497 hSocketRet
= hSocket
;
501 bool SetProxy(enum Network net
, const proxyType
&addrProxy
) {
502 assert(net
>= 0 && net
< NET_MAX
);
503 if (!addrProxy
.IsValid())
506 proxyInfo
[net
] = addrProxy
;
510 bool GetProxy(enum Network net
, proxyType
&proxyInfoOut
) {
511 assert(net
>= 0 && net
< NET_MAX
);
513 if (!proxyInfo
[net
].IsValid())
515 proxyInfoOut
= proxyInfo
[net
];
519 bool SetNameProxy(const proxyType
&addrProxy
) {
520 if (!addrProxy
.IsValid())
523 nameProxy
= addrProxy
;
527 bool GetNameProxy(proxyType
&nameProxyOut
) {
529 if(!nameProxy
.IsValid())
531 nameProxyOut
= nameProxy
;
535 bool HaveNameProxy() {
537 return nameProxy
.IsValid();
540 bool IsProxy(const CNetAddr
&addr
) {
542 for (int i
= 0; i
< NET_MAX
; i
++) {
543 if (addr
== (CNetAddr
)proxyInfo
[i
].proxy
)
549 static bool ConnectThroughProxy(const proxyType
&proxy
, const std::string
& strDest
, int port
, SOCKET
& hSocketRet
, int nTimeout
, bool *outProxyConnectionFailed
)
551 SOCKET hSocket
= INVALID_SOCKET
;
552 // first connect to proxy server
553 if (!ConnectSocketDirectly(proxy
.proxy
, hSocket
, nTimeout
)) {
554 if (outProxyConnectionFailed
)
555 *outProxyConnectionFailed
= true;
558 // do socks negotiation
559 if (proxy
.randomize_credentials
) {
560 ProxyCredentials random_auth
;
561 static std::atomic_int counter
;
562 random_auth
.username
= random_auth
.password
= strprintf("%i", counter
++);
563 if (!Socks5(strDest
, (unsigned short)port
, &random_auth
, hSocket
))
566 if (!Socks5(strDest
, (unsigned short)port
, 0, hSocket
))
570 hSocketRet
= hSocket
;
574 bool ConnectSocket(const CService
&addrDest
, SOCKET
& hSocketRet
, int nTimeout
, bool *outProxyConnectionFailed
)
577 if (outProxyConnectionFailed
)
578 *outProxyConnectionFailed
= false;
580 if (GetProxy(addrDest
.GetNetwork(), proxy
))
581 return ConnectThroughProxy(proxy
, addrDest
.ToStringIP(), addrDest
.GetPort(), hSocketRet
, nTimeout
, outProxyConnectionFailed
);
582 else // no proxy needed (none set for target network)
583 return ConnectSocketDirectly(addrDest
, hSocketRet
, nTimeout
);
586 bool ConnectSocketByName(CService
&addr
, SOCKET
& hSocketRet
, const char *pszDest
, int portDefault
, int nTimeout
, bool *outProxyConnectionFailed
)
589 int port
= portDefault
;
591 if (outProxyConnectionFailed
)
592 *outProxyConnectionFailed
= false;
594 SplitHostPort(std::string(pszDest
), port
, strDest
);
599 std::vector
<CService
> addrResolved
;
600 if (Lookup(strDest
.c_str(), addrResolved
, port
, fNameLookup
&& !HaveNameProxy(), 256)) {
601 if (addrResolved
.size() > 0) {
602 addr
= addrResolved
[GetRand(addrResolved
.size())];
603 return ConnectSocket(addr
, hSocketRet
, nTimeout
);
609 if (!HaveNameProxy())
611 return ConnectThroughProxy(proxy
, strDest
, port
, hSocketRet
, nTimeout
, outProxyConnectionFailed
);
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);
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();
644 ret
= CSubNet(network
);
645 return ret
.IsValid();
652 std::string
NetworkErrorString(int err
)
656 if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_MAX_WIDTH_MASK
,
657 NULL
, err
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
658 buf
, sizeof(buf
), NULL
))
660 return strprintf("%s (%d)", buf
, err
);
664 return strprintf("Unknown error (%d)", err
);
668 std::string
NetworkErrorString(int err
)
672 /* Too bad there are two incompatible implementations of the
673 * thread-safe strerror. */
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 */
679 if (strerror_r(err
, buf
, sizeof(buf
)))
682 return strprintf("%s (%d)", s
, err
);
686 bool CloseSocket(SOCKET
& hSocket
)
688 if (hSocket
== INVALID_SOCKET
)
691 int ret
= closesocket(hSocket
);
693 int ret
= close(hSocket
);
695 hSocket
= INVALID_SOCKET
;
696 return ret
!= SOCKET_ERROR
;
699 bool SetSocketNonBlocking(SOCKET
& hSocket
, bool fNonBlocking
)
704 if (ioctlsocket(hSocket
, FIONBIO
, &nOne
) == SOCKET_ERROR
) {
706 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
707 if (fcntl(hSocket
, F_SETFL
, fFlags
| O_NONBLOCK
) == SOCKET_ERROR
) {
709 CloseSocket(hSocket
);
715 if (ioctlsocket(hSocket
, FIONBIO
, &nZero
) == SOCKET_ERROR
) {
717 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
718 if (fcntl(hSocket
, F_SETFL
, fFlags
& ~O_NONBLOCK
) == SOCKET_ERROR
) {
720 CloseSocket(hSocket
);
728 bool SetSocketNoDelay(SOCKET
& hSocket
)
731 int rc
= setsockopt(hSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&set
, sizeof(int));
735 void InterruptSocks5(bool interrupt
)
737 interruptSocks5Recv
= interrupt
;