Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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 <bitcoin-build-config.h>
7 : :
8 : : #include <netbase.h>
9 : :
10 : : #include <compat/compat.h>
11 : : #include <sync.h>
12 : : #include <tinyformat.h>
13 : : #include <util/check.h>
14 : : #include <util/log.h>
15 : : #include <util/sock.h>
16 : : #include <util/strencodings.h>
17 : : #include <util/string.h>
18 : : #include <util/time.h>
19 : :
20 : : #include <atomic>
21 : : #include <chrono>
22 : : #include <cstdint>
23 : : #include <functional>
24 : : #include <limits>
25 : : #include <memory>
26 : :
27 : : #ifdef HAVE_SOCKADDR_UN
28 : : #include <sys/un.h>
29 : : #endif
30 : :
31 : : using util::ContainsNUL;
32 : :
33 : : // Settings
34 : : static GlobalMutex g_proxyinfo_mutex;
35 : : static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
36 : : static Proxy nameProxy GUARDED_BY(g_proxyinfo_mutex);
37 : : int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
38 : : bool fNameLookup = DEFAULT_NAME_LOOKUP;
39 : :
40 : : // Need ample time for negotiation for very slow proxies such as Tor
41 : : std::chrono::milliseconds g_socks5_recv_timeout = 20s;
42 : : CThreadInterrupt g_socks5_interrupt;
43 : :
44 : : ReachableNets g_reachable_nets;
45 : :
46 : 56436 : std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
47 : : {
48 : 56436 : addrinfo ai_hint{};
49 : : // We want a TCP port, which is a streaming socket type
50 : 56436 : ai_hint.ai_socktype = SOCK_STREAM;
51 : 56436 : ai_hint.ai_protocol = IPPROTO_TCP;
52 : : // We don't care which address family (IPv4 or IPv6) is returned
53 : 56436 : ai_hint.ai_family = AF_UNSPEC;
54 : :
55 : : // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
56 : : // return addresses whose family we have an address configured for.
57 : : //
58 : : // If we don't allow lookups, then use the AI_NUMERICHOST flag for
59 : : // getaddrinfo to only decode numerical network addresses and suppress
60 : : // hostname lookups.
61 [ + + ]: 56436 : ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
62 : :
63 : 56436 : addrinfo* ai_res{nullptr};
64 : 56436 : const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
65 [ + + ]: 56436 : if (n_err != 0) {
66 [ + + ]: 112 : if ((ai_hint.ai_flags & AI_ADDRCONFIG) == AI_ADDRCONFIG) {
67 : : // AI_ADDRCONFIG on some systems may exclude loopback-only addresses
68 : : // If first lookup failed we perform a second lookup without AI_ADDRCONFIG
69 : 6 : ai_hint.ai_flags = (ai_hint.ai_flags & ~AI_ADDRCONFIG);
70 : 6 : const int n_err_retry{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
71 [ + + ]: 6 : if (n_err_retry != 0) {
72 : 5 : return {};
73 : : }
74 : : } else {
75 : 106 : return {};
76 : : }
77 : : }
78 : :
79 : : // Traverse the linked list starting with ai_trav.
80 : 56325 : addrinfo* ai_trav{ai_res};
81 : 56325 : std::vector<CNetAddr> resolved_addresses;
82 [ + + ]: 112662 : while (ai_trav != nullptr) {
83 [ + + ]: 56337 : if (ai_trav->ai_family == AF_INET) {
84 [ - + ]: 53600 : assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
85 [ + - ]: 53600 : resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
86 : : }
87 [ + + ]: 56337 : if (ai_trav->ai_family == AF_INET6) {
88 [ - + ]: 2737 : assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
89 : 2737 : const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
90 [ + - ]: 2737 : resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
91 : : }
92 : 56337 : ai_trav = ai_trav->ai_next;
93 : : }
94 : 56325 : freeaddrinfo(ai_res);
95 : :
96 : 56325 : return resolved_addresses;
97 : 56325 : }
98 : :
99 : : DNSLookupFn g_dns_lookup{WrappedGetAddrInfo};
100 : :
101 : 65 : enum Network ParseNetwork(const std::string& net_in) {
102 [ - + ]: 65 : std::string net = ToLower(net_in);
103 [ + + ]: 65 : if (net == "ipv4") return NET_IPV4;
104 [ + + ]: 52 : if (net == "ipv6") return NET_IPV6;
105 [ + + ]: 46 : if (net == "onion") return NET_ONION;
106 [ + + ]: 31 : if (net == "i2p") {
107 : : return NET_I2P;
108 : : }
109 [ + + ]: 23 : if (net == "cjdns") {
110 : 7 : return NET_CJDNS;
111 : : }
112 : : return NET_UNROUTABLE;
113 : 65 : }
114 : :
115 : 232560 : std::string GetNetworkName(enum Network net)
116 : : {
117 [ + + + + : 232560 : switch (net) {
+ + - -
- ]
118 : 31181 : case NET_UNROUTABLE: return "not_publicly_routable";
119 : 62871 : case NET_IPV4: return "ipv4";
120 : 35202 : case NET_IPV6: return "ipv6";
121 : 35239 : case NET_ONION: return "onion";
122 : 32953 : case NET_I2P: return "i2p";
123 : 35114 : case NET_CJDNS: return "cjdns";
124 : 0 : case NET_INTERNAL: return "internal";
125 : 0 : case NET_MAX: AssertUnreachable();
126 : : } // no default case, so the compiler can warn about missing cases
127 : :
128 : 0 : AssertUnreachable();
129 : : }
130 : :
131 : 31928 : std::vector<std::string> GetNetworkNames(bool append_unroutable)
132 : : {
133 : 31928 : std::vector<std::string> names;
134 [ + + ]: 255424 : for (int n = 0; n < NET_MAX; ++n) {
135 : 223496 : const enum Network network{static_cast<Network>(n)};
136 [ + + ]: 223496 : if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
137 [ + - + - ]: 319280 : names.emplace_back(GetNetworkName(network));
138 : : }
139 [ + + ]: 31928 : if (append_unroutable) {
140 [ + - + - ]: 25674 : names.emplace_back(GetNetworkName(NET_UNROUTABLE));
141 : : }
142 : 31928 : return names;
143 : 0 : }
144 : :
145 : 56545 : static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
146 : : {
147 [ - + - + ]: 113090 : if (ContainsNUL(name)) return {};
148 : 56545 : {
149 : 56545 : CNetAddr addr;
150 : : // From our perspective, onion addresses are not hostnames but rather
151 : : // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
152 : : // or IPv6 colon-separated hextet notation. Since we can't use
153 : : // getaddrinfo to decode them and it wouldn't make sense to resolve
154 : : // them, we return a network address representing it instead. See
155 : : // CNetAddr::SetSpecial(const std::string&) for more details.
156 [ - + + - : 56763 : if (addr.SetSpecial(name)) return {addr};
+ + + + -
- ]
157 : 109 : }
158 : :
159 : 56436 : std::vector<CNetAddr> addresses;
160 : :
161 [ + - + + ]: 112771 : for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
162 [ + - + + ]: 112674 : if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) {
163 : : break;
164 : : }
165 : : /* Never allow resolving to an internal address. Consider any such result invalid */
166 [ + - + + ]: 56335 : if (!resolved.IsInternal()) {
167 [ + - ]: 56334 : addresses.push_back(resolved);
168 : : }
169 : 56436 : }
170 : :
171 : 56436 : return addresses;
172 [ - + ]: 56545 : }
173 : :
174 : 42344 : std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
175 : : {
176 [ - + + + ]: 84688 : if (ContainsNUL(name)) return {};
177 : 42341 : std::string strHost = name;
178 [ + + ]: 42341 : if (strHost.empty()) return {};
179 [ + + + - ]: 42379 : if (strHost.front() == '[' && strHost.back() == ']') {
180 [ + - ]: 41 : strHost = strHost.substr(1, strHost.size() - 2);
181 : : }
182 : :
183 [ + - + - ]: 84676 : return LookupIntern(strHost, nMaxSolutions, fAllowLookup, dns_lookup_function);
184 : 42341 : }
185 : :
186 : 42344 : std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function)
187 : : {
188 [ + - ]: 42344 : const std::vector<CNetAddr> addresses{LookupHost(name, 1, fAllowLookup, dns_lookup_function)};
189 [ + + ]: 84688 : return addresses.empty() ? std::nullopt : std::make_optional(addresses.front());
190 : 42344 : }
191 : :
192 : 14210 : std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
193 : : {
194 [ + + + + ]: 42626 : if (name.empty() || ContainsNUL(name)) {
195 : 3 : return {};
196 : : }
197 : 14207 : uint16_t port{portDefault};
198 [ - + ]: 14207 : std::string hostname;
199 [ - + + - ]: 14207 : SplitHostPort(name, port, hostname);
200 : :
201 [ + - + - ]: 14207 : const std::vector<CNetAddr> addresses{LookupIntern(hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)};
202 [ + + ]: 14207 : if (addresses.empty()) return {};
203 : 14109 : std::vector<CService> services;
204 [ - + + - ]: 14109 : services.reserve(addresses.size());
205 [ + + ]: 28228 : for (const auto& addr : addresses)
206 [ + - ]: 14119 : services.emplace_back(addr, port);
207 : 14109 : return services;
208 : 14207 : }
209 : :
210 : 12478 : std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
211 : : {
212 [ + - ]: 12478 : const std::vector<CService> services{Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)};
213 : :
214 [ + + ]: 24956 : return services.empty() ? std::nullopt : std::make_optional(services.front());
215 : 12478 : }
216 : :
217 : 102 : CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
218 : : {
219 [ - + - + ]: 204 : if (ContainsNUL(name)) {
220 : 0 : return {};
221 : : }
222 : : // "1.2:345" will fail to resolve the ip, but will still set the port.
223 : : // If the ip fails to resolve, re-init the result.
224 [ + - + - ]: 102 : return Lookup(name, portDefault, /*fAllowLookup=*/false, dns_lookup_function).value_or(CService{});
225 : : }
226 : :
227 : 101 : bool IsUnixSocketPath(const std::string& name)
228 : : {
229 : : #ifdef HAVE_SOCKADDR_UN
230 [ - + - + : 101 : if (!name.starts_with(ADDR_PREFIX_UNIX)) return false;
+ + ]
231 : :
232 : : // Split off "unix:" prefix
233 : 43 : std::string str{name.substr(ADDR_PREFIX_UNIX.length())};
234 : :
235 : : // Path size limit is platform-dependent
236 : : // see https://manpages.ubuntu.com/manpages/xenial/en/man7/unix.7.html
237 [ - + + + ]: 43 : if (str.size() + 1 > sizeof(((sockaddr_un*)nullptr)->sun_path)) return false;
238 : :
239 : : return true;
240 : : #else
241 : : return false;
242 : : #endif
243 : 43 : }
244 : :
245 : : /** SOCKS version */
246 : : enum SOCKSVersion: uint8_t {
247 : : SOCKS4 = 0x04,
248 : : SOCKS5 = 0x05
249 : : };
250 : :
251 : : /** Values defined for METHOD in RFC1928 */
252 : : enum SOCKS5Method: uint8_t {
253 : : NOAUTH = 0x00, //!< No authentication required
254 : : GSSAPI = 0x01, //!< GSSAPI
255 : : USER_PASS = 0x02, //!< Username/password
256 : : NO_ACCEPTABLE = 0xff, //!< No acceptable methods
257 : : };
258 : :
259 : : /** Values defined for CMD in RFC1928 */
260 : : enum SOCKS5Command: uint8_t {
261 : : CONNECT = 0x01,
262 : : BIND = 0x02,
263 : : UDP_ASSOCIATE = 0x03
264 : : };
265 : :
266 : : /** Values defined for REP in RFC1928 and https://spec.torproject.org/socks-extensions.html */
267 : : enum SOCKS5Reply: uint8_t {
268 : : SUCCEEDED = 0x00, //!< RFC1928: Succeeded
269 : : GENFAILURE = 0x01, //!< RFC1928: General failure
270 : : NOTALLOWED = 0x02, //!< RFC1928: Connection not allowed by ruleset
271 : : NETUNREACHABLE = 0x03, //!< RFC1928: Network unreachable
272 : : HOSTUNREACHABLE = 0x04, //!< RFC1928: Network unreachable
273 : : CONNREFUSED = 0x05, //!< RFC1928: Connection refused
274 : : TTLEXPIRED = 0x06, //!< RFC1928: TTL expired
275 : : CMDUNSUPPORTED = 0x07, //!< RFC1928: Command not supported
276 : : ATYPEUNSUPPORTED = 0x08, //!< RFC1928: Address type not supported
277 : : TOR_HS_DESC_NOT_FOUND = 0xf0, //!< Tor: Onion service descriptor can not be found
278 : : TOR_HS_DESC_INVALID = 0xf1, //!< Tor: Onion service descriptor is invalid
279 : : TOR_HS_INTRO_FAILED = 0xf2, //!< Tor: Onion service introduction failed
280 : : TOR_HS_REND_FAILED = 0xf3, //!< Tor: Onion service rendezvous failed
281 : : TOR_HS_MISSING_CLIENT_AUTH = 0xf4, //!< Tor: Onion service missing client authorization
282 : : TOR_HS_WRONG_CLIENT_AUTH = 0xf5, //!< Tor: Onion service wrong client authorization
283 : : TOR_HS_BAD_ADDRESS = 0xf6, //!< Tor: Onion service invalid address
284 : : TOR_HS_INTRO_TIMEOUT = 0xf7, //!< Tor: Onion service introduction timed out
285 : : };
286 : :
287 : : /** Values defined for ATYPE in RFC1928 */
288 : : enum SOCKS5Atyp: uint8_t {
289 : : IPV4 = 0x01,
290 : : DOMAINNAME = 0x03,
291 : : IPV6 = 0x04,
292 : : };
293 : :
294 : : /** Status codes that can be returned by InterruptibleRecv */
295 : : enum class IntrRecvError {
296 : : OK,
297 : : Timeout,
298 : : Disconnected,
299 : : NetworkError,
300 : : Interrupted
301 : : };
302 : :
303 : : /**
304 : : * Try to read a specified number of bytes from a socket. Please read the "see
305 : : * also" section for more detail.
306 : : *
307 : : * @param data The buffer where the read bytes should be stored.
308 : : * @param len The number of bytes to read into the specified buffer.
309 : : * @param timeout The total timeout for this read.
310 : : * @param sock The socket (has to be in non-blocking mode) from which to read bytes.
311 : : *
312 : : * @returns An IntrRecvError indicating the resulting status of this read.
313 : : * IntrRecvError::OK only if all of the specified number of bytes were
314 : : * read.
315 : : *
316 : : * @see This function can be interrupted by calling g_socks5_interrupt().
317 : : * Sockets can be made non-blocking with Sock::SetNonBlocking().
318 : : */
319 : 417 : static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, std::chrono::milliseconds timeout, const Sock& sock)
320 : : {
321 : 417 : auto curTime{Now<SteadyMilliseconds>()};
322 : 417 : const auto endTime{curTime + timeout};
323 [ + + + - ]: 1051 : while (len > 0 && curTime < endTime) {
324 : 637 : ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
325 [ + + ]: 637 : if (ret > 0) {
326 : 414 : len -= ret;
327 : 414 : data += ret;
328 [ + - ]: 223 : } else if (ret == 0) { // Unexpected disconnection
329 : : return IntrRecvError::Disconnected;
330 : : } else { // Other error or blocking
331 : 223 : int nErr = WSAGetLastError();
332 [ - + - - ]: 223 : if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
333 : : // Only wait at most MAX_WAIT_FOR_IO at a time, unless
334 : : // we're approaching the end of the specified total timeout
335 : 223 : const auto remaining = std::chrono::milliseconds{endTime - curTime};
336 : 223 : const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
337 [ + - ]: 223 : if (!sock.Wait(timeout, Sock::RecvEvent)) {
338 : : return IntrRecvError::NetworkError;
339 : : }
340 : : } else {
341 : : return IntrRecvError::NetworkError;
342 : : }
343 : : }
344 [ + + ]: 637 : if (g_socks5_interrupt) {
345 : : return IntrRecvError::Interrupted;
346 : : }
347 : 634 : curTime = Now<SteadyMilliseconds>();
348 : : }
349 : 414 : return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
350 : : }
351 : :
352 : : /** Convert SOCKS5 reply to an error message */
353 : 0 : static std::string Socks5ErrorString(uint8_t err)
354 : : {
355 [ # # # # : 0 : switch(err) {
# # # # #
# # # # #
# # # ]
356 : 0 : case SOCKS5Reply::GENFAILURE:
357 : 0 : return "general failure";
358 : 0 : case SOCKS5Reply::NOTALLOWED:
359 : 0 : return "connection not allowed";
360 : 0 : case SOCKS5Reply::NETUNREACHABLE:
361 : 0 : return "network unreachable";
362 : 0 : case SOCKS5Reply::HOSTUNREACHABLE:
363 : 0 : return "host unreachable";
364 : 0 : case SOCKS5Reply::CONNREFUSED:
365 : 0 : return "connection refused";
366 : 0 : case SOCKS5Reply::TTLEXPIRED:
367 : 0 : return "TTL expired";
368 : 0 : case SOCKS5Reply::CMDUNSUPPORTED:
369 : 0 : return "protocol error";
370 : 0 : case SOCKS5Reply::ATYPEUNSUPPORTED:
371 : 0 : return "address type not supported";
372 : 0 : case SOCKS5Reply::TOR_HS_DESC_NOT_FOUND:
373 : 0 : return "onion service descriptor can not be found";
374 : 0 : case SOCKS5Reply::TOR_HS_DESC_INVALID:
375 : 0 : return "onion service descriptor is invalid";
376 : 0 : case SOCKS5Reply::TOR_HS_INTRO_FAILED:
377 : 0 : return "onion service introduction failed";
378 : 0 : case SOCKS5Reply::TOR_HS_REND_FAILED:
379 : 0 : return "onion service rendezvous failed";
380 : 0 : case SOCKS5Reply::TOR_HS_MISSING_CLIENT_AUTH:
381 : 0 : return "onion service missing client authorization";
382 : 0 : case SOCKS5Reply::TOR_HS_WRONG_CLIENT_AUTH:
383 : 0 : return "onion service wrong client authorization";
384 : 0 : case SOCKS5Reply::TOR_HS_BAD_ADDRESS:
385 : 0 : return "onion service invalid address";
386 : 0 : case SOCKS5Reply::TOR_HS_INTRO_TIMEOUT:
387 : 0 : return "onion service introduction timed out";
388 : 0 : default:
389 : 0 : return strprintf("unknown (0x%02x)", err);
390 : : }
391 : : }
392 : :
393 : 89 : bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
394 : : {
395 : 89 : try {
396 : 89 : IntrRecvError recvr;
397 [ + - + - : 89 : LogDebug(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
+ - ]
398 [ - + - + ]: 89 : if (strDest.size() > 255) {
399 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Hostname too long for SOCKS5 proxying: %s", strDest);
# # ]
400 : 0 : return false;
401 : : }
402 : : // Construct the version identifier/method selection message
403 : 89 : std::vector<uint8_t> vSocks5Init;
404 [ + - ]: 89 : vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
405 [ + + ]: 89 : if (auth) {
406 [ + - ]: 82 : vSocks5Init.push_back(0x02); // 2 method identifiers follow...
407 [ + - ]: 82 : vSocks5Init.push_back(SOCKS5Method::NOAUTH);
408 [ + - ]: 82 : vSocks5Init.push_back(SOCKS5Method::USER_PASS);
409 : : } else {
410 [ + - ]: 7 : vSocks5Init.push_back(0x01); // 1 method identifier follows...
411 [ + - ]: 7 : vSocks5Init.push_back(SOCKS5Method::NOAUTH);
412 : : }
413 [ - + + - ]: 89 : sock.SendComplete(vSocks5Init, g_socks5_recv_timeout, g_socks5_interrupt);
414 : 89 : uint8_t pchRet1[2];
415 [ + - + + ]: 89 : if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
416 [ + - + - : 3 : LogDebug(BCLog::PROXY, "Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure", strDest, port);
+ - ]
417 : 3 : return false;
418 : : }
419 [ - + ]: 86 : if (pchRet1[0] != SOCKSVersion::SOCKS5) {
420 [ # # # # : 0 : LogDebug(BCLog::PROXY, "SOCKS5 Proxy failed to initialize");
# # ]
421 : 0 : return false;
422 : : }
423 [ + + + - ]: 86 : if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
424 : : // Perform username/password authentication (as described in RFC1929)
425 : 70 : std::vector<uint8_t> vAuth;
426 [ + - ]: 70 : vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
427 [ - + + - : 70 : if (auth->username.size() > 255 || auth->password.size() > 255) {
- + - + ]
428 [ # # # # : 0 : LogWarnThenDebug(BCLog::PROXY, "SOCKS5 Proxy username or password too long");
# # # # #
# ]
429 : 0 : return false;
430 : : }
431 [ + - ]: 70 : vAuth.push_back(auth->username.size());
432 [ - + + - ]: 70 : vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
433 [ - + + - ]: 70 : vAuth.push_back(auth->password.size());
434 [ - + + - ]: 70 : vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
435 [ + - + - : 70 : LogDebug(BCLog::PROXY, "SOCKS5 sending username/password authentication\n");
+ - ]
436 [ - + + - ]: 70 : sock.SendComplete(vAuth, g_socks5_recv_timeout, g_socks5_interrupt);
437 : 70 : uint8_t pchRetA[2];
438 [ + - - + ]: 70 : if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
439 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Error reading SOCKS5 proxy authentication response");
# # ]
440 : 0 : return false;
441 : : }
442 [ + - - + ]: 70 : if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
443 [ # # # # : 0 : LogWarnThenDebug(BCLog::PROXY, "SOCKS5 Proxy authentication unsuccessful");
# # # # #
# ]
444 : 0 : return false;
445 : : }
446 [ - + ]: 86 : } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
447 : : // Perform no authentication
448 : : } else {
449 [ # # # # : 0 : LogWarnThenDebug(BCLog::PROXY, "SOCKS5 Proxy requested wrong authentication method %02x", pchRet1[1]);
# # # # #
# ]
450 : 0 : return false;
451 : : }
452 : 86 : std::vector<uint8_t> vSocks5;
453 [ + - ]: 86 : vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
454 [ + - ]: 86 : vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
455 [ + - ]: 86 : vSocks5.push_back(0x00); // RSV Reserved must be 0
456 [ + - ]: 86 : vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
457 [ - + + - ]: 86 : vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
458 [ - + + - ]: 86 : vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
459 [ + - ]: 86 : vSocks5.push_back((port >> 8) & 0xFF);
460 [ + - ]: 86 : vSocks5.push_back((port >> 0) & 0xFF);
461 [ - + + - ]: 86 : sock.SendComplete(vSocks5, g_socks5_recv_timeout, g_socks5_interrupt);
462 : 86 : uint8_t pchRet2[4];
463 [ + - - + ]: 86 : if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
464 [ # # ]: 0 : if (recvr == IntrRecvError::Timeout) {
465 : : /* If a timeout happens here, this effectively means we timed out while connecting
466 : : * to the remote node. This is very common for Tor, so do not print an
467 : : * error message. */
468 : : return false;
469 : : } else {
470 [ # # # # : 0 : LogDebug(BCLog::PROXY, "SOCKS5 Error while reading proxy response");
# # ]
471 : 0 : return false;
472 : : }
473 : : }
474 [ - + ]: 86 : if (pchRet2[0] != SOCKSVersion::SOCKS5) {
475 [ # # # # : 0 : LogDebug(BCLog::PROXY, "SOCKS5 Proxy failed to accept request");
# # ]
476 : 0 : return false;
477 : : }
478 [ - + ]: 86 : if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
479 : : // Failures to connect to a peer that are not proxy errors
480 [ # # # # : 0 : LogDebug(BCLog::PROXY,
# # # # ]
481 : : "Socks5() connect to %s:%d failed: %s", strDest, port, Socks5ErrorString(pchRet2[1]));
482 : 0 : return false;
483 : : }
484 [ - + ]: 86 : if (pchRet2[2] != 0x00) { // Reserved field must be 0
485 [ # # # # : 0 : LogDebug(BCLog::PROXY, "malformed SOCKS5 proxy response");
# # ]
486 : 0 : return false;
487 : : }
488 : 86 : uint8_t pchRet3[256];
489 [ + - - - ]: 86 : switch (pchRet2[3]) {
490 [ + - ]: 86 : case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
491 [ # # ]: 0 : case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
492 : 0 : case SOCKS5Atyp::DOMAINNAME: {
493 [ # # ]: 0 : recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
494 [ # # ]: 0 : if (recvr != IntrRecvError::OK) {
495 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Error reading from SOCKS5 proxy");
# # ]
496 : 0 : return false;
497 : : }
498 : 0 : int nRecv = pchRet3[0];
499 [ # # ]: 0 : recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
500 : : break;
501 : : }
502 : 0 : default: {
503 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Malformed SOCKS5 proxy response");
# # ]
504 : : return false;
505 : : }
506 : : }
507 [ - + ]: 86 : if (recvr != IntrRecvError::OK) {
508 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Error reading from SOCKS5 proxy");
# # ]
509 : 0 : return false;
510 : : }
511 [ + - - + ]: 86 : if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
512 [ # # # # : 0 : LogDebug(BCLog::PROXY, "Error reading from SOCKS5 proxy");
# # ]
513 : 0 : return false;
514 : : }
515 [ + - + - : 86 : LogDebug(BCLog::NET, "SOCKS5 connected %s\n", strDest);
+ - ]
516 : : return true;
517 [ - - ]: 175 : } catch (const std::runtime_error& e) {
518 [ - - - - : 0 : LogDebug(BCLog::PROXY, "Error during SOCKS5 proxy handshake: %s", e.what());
- - ]
519 : 0 : return false;
520 : 0 : }
521 : : }
522 : :
523 : 5470 : std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol)
524 : : {
525 : : // Not IPv4, IPv6 or UNIX
526 [ - + ]: 5470 : if (domain == AF_UNSPEC) return nullptr;
527 : :
528 : : // Create a socket in the specified address family.
529 : 5470 : SOCKET hSocket = socket(domain, type, protocol);
530 [ - + ]: 5470 : if (hSocket == INVALID_SOCKET) {
531 : 0 : return nullptr;
532 : : }
533 : :
534 : 5470 : auto sock = std::make_unique<Sock>(hSocket);
535 : :
536 [ + + - + ]: 5470 : if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNIX) {
537 : 0 : return sock;
538 : : }
539 : :
540 : : // Ensure that waiting for I/O on this socket won't result in undefined
541 : : // behavior.
542 [ + - - + ]: 5470 : if (!sock->IsSelectable()) {
543 [ # # # # : 0 : LogWarnThenDebug(BCLog::NET, "Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)");
# # # # #
# ]
544 : 0 : return nullptr;
545 : : }
546 : :
547 : : #ifdef SO_NOSIGPIPE
548 : : int set = 1;
549 : : // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
550 : : // should use the MSG_NOSIGNAL flag for every send.
551 : : if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof(int)) == SOCKET_ERROR) {
552 : : LogDebug(BCLog::NET, "Error setting SO_NOSIGPIPE on socket: %s, continuing anyway",
553 : : NetworkErrorString(WSAGetLastError()));
554 : : }
555 : : #endif
556 : :
557 : : // Set the non-blocking option on the socket.
558 [ + - - + ]: 5470 : if (!sock->SetNonBlocking()) {
559 [ # # # # : 0 : LogWarnThenDebug(BCLog::NET, "Error setting socket to non-blocking: %s", NetworkErrorString(WSAGetLastError()));
# # # # #
# # # #
# ]
560 : 0 : return nullptr;
561 : : }
562 : :
563 : : #ifdef HAVE_SOCKADDR_UN
564 [ + + ]: 5470 : if (domain == AF_UNIX) return sock;
565 : : #endif
566 : :
567 [ + - ]: 5466 : if (protocol == IPPROTO_TCP) {
568 : : // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
569 : 5466 : const int on{1};
570 [ + - - + ]: 5466 : if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
571 [ # # # # : 0 : LogDebug(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
# # ]
572 : : }
573 : : }
574 : :
575 : 5466 : return sock;
576 : 5470 : }
577 : :
578 : : std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock = CreateSockOS;
579 : :
580 : : template <typename... Args>
581 : 52 : static void LogConnectFailure(bool manual_connection, util::log::FormatString<sizeof...(Args)> fmt, const Args&... args)
582 : : {
583 : 52 : std::string error_message = tfm::format(fmt, args...);
584 [ + - ]: 52 : if (manual_connection) {
585 [ + - ]: 52 : LogInfo("%s", error_message);
586 : : } else {
587 [ - - - - : 52 : LogDebug(BCLog::NET, "%s", error_message);
- - ]
588 : : }
589 : 52 : }
590 : :
591 : 1831 : static bool ConnectToSocket(const Sock& sock,
592 : : struct sockaddr* sockaddr,
593 : : socklen_t len,
594 : : const std::string& dest_str,
595 : : bool manual_connection,
596 : : std::chrono::milliseconds timeout)
597 : : {
598 : : // Connect to `sockaddr` using `sock`.
599 [ + + ]: 1831 : if (sock.Connect(sockaddr, len) == SOCKET_ERROR) {
600 : 1811 : int nErr = WSAGetLastError();
601 : : // WSAEINVAL is here because some legacy version of winsock uses it
602 [ - + - - ]: 1811 : if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
603 : : {
604 : : // Connection didn't actually fail, but is being established
605 : : // asynchronously. Thus, use async I/O api (select/poll)
606 : : // synchronously to check for successful connection with a timeout.
607 : 1811 : const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent;
608 : 1811 : Sock::Event occurred;
609 [ - + ]: 1811 : if (!sock.Wait(timeout, requested, &occurred)) {
610 [ # # # # ]: 0 : LogDebug(BCLog::NET, "wait for connect to %s failed: %s",
611 : : dest_str,
612 : : NetworkErrorString(WSAGetLastError()));
613 : 0 : return false;
614 [ - + ]: 1811 : } else if (occurred == 0) {
615 [ # # ]: 0 : LogDebug(BCLog::NET, "connection attempt to %s timed out\n", dest_str);
616 : 0 : return false;
617 : : }
618 : :
619 : : // Even if the wait was successful, the connect might not
620 : : // have been successful. The reason for this failure is hidden away
621 : : // in the SO_ERROR for the socket in modern systems. We read it into
622 : : // sockerr here.
623 : 1811 : int sockerr;
624 : 1811 : socklen_t sockerr_len = sizeof(sockerr);
625 [ - + ]: 1811 : if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, &sockerr, &sockerr_len) ==
626 : : SOCKET_ERROR) {
627 [ # # # # : 0 : LogWarnThenDebug(BCLog::NET, "getsockopt() for %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError()));
# # # # ]
628 : 0 : return false;
629 : : }
630 [ + + ]: 1811 : if (sockerr != 0) {
631 [ + - ]: 52 : LogConnectFailure(manual_connection,
632 : : "connect() to %s failed after wait: %s",
633 : : dest_str,
634 : 52 : NetworkErrorString(sockerr));
635 : 52 : return false;
636 : : }
637 : : }
638 : : #ifdef WIN32
639 : : else if (WSAGetLastError() != WSAEISCONN)
640 : : #else
641 : : else
642 : : #endif
643 : : {
644 [ # # ]: 0 : LogConnectFailure(manual_connection, "connect() to %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError()));
645 : 0 : return false;
646 : : }
647 : : }
648 : : return true;
649 : : }
650 : :
651 : 785 : std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection)
652 : : {
653 : 785 : return ConnectDirectly(dest, manual_connection, std::chrono::milliseconds{nConnectTimeout});
654 : : }
655 : :
656 : 1827 : std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
657 : : bool manual_connection,
658 : : std::chrono::milliseconds timeout)
659 : : {
660 : 1827 : auto sock = CreateSock(dest.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
661 [ - + ]: 1827 : if (!sock) {
662 [ # # # # : 0 : LogDebug(BCLog::NET, "Cannot create a socket for connecting to %s", dest.ToStringAddrPort());
# # # # ]
663 : 0 : return {};
664 : : }
665 : :
666 : : // Create a sockaddr from the specified service.
667 : 1827 : struct sockaddr_storage sockaddr;
668 : 1827 : socklen_t len = sizeof(sockaddr);
669 [ + - - + ]: 1827 : if (!dest.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
670 [ # # # # : 0 : LogDebug(BCLog::NET, "Cannot get sockaddr for %s: unsupported network", dest.ToStringAddrPort());
# # # # ]
671 : 0 : return {};
672 : : }
673 : :
674 [ + - + - : 1827 : if (!ConnectToSocket(*sock, (struct sockaddr*)&sockaddr, len, dest.ToStringAddrPort(), manual_connection, timeout)) {
+ + ]
675 : 52 : return {};
676 : : }
677 : :
678 : 1775 : return sock;
679 : 1827 : }
680 : :
681 : 150 : std::unique_ptr<Sock> Proxy::Connect() const
682 : : {
683 [ - + ]: 150 : if (!IsValid()) return {};
684 : :
685 [ + + ]: 150 : if (!m_is_unix_socket) return ConnectDirectly(proxy, /*manual_connection=*/true);
686 : :
687 : : #ifdef HAVE_SOCKADDR_UN
688 : 4 : auto sock = CreateSock(AF_UNIX, SOCK_STREAM, 0);
689 [ - + ]: 4 : if (!sock) {
690 [ # # # # : 0 : LogWarnThenDebug(BCLog::PROXY, "Cannot create a socket for connecting to %s", m_unix_socket_path);
# # # # #
# ]
691 : 0 : return {};
692 : : }
693 : :
694 [ - + + - ]: 4 : const std::string path{m_unix_socket_path.substr(ADDR_PREFIX_UNIX.length())};
695 : :
696 : 4 : struct sockaddr_un addrun;
697 [ - + ]: 4 : memset(&addrun, 0, sizeof(addrun));
698 : 4 : addrun.sun_family = AF_UNIX;
699 : : // leave the last char in addrun.sun_path[] to be always '\0'
700 [ - + - + : 4 : memcpy(addrun.sun_path, path.c_str(), std::min(sizeof(addrun.sun_path) - 1, path.length()));
+ - ]
701 : 4 : socklen_t len = sizeof(addrun);
702 : :
703 [ + - - + ]: 4 : if (!ConnectToSocket(*sock,
704 : : (struct sockaddr*)&addrun,
705 : : len,
706 : : path,
707 : : /*manual_connection=*/true,
708 [ + - ]: 4 : std::chrono::milliseconds{nConnectTimeout})) {
709 : 0 : return {};
710 : : }
711 : :
712 : 4 : return sock;
713 : : #else
714 : : return {};
715 : : #endif
716 : 4 : }
717 : :
718 : 196 : bool SetProxy(enum Network net, const Proxy &addrProxy) {
719 [ - + ]: 196 : assert(net >= 0 && net < NET_MAX);
720 [ + - ]: 196 : if (!addrProxy.IsValid())
721 : : return false;
722 : 196 : LOCK(g_proxyinfo_mutex);
723 [ + - ]: 196 : proxyInfo[net] = addrProxy;
724 [ + - ]: 196 : return true;
725 : 196 : }
726 : :
727 : 6924 : std::optional<Proxy> GetProxy(enum Network net)
728 : : {
729 [ - + ]: 6924 : assert(net >= 0 && net < NET_MAX);
730 : 6924 : LOCK(g_proxyinfo_mutex);
731 [ + - + + ]: 6924 : if (!proxyInfo[net].IsValid()) {
732 : 6575 : return std::nullopt;
733 : : }
734 [ + - ]: 349 : return proxyInfo[net];
735 : 6924 : }
736 : :
737 : 43 : bool SetNameProxy(const Proxy &addrProxy) {
738 [ + - ]: 43 : if (!addrProxy.IsValid())
739 : : return false;
740 : 43 : LOCK(g_proxyinfo_mutex);
741 [ + - ]: 43 : nameProxy = addrProxy;
742 [ + - ]: 43 : return true;
743 : 43 : }
744 : :
745 : 16 : std::optional<Proxy> GetNameProxy()
746 : : {
747 : 16 : LOCK(g_proxyinfo_mutex);
748 [ + - + + ]: 16 : if (!nameProxy.IsValid()) {
749 : 2 : return std::nullopt;
750 : : }
751 [ + - ]: 14 : return nameProxy;
752 : 16 : }
753 : :
754 : 698 : bool HaveNameProxy() {
755 : 698 : LOCK(g_proxyinfo_mutex);
756 [ + - + - ]: 698 : return nameProxy.IsValid();
757 : 698 : }
758 : :
759 : 47 : bool IsProxy(const CNetAddr &addr) {
760 : 47 : LOCK(g_proxyinfo_mutex);
761 [ + + ]: 376 : for (int i = 0; i < NET_MAX; i++) {
762 [ + - + - ]: 329 : if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
763 : : return true;
764 : : }
765 : : return false;
766 : 47 : }
767 : :
768 : : /**
769 : : * Generate unique credentials for Tor stream isolation. Tor will create
770 : : * separate circuits for SOCKS5 proxy connections with different credentials, which
771 : : * makes it harder to correlate the connections.
772 : : */
773 : : class TorStreamIsolationCredentialsGenerator
774 : : {
775 : : public:
776 : 11 : TorStreamIsolationCredentialsGenerator():
777 : 11 : m_prefix(GenerateUniquePrefix()) {
778 : : }
779 : :
780 : : /** Return the next unique proxy credentials. */
781 : 82 : ProxyCredentials Generate() {
782 [ + - ]: 82 : ProxyCredentials auth;
783 [ + - + - ]: 164 : auth.username = auth.password = strprintf("%s%i", m_prefix, m_counter);
784 : 82 : ++m_counter;
785 : 82 : return auth;
786 : 0 : }
787 : :
788 : : /** Size of session prefix in bytes. */
789 : : static constexpr size_t PREFIX_BYTE_LENGTH = 8;
790 : : private:
791 : : const std::string m_prefix;
792 : : std::atomic<uint64_t> m_counter;
793 : :
794 : : /** Generate a random prefix for each of the credentials returned by this generator.
795 : : * This makes sure that different launches of the application (either successively or in parallel)
796 : : * will not share the same circuits, as would be the case with a bare counter.
797 : : */
798 : 11 : static std::string GenerateUniquePrefix() {
799 : 11 : std::array<uint8_t, PREFIX_BYTE_LENGTH> prefix_bytes;
800 : 11 : GetRandBytes(prefix_bytes);
801 [ + - ]: 22 : return HexStr(prefix_bytes) + "-";
802 : : }
803 : : };
804 : :
805 : 104 : std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
806 : : const std::string& dest,
807 : : uint16_t port,
808 : : bool& proxy_connection_failed)
809 : : {
810 : : // first connect to proxy server
811 : 104 : auto sock = proxy.Connect();
812 [ + + ]: 104 : if (!sock) {
813 : 15 : proxy_connection_failed = true;
814 : 15 : return {};
815 : : }
816 : :
817 : : // do socks negotiation
818 [ + + ]: 89 : if (proxy.m_tor_stream_isolation) {
819 [ + + + - : 82 : static TorStreamIsolationCredentialsGenerator generator;
+ - ]
820 [ + - ]: 82 : ProxyCredentials random_auth{generator.Generate()};
821 [ + - + + ]: 82 : if (!Socks5(dest, port, &random_auth, *sock)) {
822 : 3 : return {};
823 : : }
824 : 82 : } else {
825 [ + - - + ]: 7 : if (!Socks5(dest, port, nullptr, *sock)) {
826 : 0 : return {};
827 : : }
828 : : }
829 : 86 : return sock;
830 : 104 : }
831 : :
832 : 385 : CSubNet LookupSubNet(const std::string& subnet_str)
833 : : {
834 : 385 : CSubNet subnet;
835 [ + - - + ]: 385 : assert(!subnet.IsValid());
836 [ - + + + ]: 770 : if (ContainsNUL(subnet_str)) {
837 : : return subnet;
838 : : }
839 : :
840 [ + - ]: 379 : const size_t slash_pos{subnet_str.find_last_of('/')};
841 [ + - ]: 379 : const std::string str_addr{subnet_str.substr(0, slash_pos)};
842 [ + - + - ]: 379 : std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)};
843 : :
844 [ + + ]: 379 : if (addr.has_value()) {
845 [ + - + - ]: 372 : addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
846 [ + + ]: 372 : if (slash_pos != subnet_str.npos) {
847 [ + - ]: 103 : const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
848 [ - + + + ]: 103 : if (const auto netmask{ToIntegral<uint8_t>(netmask_str)}) {
849 : : // Valid number; assume CIDR variable-length subnet masking.
850 [ + - + - ]: 56 : subnet = CSubNet{addr.value(), *netmask};
851 : : } else {
852 : : // Invalid number; try full netmask syntax. Never allow lookup for netmask.
853 [ + - + - ]: 47 : const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)};
854 [ + + ]: 47 : if (full_netmask.has_value()) {
855 [ - + + - ]: 44 : subnet = CSubNet{addr.value(), full_netmask.value()};
856 : : }
857 : 47 : }
858 : 103 : } else {
859 : : // Single IP subnet (<ipv4>/32 or <ipv6>/128).
860 [ + - + - ]: 269 : subnet = CSubNet{addr.value()};
861 : : }
862 : : }
863 : :
864 : 379 : return subnet;
865 : 379 : }
866 : :
867 : 66707 : bool IsBadPort(uint16_t port)
868 : : {
869 : : /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */
870 : :
871 [ + + ]: 66707 : switch (port) {
872 : : case 1: // tcpmux
873 : : case 7: // echo
874 : : case 9: // discard
875 : : case 11: // systat
876 : : case 13: // daytime
877 : : case 15: // netstat
878 : : case 17: // qotd
879 : : case 19: // chargen
880 : : case 20: // ftp data
881 : : case 21: // ftp access
882 : : case 22: // ssh
883 : : case 23: // telnet
884 : : case 25: // smtp
885 : : case 37: // time
886 : : case 42: // name
887 : : case 43: // nicname
888 : : case 53: // domain
889 : : case 69: // tftp
890 : : case 77: // priv-rjs
891 : : case 79: // finger
892 : : case 87: // ttylink
893 : : case 95: // supdup
894 : : case 101: // hostname
895 : : case 102: // iso-tsap
896 : : case 103: // gppitnp
897 : : case 104: // acr-nema
898 : : case 109: // pop2
899 : : case 110: // pop3
900 : : case 111: // sunrpc
901 : : case 113: // auth
902 : : case 115: // sftp
903 : : case 117: // uucp-path
904 : : case 119: // nntp
905 : : case 123: // NTP
906 : : case 135: // loc-srv /epmap
907 : : case 137: // netbios
908 : : case 139: // netbios
909 : : case 143: // imap2
910 : : case 161: // snmp
911 : : case 179: // BGP
912 : : case 389: // ldap
913 : : case 427: // SLP (Also used by Apple Filing Protocol)
914 : : case 465: // smtp+ssl
915 : : case 512: // print / exec
916 : : case 513: // login
917 : : case 514: // shell
918 : : case 515: // printer
919 : : case 526: // tempo
920 : : case 530: // courier
921 : : case 531: // chat
922 : : case 532: // netnews
923 : : case 540: // uucp
924 : : case 548: // AFP (Apple Filing Protocol)
925 : : case 554: // rtsp
926 : : case 556: // remotefs
927 : : case 563: // nntp+ssl
928 : : case 587: // smtp (rfc6409)
929 : : case 601: // syslog-conn (rfc3195)
930 : : case 636: // ldap+ssl
931 : : case 989: // ftps-data
932 : : case 990: // ftps
933 : : case 993: // ldap+ssl
934 : : case 995: // pop3+ssl
935 : : case 1719: // h323gatestat
936 : : case 1720: // h323hostcall
937 : : case 1723: // pptp
938 : : case 2049: // nfs
939 : : case 3306: // MySQL
940 : : case 3389: // RDP / Windows Remote Desktop
941 : : case 3659: // apple-sasl / PasswordServer
942 : : case 4045: // lockd
943 : : case 5060: // sip
944 : : case 5061: // sips
945 : : case 5432: // PostgreSQL
946 : : case 5900: // VNC
947 : : case 6000: // X11
948 : : case 6566: // sane-port
949 : : case 6665: // Alternate IRC
950 : : case 6666: // Alternate IRC
951 : : case 6667: // Standard IRC
952 : : case 6668: // Alternate IRC
953 : : case 6669: // Alternate IRC
954 : : case 6697: // IRC + TLS
955 : : case 10080: // Amanda
956 : : case 27017: // MongoDB
957 : : return true;
958 : : }
959 : 66619 : return false;
960 : : }
961 : :
962 : 36991 : CService MaybeFlipIPv6toCJDNS(const CService& service)
963 : : {
964 : 36991 : CService ret{service};
965 [ + + + - : 37091 : if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) {
+ + + - +
- ]
966 : 30 : ret.m_net = NET_CJDNS;
967 : : }
968 : 36991 : return ret;
969 : 0 : }
970 : :
971 : 1862 : CService GetBindAddress(const Sock& sock)
972 : : {
973 : 1862 : CService addr_bind;
974 : 1862 : sockaddr_storage storage;
975 : 1862 : socklen_t len = sizeof(storage);
976 : :
977 : 1862 : auto sa = reinterpret_cast<sockaddr*>(&storage);
978 : :
979 [ + - + - ]: 1862 : if (sock.GetSockName(sa, &len) == 0) {
980 [ + - ]: 1862 : addr_bind.SetSockAddr(sa, len);
981 : : } else {
982 [ # # ]: 0 : LogWarning("getsockname failed");
983 : : }
984 : 1862 : return addr_bind;
985 : 0 : }
|