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