Branch data Line data Source code
1 : : // Copyright (c) 2009-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_NETBASE_H
6 : : #define BITCOIN_NETBASE_H
7 : :
8 : : #include <compat/compat.h>
9 : : #include <netaddress.h>
10 : : #include <serialize.h>
11 : : #include <util/sock.h>
12 : : #include <util/threadinterrupt.h>
13 : :
14 : : #include <chrono>
15 : : #include <cstdint>
16 : : #include <functional>
17 : : #include <memory>
18 : : #include <optional>
19 : : #include <string>
20 : : #include <type_traits>
21 : : #include <unordered_set>
22 : : #include <vector>
23 : :
24 : : extern int nConnectTimeout;
25 : : extern bool fNameLookup;
26 : :
27 : : //! -timeout default
28 : : inline constexpr int DEFAULT_CONNECT_TIMEOUT = 5000;
29 : : //! -dns default
30 : : inline constexpr int DEFAULT_NAME_LOOKUP = true;
31 : :
32 : : /** Prefix for unix domain socket addresses (which are local filesystem paths) */
33 : : inline const std::string ADDR_PREFIX_UNIX = "unix:";
34 : :
35 : : enum class ConnectionDirection {
36 : : None = 0,
37 : : In = (1U << 0),
38 : : Out = (1U << 1),
39 : : Both = (In | Out),
40 : : };
41 : 1331 : static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {
42 : 1331 : using underlying = std::underlying_type_t<ConnectionDirection>;
43 : 1331 : a = ConnectionDirection(underlying(a) | underlying(b));
44 : 1331 : return a;
45 : : }
46 : 287194 : static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {
47 : 287194 : using underlying = std::underlying_type_t<ConnectionDirection>;
48 [ + + ]: 287194 : return (underlying(a) & underlying(b));
[ # # # # ]
49 : : }
50 : :
51 : : /**
52 : : * Check if a string is a valid UNIX domain socket path
53 : : *
54 : : * @param name The string provided by the user representing a local path
55 : : *
56 : : * @returns Whether the string has proper format, length, and points to an existing file path
57 : : */
58 : : bool IsUnixSocketPath(const std::string& name);
59 : :
60 [ # # ]: 39054 : class Proxy
61 : : {
62 : : public:
63 : 0 : Proxy() : m_is_unix_socket(false), m_tor_stream_isolation(false) {}
[ # # # #
# # # # #
# # # # #
# # # # ]
64 : 31407 : explicit Proxy(const CService& _proxy, bool tor_stream_isolation = false) : proxy(_proxy), m_is_unix_socket(false), m_tor_stream_isolation(tor_stream_isolation) {}
65 : 0 : explicit Proxy(std::string path, bool tor_stream_isolation = false)
66 [ # # # # ]: 0 : : m_unix_socket_path(std::move(path)), m_is_unix_socket(true), m_tor_stream_isolation(tor_stream_isolation) {}
67 : :
68 : : CService proxy;
69 : : std::string m_unix_socket_path;
70 : : bool m_is_unix_socket;
71 : : bool m_tor_stream_isolation;
72 : :
73 : 35179 : bool IsValid() const
74 : : {
75 [ - + ]: 35179 : if (m_is_unix_socket) return IsUnixSocketPath(m_unix_socket_path);
76 : 35179 : return proxy.IsValid();
77 : : }
78 : :
79 : 950 : std::string ToString() const
80 : : {
81 [ - + - - ]: 950 : if (m_is_unix_socket) return m_unix_socket_path;
82 : 950 : return proxy.ToStringAddrPort();
83 : : }
84 : :
85 : : std::unique_ptr<Sock> Connect() const;
86 : : };
87 : :
88 : : /** Credentials for proxy authentication */
89 [ + - ]: 318 : struct ProxyCredentials
90 : : {
91 : : std::string username;
92 : : std::string password;
93 : : };
94 : :
95 : : /**
96 : : * List of reachable networks. Everything is reachable by default.
97 : : */
98 : : class ReachableNets {
99 : : public:
100 : 6435 : void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
101 : : {
102 : 6435 : AssertLockNotHeld(m_mutex);
103 : 6435 : LOCK(m_mutex);
104 [ + - + - ]: 6435 : m_reachable.insert(net);
105 : 6435 : }
106 : :
107 : 0 : void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
108 : : {
109 : 0 : AssertLockNotHeld(m_mutex);
110 : 0 : LOCK(m_mutex);
111 [ # # ]: 0 : m_reachable.erase(net);
112 : 0 : }
113 : :
114 : 0 : void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
115 : : {
116 : 0 : AssertLockNotHeld(m_mutex);
117 : 0 : LOCK(m_mutex);
118 [ # # ]: 0 : m_reachable.clear();
119 : 0 : }
120 : :
121 : 1770 : void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
122 : : {
123 : 1770 : AssertLockNotHeld(m_mutex);
124 : 1770 : LOCK(m_mutex);
125 [ + - + - ]: 1770 : m_reachable = DefaultNets();
126 : 1770 : }
127 : :
128 : 505606 : [[nodiscard]] bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
129 : : {
130 : 505606 : AssertLockNotHeld(m_mutex);
131 : 505606 : LOCK(m_mutex);
132 [ + - ]: 505606 : return m_reachable.contains(net);
133 : 505606 : }
134 : :
135 : 504679 : [[nodiscard]] bool Contains(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
136 : : {
137 : 504679 : AssertLockNotHeld(m_mutex);
138 : 504679 : return Contains(addr.GetNetwork());
139 : : }
140 : :
141 : 0 : [[nodiscard]] std::unordered_set<Network> All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
142 : : {
143 : 0 : AssertLockNotHeld(m_mutex);
144 : 0 : LOCK(m_mutex);
145 [ # # # # ]: 0 : return m_reachable;
146 : 0 : }
147 : :
148 : : private:
149 : 2008 : static std::unordered_set<Network> DefaultNets()
150 : : {
151 : 2008 : return {
152 : : NET_UNROUTABLE,
153 : : NET_IPV4,
154 : : NET_IPV6,
155 : : NET_ONION,
156 : : NET_I2P,
157 : : NET_CJDNS,
158 : : NET_INTERNAL
159 : 2008 : };
160 : : };
161 : :
162 : : mutable Mutex m_mutex;
163 : : std::unordered_set<Network> m_reachable GUARDED_BY(m_mutex){DefaultNets()};
164 : : };
165 : :
166 : : extern ReachableNets g_reachable_nets;
167 : :
168 : : /**
169 : : * Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.
170 : : */
171 : : std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup);
172 : :
173 : : enum Network ParseNetwork(const std::string& net);
174 : : std::string GetNetworkName(enum Network net);
175 : : /** Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE. */
176 : : std::vector<std::string> GetNetworkNames(bool append_unroutable = false);
177 : : bool SetProxy(enum Network net, const Proxy &addrProxy);
178 : : std::optional<Proxy> GetProxy(enum Network net);
179 : : bool IsProxy(const CNetAddr &addr);
180 : : /**
181 : : * Set the name proxy to use for all connections to nodes specified by a
182 : : * hostname. After setting this proxy, connecting to a node specified by a
183 : : * hostname won't result in a local lookup of said hostname, rather, connect to
184 : : * the node by asking the name proxy for a proxy connection to the hostname,
185 : : * effectively delegating the hostname lookup to the specified proxy.
186 : : *
187 : : * This delegation increases privacy for those who set the name proxy as they no
188 : : * longer leak their external hostname queries to their DNS servers.
189 : : *
190 : : * @returns Whether or not the operation succeeded.
191 : : *
192 : : * @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5
193 : : * server in common use (most notably Tor) actually implements UDP
194 : : * support, and a DNS resolver is beyond the scope of this project.
195 : : */
196 : : bool SetNameProxy(const Proxy &addrProxy);
197 : : bool HaveNameProxy();
198 : : std::optional<Proxy> GetNameProxy();
199 : :
200 : : using DNSLookupFn = std::function<std::vector<CNetAddr>(const std::string&, bool)>;
201 : : extern DNSLookupFn g_dns_lookup;
202 : :
203 : : /**
204 : : * Resolve a host string to its corresponding network addresses.
205 : : *
206 : : * @param name The string representing a host. Could be a name or a numerical
207 : : * IP address (IPv6 addresses in their bracketed form are
208 : : * allowed).
209 : : *
210 : : * @returns The resulting network addresses to which the specified host
211 : : * string resolved.
212 : : *
213 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
214 : : * for additional parameter descriptions.
215 : : */
216 : : std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
217 : :
218 : : /**
219 : : * Resolve a host string to its first corresponding network address.
220 : : *
221 : : * @returns The resulting network address to which the specified host
222 : : * string resolved or std::nullopt if host does not resolve to an address.
223 : : *
224 : : * @see LookupHost(const std::string&, unsigned int, bool, DNSLookupFn)
225 : : * for additional parameter descriptions.
226 : : */
227 : : std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
228 : :
229 : : /**
230 : : * Resolve a service string to its corresponding service.
231 : : *
232 : : * @param name The string representing a service. Could be a name or a
233 : : * numerical IP address (IPv6 addresses should be in their
234 : : * disambiguated bracketed form), optionally followed by a uint16_t port
235 : : * number. (e.g. example.com:8333 or
236 : : * [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420)
237 : : * @param portDefault The default port for resulting services if not specified
238 : : * by the service string.
239 : : * @param fAllowLookup Whether or not hostname lookups are permitted. If yes,
240 : : * external queries may be performed.
241 : : * @param nMaxSolutions The maximum number of results we want, specifying 0
242 : : * means "as many solutions as we get."
243 : : *
244 : : * @returns The resulting services to which the specified service string
245 : : * resolved.
246 : : */
247 : : std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function = g_dns_lookup);
248 : :
249 : : /**
250 : : * Resolve a service string to its first corresponding service.
251 : : *
252 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
253 : : * for additional parameter descriptions.
254 : : */
255 : : std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
256 : :
257 : : /**
258 : : * Resolve a service string with a numeric IP to its first corresponding
259 : : * service.
260 : : *
261 : : * @returns The resulting CService if the resolution was successful, [::]:0 otherwise.
262 : : *
263 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
264 : : * for additional parameter descriptions.
265 : : */
266 : : CService LookupNumeric(const std::string& name, uint16_t portDefault = 0, DNSLookupFn dns_lookup_function = g_dns_lookup);
267 : :
268 : : /**
269 : : * Parse and resolve a specified subnet string into the appropriate internal
270 : : * representation.
271 : : *
272 : : * @param[in] subnet_str A string representation of a subnet of the form
273 : : * `network address [ "/", ( CIDR-style suffix | netmask ) ]`
274 : : * e.g. "2001:db8::/32", "192.0.2.0/255.255.255.0" or "8.8.8.8".
275 : : * @returns a CSubNet object (that may or may not be valid).
276 : : */
277 : : CSubNet LookupSubNet(const std::string& subnet_str);
278 : :
279 : : /**
280 : : * Create a real socket from the operating system.
281 : : * @param[in] domain Communications domain, first argument to the socket(2) syscall.
282 : : * @param[in] type Type of the socket, second argument to the socket(2) syscall.
283 : : * @param[in] protocol The particular protocol to be used with the socket, third argument to the socket(2) syscall.
284 : : * @return pointer to the created Sock object or unique_ptr that owns nothing in case of failure
285 : : */
286 : : std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol);
287 : :
288 : : /**
289 : : * Socket factory. Defaults to `CreateSockOS()`, but can be overridden by unit tests.
290 : : */
291 : : extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
292 : :
293 : : /**
294 : : * Create a socket and try to connect to the specified service.
295 : : *
296 : : * @param[in] dest The service to which to connect.
297 : : * @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
298 : : *
299 : : * @returns the connected socket if the operation succeeded, empty unique_ptr otherwise
300 : : */
301 : : std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection);
302 : :
303 : : /** Create a socket and try to connect to the specified service, using the provided timeout. */
304 : : std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
305 : : bool manual_connection,
306 : : std::chrono::milliseconds timeout);
307 : :
308 : : /**
309 : : * Connect to a specified destination service through a SOCKS5 proxy by first
310 : : * connecting to the SOCKS5 proxy.
311 : : *
312 : : * @param[in] proxy The SOCKS5 proxy.
313 : : * @param[in] dest The destination service to which to connect.
314 : : * @param[in] port The destination port.
315 : : * @param[out] proxy_connection_failed Whether or not the connection to the SOCKS5 proxy failed.
316 : : *
317 : : * @returns the connected socket if the operation succeeded. Otherwise an empty unique_ptr.
318 : : */
319 : : std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
320 : : const std::string& dest,
321 : : uint16_t port,
322 : : bool& proxy_connection_failed);
323 : :
324 : : /**
325 : : * Interrupt SOCKS5 reads or writes.
326 : : */
327 : : extern CThreadInterrupt g_socks5_interrupt;
328 : :
329 : : /**
330 : : * Connect to a specified destination service through an already connected
331 : : * SOCKS5 proxy.
332 : : *
333 : : * @param strDest The destination fully-qualified domain name.
334 : : * @param port The destination port.
335 : : * @param auth The credentials with which to authenticate with the specified
336 : : * SOCKS5 proxy.
337 : : * @param socket The SOCKS5 proxy socket.
338 : : *
339 : : * @returns Whether or not the operation succeeded.
340 : : *
341 : : * @note The specified SOCKS5 proxy socket must already be connected to the
342 : : * SOCKS5 proxy.
343 : : *
344 : : * @see <a href="https://www.ietf.org/rfc/rfc1928.txt">RFC1928: SOCKS Protocol
345 : : * Version 5</a>
346 : : */
347 : : bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& socket);
348 : :
349 : : /**
350 : : * Determine if a port is "bad" from the perspective of attempting to connect
351 : : * to a node on that port.
352 : : * @see doc/p2p-bad-ports.md
353 : : * @param[in] port Port to check.
354 : : * @returns whether the port is bad
355 : : */
356 : : bool IsBadPort(uint16_t port);
357 : :
358 : : /**
359 : : * If an IPv6 address belongs to the address range used by the CJDNS network and
360 : : * the CJDNS network is reachable (-cjdnsreachable config is set), then change
361 : : * the type from NET_IPV6 to NET_CJDNS.
362 : : * @param[in] service Address to potentially convert.
363 : : * @return a copy of `service` either unmodified or changed to CJDNS.
364 : : */
365 : : CService MaybeFlipIPv6toCJDNS(const CService& service);
366 : :
367 : : /** Get the bind address for a socket as CService. */
368 : : CService GetBindAddress(const Sock& sock);
369 : :
370 : : #endif // BITCOIN_NETBASE_H
|