1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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.
5 
6 #include <netbase.h>
7 
8 #include <compat.h>
9 #include <sync.h>
10 #include <tinyformat.h>
11 #include <util/sock.h>
12 #include <util/strencodings.h>
13 #include <util/string.h>
14 #include <util/system.h>
15 #include <util/time.h>
16 
17 #include <atomic>
18 #include <chrono>
19 #include <cstdint>
20 #include <functional>
21 #include <limits>
22 #include <memory>
23 
24 #ifndef WIN32
25 #include <fcntl.h>
26 #else
27 #include <codecvt>
28 #endif
29 
30 #ifdef USE_POLL
31 #include <poll.h>
32 #endif
33 
34 // Settings
35 static Mutex g_proxyinfo_mutex;
36 static proxyType proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
37 static proxyType nameProxy GUARDED_BY(g_proxyinfo_mutex);
38 int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
39 bool fNameLookup = DEFAULT_NAME_LOOKUP;
40 
41 // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
42 int g_socks5_recv_timeout = 20 * 1000;
43 static std::atomic<bool> interruptSocks5Recv(false);
44 
WrappedGetAddrInfo(const std::string & name,bool allow_lookup)45 std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
46 {
47     addrinfo ai_hint{};
48     // We want a TCP port, which is a streaming socket type
49     ai_hint.ai_socktype = SOCK_STREAM;
50     ai_hint.ai_protocol = IPPROTO_TCP;
51     // We don't care which address family (IPv4 or IPv6) is returned
52     ai_hint.ai_family = AF_UNSPEC;
53     // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
54     // return addresses whose family we have an address configured for.
55     //
56     // If we don't allow lookups, then use the AI_NUMERICHOST flag for
57     // getaddrinfo to only decode numerical network addresses and suppress
58     // hostname lookups.
59     ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
60 
61     addrinfo* ai_res{nullptr};
62     const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
63     if (n_err != 0) {
64         return {};
65     }
66 
67     // Traverse the linked list starting with ai_trav.
68     addrinfo* ai_trav{ai_res};
69     std::vector<CNetAddr> resolved_addresses;
70     while (ai_trav != nullptr) {
71         if (ai_trav->ai_family == AF_INET) {
72             assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
73             resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
74         }
75         if (ai_trav->ai_family == AF_INET6) {
76             assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
77             const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
78             resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
79         }
80         ai_trav = ai_trav->ai_next;
81     }
82     freeaddrinfo(ai_res);
83 
84     return resolved_addresses;
85 }
86 
87 DNSLookupFn g_dns_lookup{WrappedGetAddrInfo};
88 
ParseNetwork(const std::string & net_in)89 enum Network ParseNetwork(const std::string& net_in) {
90     std::string net = ToLower(net_in);
91     if (net == "ipv4") return NET_IPV4;
92     if (net == "ipv6") return NET_IPV6;
93     if (net == "onion") return NET_ONION;
94     if (net == "tor") {
95         LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
96         return NET_ONION;
97     }
98     if (net == "i2p") {
99         return NET_I2P;
100     }
101     return NET_UNROUTABLE;
102 }
103 
GetNetworkName(enum Network net)104 std::string GetNetworkName(enum Network net)
105 {
106     switch (net) {
107     case NET_UNROUTABLE: return "not_publicly_routable";
108     case NET_IPV4: return "ipv4";
109     case NET_IPV6: return "ipv6";
110     case NET_ONION: return "onion";
111     case NET_I2P: return "i2p";
112     case NET_CJDNS: return "cjdns";
113     case NET_INTERNAL: return "internal";
114     case NET_MAX: assert(false);
115     } // no default case, so the compiler can warn about missing cases
116 
117     assert(false);
118 }
119 
GetNetworkNames(bool append_unroutable)120 std::vector<std::string> GetNetworkNames(bool append_unroutable)
121 {
122     std::vector<std::string> names;
123     for (int n = 0; n < NET_MAX; ++n) {
124         const enum Network network{static_cast<Network>(n)};
125         if (network == NET_UNROUTABLE || network == NET_CJDNS || network == NET_INTERNAL) continue;
126         names.emplace_back(GetNetworkName(network));
127     }
128     if (append_unroutable) {
129         names.emplace_back(GetNetworkName(NET_UNROUTABLE));
130     }
131     return names;
132 }
133 
LookupIntern(const std::string & name,std::vector<CNetAddr> & vIP,unsigned int nMaxSolutions,bool fAllowLookup,DNSLookupFn dns_lookup_function)134 static bool LookupIntern(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
135 {
136     vIP.clear();
137 
138     if (!ValidAsCString(name)) {
139         return false;
140     }
141 
142     {
143         CNetAddr addr;
144         // From our perspective, onion addresses are not hostnames but rather
145         // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
146         // or IPv6 colon-separated hextet notation. Since we can't use
147         // getaddrinfo to decode them and it wouldn't make sense to resolve
148         // them, we return a network address representing it instead. See
149         // CNetAddr::SetSpecial(const std::string&) for more details.
150         if (addr.SetSpecial(name)) {
151             vIP.push_back(addr);
152             return true;
153         }
154     }
155 
156     for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
157         if (nMaxSolutions > 0 && vIP.size() >= nMaxSolutions) {
158             break;
159         }
160         /* Never allow resolving to an internal address. Consider any such result invalid */
161         if (!resolved.IsInternal()) {
162             vIP.push_back(resolved);
163         }
164     }
165 
166     return (vIP.size() > 0);
167 }
168 
LookupHost(const std::string & name,std::vector<CNetAddr> & vIP,unsigned int nMaxSolutions,bool fAllowLookup,DNSLookupFn dns_lookup_function)169 bool LookupHost(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
170 {
171     if (!ValidAsCString(name)) {
172         return false;
173     }
174     std::string strHost = name;
175     if (strHost.empty())
176         return false;
177     if (strHost.front() == '[' && strHost.back() == ']') {
178         strHost = strHost.substr(1, strHost.size() - 2);
179     }
180 
181     return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
182 }
183 
LookupHost(const std::string & name,CNetAddr & addr,bool fAllowLookup,DNSLookupFn dns_lookup_function)184 bool LookupHost(const std::string& name, CNetAddr& addr, bool fAllowLookup, DNSLookupFn dns_lookup_function)
185 {
186     if (!ValidAsCString(name)) {
187         return false;
188     }
189     std::vector<CNetAddr> vIP;
190     LookupHost(name, vIP, 1, fAllowLookup, dns_lookup_function);
191     if(vIP.empty())
192         return false;
193     addr = vIP.front();
194     return true;
195 }
196 
Lookup(const std::string & name,std::vector<CService> & vAddr,uint16_t portDefault,bool fAllowLookup,unsigned int nMaxSolutions,DNSLookupFn dns_lookup_function)197 bool Lookup(const std::string& name, std::vector<CService>& vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
198 {
199     if (name.empty() || !ValidAsCString(name)) {
200         return false;
201     }
202     uint16_t port{portDefault};
203     std::string hostname;
204     SplitHostPort(name, port, hostname);
205 
206     std::vector<CNetAddr> vIP;
207     bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup, dns_lookup_function);
208     if (!fRet)
209         return false;
210     vAddr.resize(vIP.size());
211     for (unsigned int i = 0; i < vIP.size(); i++)
212         vAddr[i] = CService(vIP[i], port);
213     return true;
214 }
215 
Lookup(const std::string & name,CService & addr,uint16_t portDefault,bool fAllowLookup,DNSLookupFn dns_lookup_function)216 bool Lookup(const std::string& name, CService& addr, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
217 {
218     if (!ValidAsCString(name)) {
219         return false;
220     }
221     std::vector<CService> vService;
222     bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1, dns_lookup_function);
223     if (!fRet)
224         return false;
225     addr = vService[0];
226     return true;
227 }
228 
LookupNumeric(const std::string & name,uint16_t portDefault,DNSLookupFn dns_lookup_function)229 CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
230 {
231     if (!ValidAsCString(name)) {
232         return {};
233     }
234     CService addr;
235     // "1.2:345" will fail to resolve the ip, but will still set the port.
236     // If the ip fails to resolve, re-init the result.
237     if(!Lookup(name, addr, portDefault, false, dns_lookup_function))
238         addr = CService();
239     return addr;
240 }
241 
242 /** SOCKS version */
243 enum SOCKSVersion: uint8_t {
244     SOCKS4 = 0x04,
245     SOCKS5 = 0x05
246 };
247 
248 /** Values defined for METHOD in RFC1928 */
249 enum SOCKS5Method: uint8_t {
250     NOAUTH = 0x00,        //!< No authentication required
251     GSSAPI = 0x01,        //!< GSSAPI
252     USER_PASS = 0x02,     //!< Username/password
253     NO_ACCEPTABLE = 0xff, //!< No acceptable methods
254 };
255 
256 /** Values defined for CMD in RFC1928 */
257 enum SOCKS5Command: uint8_t {
258     CONNECT = 0x01,
259     BIND = 0x02,
260     UDP_ASSOCIATE = 0x03
261 };
262 
263 /** Values defined for REP in RFC1928 */
264 enum SOCKS5Reply: uint8_t {
265     SUCCEEDED = 0x00,        //!< Succeeded
266     GENFAILURE = 0x01,       //!< General failure
267     NOTALLOWED = 0x02,       //!< Connection not allowed by ruleset
268     NETUNREACHABLE = 0x03,   //!< Network unreachable
269     HOSTUNREACHABLE = 0x04,  //!< Network unreachable
270     CONNREFUSED = 0x05,      //!< Connection refused
271     TTLEXPIRED = 0x06,       //!< TTL expired
272     CMDUNSUPPORTED = 0x07,   //!< Command not supported
273     ATYPEUNSUPPORTED = 0x08, //!< Address type not supported
274 };
275 
276 /** Values defined for ATYPE in RFC1928 */
277 enum SOCKS5Atyp: uint8_t {
278     IPV4 = 0x01,
279     DOMAINNAME = 0x03,
280     IPV6 = 0x04,
281 };
282 
283 /** Status codes that can be returned by InterruptibleRecv */
284 enum class IntrRecvError {
285     OK,
286     Timeout,
287     Disconnected,
288     NetworkError,
289     Interrupted
290 };
291 
292 /**
293  * Try to read a specified number of bytes from a socket. Please read the "see
294  * also" section for more detail.
295  *
296  * @param data The buffer where the read bytes should be stored.
297  * @param len The number of bytes to read into the specified buffer.
298  * @param timeout The total timeout in milliseconds for this read.
299  * @param sock The socket (has to be in non-blocking mode) from which to read bytes.
300  *
301  * @returns An IntrRecvError indicating the resulting status of this read.
302  *          IntrRecvError::OK only if all of the specified number of bytes were
303  *          read.
304  *
305  * @see This function can be interrupted by calling InterruptSocks5(bool).
306  *      Sockets can be made non-blocking with SetSocketNonBlocking(const
307  *      SOCKET&, bool).
308  */
InterruptibleRecv(uint8_t * data,size_t len,int timeout,const Sock & sock)309 static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const Sock& sock)
310 {
311     int64_t curTime = GetTimeMillis();
312     int64_t endTime = curTime + timeout;
313     while (len > 0 && curTime < endTime) {
314         ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
315         if (ret > 0) {
316             len -= ret;
317             data += ret;
318         } else if (ret == 0) { // Unexpected disconnection
319             return IntrRecvError::Disconnected;
320         } else { // Other error or blocking
321             int nErr = WSAGetLastError();
322             if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
323                 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
324                 // we're approaching the end of the specified total timeout
325                 const auto remaining = std::chrono::milliseconds{endTime - curTime};
326                 const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
327                 if (!sock.Wait(timeout, Sock::RECV)) {
328                     return IntrRecvError::NetworkError;
329                 }
330             } else {
331                 return IntrRecvError::NetworkError;
332             }
333         }
334         if (interruptSocks5Recv)
335             return IntrRecvError::Interrupted;
336         curTime = GetTimeMillis();
337     }
338     return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
339 }
340 
341 /** Convert SOCKS5 reply to an error message */
Socks5ErrorString(uint8_t err)342 static std::string Socks5ErrorString(uint8_t err)
343 {
344     switch(err) {
345         case SOCKS5Reply::GENFAILURE:
346             return "general failure";
347         case SOCKS5Reply::NOTALLOWED:
348             return "connection not allowed";
349         case SOCKS5Reply::NETUNREACHABLE:
350             return "network unreachable";
351         case SOCKS5Reply::HOSTUNREACHABLE:
352             return "host unreachable";
353         case SOCKS5Reply::CONNREFUSED:
354             return "connection refused";
355         case SOCKS5Reply::TTLEXPIRED:
356             return "TTL expired";
357         case SOCKS5Reply::CMDUNSUPPORTED:
358             return "protocol error";
359         case SOCKS5Reply::ATYPEUNSUPPORTED:
360             return "address type not supported";
361         default:
362             return "unknown";
363     }
364 }
365 
Socks5(const std::string & strDest,uint16_t port,const ProxyCredentials * auth,const Sock & sock)366 bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
367 {
368     IntrRecvError recvr;
369     LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
370     if (strDest.size() > 255) {
371         return error("Hostname too long");
372     }
373     // Construct the version identifier/method selection message
374     std::vector<uint8_t> vSocks5Init;
375     vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
376     if (auth) {
377         vSocks5Init.push_back(0x02); // 2 method identifiers follow...
378         vSocks5Init.push_back(SOCKS5Method::NOAUTH);
379         vSocks5Init.push_back(SOCKS5Method::USER_PASS);
380     } else {
381         vSocks5Init.push_back(0x01); // 1 method identifier follows...
382         vSocks5Init.push_back(SOCKS5Method::NOAUTH);
383     }
384     ssize_t ret = sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
385     if (ret != (ssize_t)vSocks5Init.size()) {
386         return error("Error sending to proxy");
387     }
388     uint8_t pchRet1[2];
389     if ((recvr = InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
390         LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
391         return false;
392     }
393     if (pchRet1[0] != SOCKSVersion::SOCKS5) {
394         return error("Proxy failed to initialize");
395     }
396     if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
397         // Perform username/password authentication (as described in RFC1929)
398         std::vector<uint8_t> vAuth;
399         vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
400         if (auth->username.size() > 255 || auth->password.size() > 255)
401             return error("Proxy username or password too long");
402         vAuth.push_back(auth->username.size());
403         vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
404         vAuth.push_back(auth->password.size());
405         vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
406         ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
407         if (ret != (ssize_t)vAuth.size()) {
408             return error("Error sending authentication to proxy");
409         }
410         LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
411         uint8_t pchRetA[2];
412         if ((recvr = InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
413             return error("Error reading proxy authentication response");
414         }
415         if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
416             return error("Proxy authentication unsuccessful");
417         }
418     } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
419         // Perform no authentication
420     } else {
421         return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
422     }
423     std::vector<uint8_t> vSocks5;
424     vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
425     vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
426     vSocks5.push_back(0x00); // RSV Reserved must be 0
427     vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
428     vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
429     vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
430     vSocks5.push_back((port >> 8) & 0xFF);
431     vSocks5.push_back((port >> 0) & 0xFF);
432     ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
433     if (ret != (ssize_t)vSocks5.size()) {
434         return error("Error sending to proxy");
435     }
436     uint8_t pchRet2[4];
437     if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
438         if (recvr == IntrRecvError::Timeout) {
439             /* If a timeout happens here, this effectively means we timed out while connecting
440              * to the remote node. This is very common for Tor, so do not print an
441              * error message. */
442             return false;
443         } else {
444             return error("Error while reading proxy response");
445         }
446     }
447     if (pchRet2[0] != SOCKSVersion::SOCKS5) {
448         return error("Proxy failed to accept request");
449     }
450     if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
451         // Failures to connect to a peer that are not proxy errors
452         LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
453         return false;
454     }
455     if (pchRet2[2] != 0x00) { // Reserved field must be 0
456         return error("Error: malformed proxy response");
457     }
458     uint8_t pchRet3[256];
459     switch (pchRet2[3])
460     {
461         case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
462         case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
463         case SOCKS5Atyp::DOMAINNAME:
464         {
465             recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
466             if (recvr != IntrRecvError::OK) {
467                 return error("Error reading from proxy");
468             }
469             int nRecv = pchRet3[0];
470             recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
471             break;
472         }
473         default: return error("Error: malformed proxy response");
474     }
475     if (recvr != IntrRecvError::OK) {
476         return error("Error reading from proxy");
477     }
478     if ((recvr = InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
479         return error("Error reading from proxy");
480     }
481     LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
482     return true;
483 }
484 
CreateSockTCP(const CService & address_family)485 std::unique_ptr<Sock> CreateSockTCP(const CService& address_family)
486 {
487     // Create a sockaddr from the specified service.
488     struct sockaddr_storage sockaddr;
489     socklen_t len = sizeof(sockaddr);
490     if (!address_family.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
491         LogPrintf("Cannot create socket for %s: unsupported network\n", address_family.ToString());
492         return nullptr;
493     }
494 
495     // Create a TCP socket in the address family of the specified service.
496     SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
497     if (hSocket == INVALID_SOCKET) {
498         return nullptr;
499     }
500 
501     // Ensure that waiting for I/O on this socket won't result in undefined
502     // behavior.
503     if (!IsSelectableSocket(hSocket)) {
504         CloseSocket(hSocket);
505         LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
506         return nullptr;
507     }
508 
509 #ifdef SO_NOSIGPIPE
510     int set = 1;
511     // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
512     // should use the MSG_NOSIGNAL flag for every send.
513     setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
514 #endif
515 
516     // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
517     SetSocketNoDelay(hSocket);
518 
519     // Set the non-blocking option on the socket.
520     if (!SetSocketNonBlocking(hSocket, true)) {
521         CloseSocket(hSocket);
522         LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
523         return nullptr;
524     }
525     return std::make_unique<Sock>(hSocket);
526 }
527 
528 std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP;
529 
530 template<typename... Args>
LogConnectFailure(bool manual_connection,const char * fmt,const Args &...args)531 static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
532     std::string error_message = tfm::format(fmt, args...);
533     if (manual_connection) {
534         LogPrintf("%s\n", error_message);
535     } else {
536         LogPrint(BCLog::NET, "%s\n", error_message);
537     }
538 }
539 
ConnectSocketDirectly(const CService & addrConnect,const Sock & sock,int nTimeout,bool manual_connection)540 bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection)
541 {
542     // Create a sockaddr from the specified service.
543     struct sockaddr_storage sockaddr;
544     socklen_t len = sizeof(sockaddr);
545     if (sock.Get() == INVALID_SOCKET) {
546         LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString());
547         return false;
548     }
549     if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
550         LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
551         return false;
552     }
553 
554     // Connect to the addrConnect service on the hSocket socket.
555     if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) {
556         int nErr = WSAGetLastError();
557         // WSAEINVAL is here because some legacy version of winsock uses it
558         if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
559         {
560             // Connection didn't actually fail, but is being established
561             // asynchronously. Thus, use async I/O api (select/poll)
562             // synchronously to check for successful connection with a timeout.
563             const Sock::Event requested = Sock::RECV | Sock::SEND;
564             Sock::Event occurred;
565             if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) {
566                 LogPrintf("wait for connect to %s failed: %s\n",
567                           addrConnect.ToString(),
568                           NetworkErrorString(WSAGetLastError()));
569                 return false;
570             } else if (occurred == 0) {
571                 LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToString());
572                 return false;
573             }
574 
575             // Even if the wait was successful, the connect might not
576             // have been successful. The reason for this failure is hidden away
577             // in the SO_ERROR for the socket in modern systems. We read it into
578             // sockerr here.
579             int sockerr;
580             socklen_t sockerr_len = sizeof(sockerr);
581             if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
582                 SOCKET_ERROR) {
583                 LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
584                 return false;
585             }
586             if (sockerr != 0) {
587                 LogConnectFailure(manual_connection,
588                                   "connect() to %s failed after wait: %s",
589                                   addrConnect.ToString(),
590                                   NetworkErrorString(sockerr));
591                 return false;
592             }
593         }
594 #ifdef WIN32
595         else if (WSAGetLastError() != WSAEISCONN)
596 #else
597         else
598 #endif
599         {
600             LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
601             return false;
602         }
603     }
604     return true;
605 }
606 
SetProxy(enum Network net,const proxyType & addrProxy)607 bool SetProxy(enum Network net, const proxyType &addrProxy) {
608     assert(net >= 0 && net < NET_MAX);
609     if (!addrProxy.IsValid())
610         return false;
611     LOCK(g_proxyinfo_mutex);
612     proxyInfo[net] = addrProxy;
613     return true;
614 }
615 
GetProxy(enum Network net,proxyType & proxyInfoOut)616 bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
617     assert(net >= 0 && net < NET_MAX);
618     LOCK(g_proxyinfo_mutex);
619     if (!proxyInfo[net].IsValid())
620         return false;
621     proxyInfoOut = proxyInfo[net];
622     return true;
623 }
624 
SetNameProxy(const proxyType & addrProxy)625 bool SetNameProxy(const proxyType &addrProxy) {
626     if (!addrProxy.IsValid())
627         return false;
628     LOCK(g_proxyinfo_mutex);
629     nameProxy = addrProxy;
630     return true;
631 }
632 
GetNameProxy(proxyType & nameProxyOut)633 bool GetNameProxy(proxyType &nameProxyOut) {
634     LOCK(g_proxyinfo_mutex);
635     if(!nameProxy.IsValid())
636         return false;
637     nameProxyOut = nameProxy;
638     return true;
639 }
640 
HaveNameProxy()641 bool HaveNameProxy() {
642     LOCK(g_proxyinfo_mutex);
643     return nameProxy.IsValid();
644 }
645 
IsProxy(const CNetAddr & addr)646 bool IsProxy(const CNetAddr &addr) {
647     LOCK(g_proxyinfo_mutex);
648     for (int i = 0; i < NET_MAX; i++) {
649         if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
650             return true;
651     }
652     return false;
653 }
654 
ConnectThroughProxy(const proxyType & proxy,const std::string & strDest,uint16_t port,const Sock & sock,int nTimeout,bool & outProxyConnectionFailed)655 bool ConnectThroughProxy(const proxyType& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed)
656 {
657     // first connect to proxy server
658     if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) {
659         outProxyConnectionFailed = true;
660         return false;
661     }
662     // do socks negotiation
663     if (proxy.randomize_credentials) {
664         ProxyCredentials random_auth;
665         static std::atomic_int counter(0);
666         random_auth.username = random_auth.password = strprintf("%i", counter++);
667         if (!Socks5(strDest, port, &random_auth, sock)) {
668             return false;
669         }
670     } else {
671         if (!Socks5(strDest, port, 0, sock)) {
672             return false;
673         }
674     }
675     return true;
676 }
677 
LookupSubNet(const std::string & strSubnet,CSubNet & ret,DNSLookupFn dns_lookup_function)678 bool LookupSubNet(const std::string& strSubnet, CSubNet& ret, DNSLookupFn dns_lookup_function)
679 {
680     if (!ValidAsCString(strSubnet)) {
681         return false;
682     }
683     size_t slash = strSubnet.find_last_of('/');
684     std::vector<CNetAddr> vIP;
685 
686     std::string strAddress = strSubnet.substr(0, slash);
687     // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just get
688     //       one CNetAddr.
689     if (LookupHost(strAddress, vIP, 1, false, dns_lookup_function))
690     {
691         CNetAddr network = vIP[0];
692         if (slash != strSubnet.npos)
693         {
694             std::string strNetmask = strSubnet.substr(slash + 1);
695             uint8_t n;
696             if (ParseUInt8(strNetmask, &n)) {
697                 // If valid number, assume CIDR variable-length subnet masking
698                 ret = CSubNet(network, n);
699                 return ret.IsValid();
700             }
701             else // If not a valid number, try full netmask syntax
702             {
703                 // Never allow lookup for netmask
704                 if (LookupHost(strNetmask, vIP, 1, false, dns_lookup_function)) {
705                     ret = CSubNet(network, vIP[0]);
706                     return ret.IsValid();
707                 }
708             }
709         }
710         else
711         {
712             ret = CSubNet(network);
713             return ret.IsValid();
714         }
715     }
716     return false;
717 }
718 
SetSocketNonBlocking(const SOCKET & hSocket,bool fNonBlocking)719 bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking)
720 {
721     if (fNonBlocking) {
722 #ifdef WIN32
723         u_long nOne = 1;
724         if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
725 #else
726         int fFlags = fcntl(hSocket, F_GETFL, 0);
727         if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
728 #endif
729             return false;
730         }
731     } else {
732 #ifdef WIN32
733         u_long nZero = 0;
734         if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
735 #else
736         int fFlags = fcntl(hSocket, F_GETFL, 0);
737         if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
738 #endif
739             return false;
740         }
741     }
742 
743     return true;
744 }
745 
746 bool SetSocketNoDelay(const SOCKET& hSocket)
747 {
748     int set = 1;
749     int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
750     return rc == 0;
751 }
752 
753 void InterruptSocks5(bool interrupt)
754 {
755     interruptSocks5Recv = interrupt;
756 }
757