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