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 <cstdint>
15 : : #include <functional>
16 : : #include <memory>
17 : : #include <optional>
18 : : #include <string>
19 : : #include <type_traits>
20 : : #include <unordered_set>
21 : : #include <vector>
22 : :
23 : : extern int nConnectTimeout;
24 : : extern bool fNameLookup;
25 : :
26 : : //! -timeout default
27 : : static const int DEFAULT_CONNECT_TIMEOUT = 5000;
28 : : //! -dns default
29 : : static const int DEFAULT_NAME_LOOKUP = true;
30 : :
31 : : /** Prefix for unix domain socket addresses (which are local filesystem paths) */
32 : : const std::string ADDR_PREFIX_UNIX = "unix:";
33 : :
34 : : enum class ConnectionDirection {
35 : : None = 0,
36 : : In = (1U << 0),
37 : : Out = (1U << 1),
38 : : Both = (In | Out),
39 : : };
40 : 4 : static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {
41 : 4 : using underlying = std::underlying_type_t<ConnectionDirection>;
42 : 4 : a = ConnectionDirection(underlying(a) | underlying(b));
43 : 4 : return a;
44 : : }
45 : 0 : static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {
46 : 0 : using underlying = std::underlying_type_t<ConnectionDirection>;
47 [ # # # # ]: 0 : return (underlying(a) & underlying(b));
[ # # # # ]
48 : : }
49 : :
50 : : /**
51 : : * Check if a string is a valid UNIX domain socket path
52 : : *
53 : : * @param name The string provided by the user representing a local path
54 : : *
55 : : * @returns Whether the string has proper format, length, and points to an existing file path
56 : : */
57 : : bool IsUnixSocketPath(const std::string& name);
58 : :
59 [ - - ]: 15 : class Proxy
60 : : {
61 : : public:
62 [ + - + - : 1 : Proxy() : m_is_unix_socket(false), m_tor_stream_isolation(false) {}
+ - + - +
- + - - -
- - - - ]
63 : 7 : explicit Proxy(const CService& _proxy, bool tor_stream_isolation = false) : proxy(_proxy), m_is_unix_socket(false), m_tor_stream_isolation(tor_stream_isolation) {}
64 : 0 : explicit Proxy(std::string path, bool tor_stream_isolation = false)
65 [ # # # # ]: 0 : : m_unix_socket_path(std::move(path)), m_is_unix_socket(true), m_tor_stream_isolation(tor_stream_isolation) {}
66 : :
67 : : CService proxy;
68 : : std::string m_unix_socket_path;
69 : : bool m_is_unix_socket;
70 : : bool m_tor_stream_isolation;
71 : :
72 : 48 : bool IsValid() const
73 : : {
74 [ - + ]: 48 : if (m_is_unix_socket) return IsUnixSocketPath(m_unix_socket_path);
75 : 48 : return proxy.IsValid();
76 : : }
77 : :
78 : : sa_family_t GetFamily() const
79 : : {
80 : : if (m_is_unix_socket) return AF_UNIX;
81 : : return proxy.GetSAFamily();
82 : : }
83 : :
84 : 11 : std::string ToString() const
85 : : {
86 [ - + - - ]: 11 : if (m_is_unix_socket) return m_unix_socket_path;
87 : 11 : return proxy.ToStringAddrPort();
88 : : }
89 : :
90 : : std::unique_ptr<Sock> Connect() const;
91 : : };
92 : :
93 : : /** Credentials for proxy authentication */
94 [ # # ]: 0 : struct ProxyCredentials
95 : : {
96 : : std::string username;
97 : : std::string password;
98 : : };
99 : :
100 : : /**
101 : : * List of reachable networks. Everything is reachable by default.
102 : : */
103 : : class ReachableNets {
104 : : public:
105 : 16 : void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
106 : : {
107 : 16 : AssertLockNotHeld(m_mutex);
108 : 16 : LOCK(m_mutex);
109 [ + - + - ]: 16 : m_reachable.insert(net);
110 : 16 : }
111 : :
112 : 9 : void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
113 : : {
114 : 9 : AssertLockNotHeld(m_mutex);
115 : 9 : LOCK(m_mutex);
116 [ + - ]: 9 : m_reachable.erase(net);
117 : 9 : }
118 : :
119 : 1 : void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
120 : : {
121 : 1 : AssertLockNotHeld(m_mutex);
122 : 1 : LOCK(m_mutex);
123 [ + - ]: 1 : m_reachable.clear();
124 : 1 : }
125 : :
126 : 654 : void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
127 : : {
128 : 654 : AssertLockNotHeld(m_mutex);
129 : 654 : LOCK(m_mutex);
130 [ + - + - ]: 654 : m_reachable = DefaultNets();
131 : 654 : }
132 : :
133 : 71 : [[nodiscard]] bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
134 : : {
135 : 71 : AssertLockNotHeld(m_mutex);
136 : 71 : LOCK(m_mutex);
137 [ + - ]: 71 : return m_reachable.contains(net);
138 : 71 : }
139 : :
140 : 17 : [[nodiscard]] bool Contains(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
141 : : {
142 : 17 : AssertLockNotHeld(m_mutex);
143 : 17 : return Contains(addr.GetNetwork());
144 : : }
145 : :
146 : 0 : [[nodiscard]] std::unordered_set<Network> All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
147 : : {
148 : 0 : AssertLockNotHeld(m_mutex);
149 : 0 : LOCK(m_mutex);
150 [ # # # # ]: 0 : return m_reachable;
151 : 0 : }
152 : :
153 : : private:
154 : 809 : static std::unordered_set<Network> DefaultNets()
155 : : {
156 : 809 : return {
157 : : NET_UNROUTABLE,
158 : : NET_IPV4,
159 : : NET_IPV6,
160 : : NET_ONION,
161 : : NET_I2P,
162 : : NET_CJDNS,
163 : : NET_INTERNAL
164 : 809 : };
165 : : };
166 : :
167 : : mutable Mutex m_mutex;
168 : : std::unordered_set<Network> m_reachable GUARDED_BY(m_mutex){DefaultNets()};
169 : : };
170 : :
171 : : extern ReachableNets g_reachable_nets;
172 : :
173 : : /**
174 : : * Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.
175 : : */
176 : : std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup);
177 : :
178 : : enum Network ParseNetwork(const std::string& net);
179 : : std::string GetNetworkName(enum Network net);
180 : : /** Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE. */
181 : : std::vector<std::string> GetNetworkNames(bool append_unroutable = false);
182 : : bool SetProxy(enum Network net, const Proxy &addrProxy);
183 : : std::optional<Proxy> GetProxy(enum Network net);
184 : : bool IsProxy(const CNetAddr &addr);
185 : : /**
186 : : * Set the name proxy to use for all connections to nodes specified by a
187 : : * hostname. After setting this proxy, connecting to a node specified by a
188 : : * hostname won't result in a local lookup of said hostname, rather, connect to
189 : : * the node by asking the name proxy for a proxy connection to the hostname,
190 : : * effectively delegating the hostname lookup to the specified proxy.
191 : : *
192 : : * This delegation increases privacy for those who set the name proxy as they no
193 : : * longer leak their external hostname queries to their DNS servers.
194 : : *
195 : : * @returns Whether or not the operation succeeded.
196 : : *
197 : : * @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5
198 : : * server in common use (most notably Tor) actually implements UDP
199 : : * support, and a DNS resolver is beyond the scope of this project.
200 : : */
201 : : bool SetNameProxy(const Proxy &addrProxy);
202 : : bool HaveNameProxy();
203 : : std::optional<Proxy> GetNameProxy();
204 : :
205 : : using DNSLookupFn = std::function<std::vector<CNetAddr>(const std::string&, bool)>;
206 : : extern DNSLookupFn g_dns_lookup;
207 : :
208 : : /**
209 : : * Resolve a host string to its corresponding network addresses.
210 : : *
211 : : * @param name The string representing a host. Could be a name or a numerical
212 : : * IP address (IPv6 addresses in their bracketed form are
213 : : * allowed).
214 : : *
215 : : * @returns The resulting network addresses to which the specified host
216 : : * string resolved.
217 : : *
218 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
219 : : * for additional parameter descriptions.
220 : : */
221 : : std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
222 : :
223 : : /**
224 : : * Resolve a host string to its first corresponding network address.
225 : : *
226 : : * @returns The resulting network address to which the specified host
227 : : * string resolved or std::nullopt if host does not resolve to an address.
228 : : *
229 : : * @see LookupHost(const std::string&, unsigned int, bool, DNSLookupFn)
230 : : * for additional parameter descriptions.
231 : : */
232 : : std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
233 : :
234 : : /**
235 : : * Resolve a service string to its corresponding service.
236 : : *
237 : : * @param name The string representing a service. Could be a name or a
238 : : * numerical IP address (IPv6 addresses should be in their
239 : : * disambiguated bracketed form), optionally followed by a uint16_t port
240 : : * number. (e.g. example.com:8333 or
241 : : * [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420)
242 : : * @param portDefault The default port for resulting services if not specified
243 : : * by the service string.
244 : : * @param fAllowLookup Whether or not hostname lookups are permitted. If yes,
245 : : * external queries may be performed.
246 : : * @param nMaxSolutions The maximum number of results we want, specifying 0
247 : : * means "as many solutions as we get."
248 : : *
249 : : * @returns The resulting services to which the specified service string
250 : : * resolved.
251 : : */
252 : : std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function = g_dns_lookup);
253 : :
254 : : /**
255 : : * Resolve a service string to its first corresponding service.
256 : : *
257 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
258 : : * for additional parameter descriptions.
259 : : */
260 : : std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
261 : :
262 : : /**
263 : : * Resolve a service string with a numeric IP to its first corresponding
264 : : * service.
265 : : *
266 : : * @returns The resulting CService if the resolution was successful, [::]:0 otherwise.
267 : : *
268 : : * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
269 : : * for additional parameter descriptions.
270 : : */
271 : : CService LookupNumeric(const std::string& name, uint16_t portDefault = 0, DNSLookupFn dns_lookup_function = g_dns_lookup);
272 : :
273 : : /**
274 : : * Parse and resolve a specified subnet string into the appropriate internal
275 : : * representation.
276 : : *
277 : : * @param[in] subnet_str A string representation of a subnet of the form
278 : : * `network address [ "/", ( CIDR-style suffix | netmask ) ]`
279 : : * e.g. "2001:db8::/32", "192.0.2.0/255.255.255.0" or "8.8.8.8".
280 : : * @returns a CSubNet object (that may or may not be valid).
281 : : */
282 : : CSubNet LookupSubNet(const std::string& subnet_str);
283 : :
284 : : /**
285 : : * Create a real socket from the operating system.
286 : : * @param[in] domain Communications domain, first argument to the socket(2) syscall.
287 : : * @param[in] type Type of the socket, second argument to the socket(2) syscall.
288 : : * @param[in] protocol The particular protocol to be used with the socket, third argument to the socket(2) syscall.
289 : : * @return pointer to the created Sock object or unique_ptr that owns nothing in case of failure
290 : : */
291 : : std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol);
292 : :
293 : : /**
294 : : * Socket factory. Defaults to `CreateSockOS()`, but can be overridden by unit tests.
295 : : */
296 : : extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
297 : :
298 : : /**
299 : : * Create a socket and try to connect to the specified service.
300 : : *
301 : : * @param[in] dest The service to which to connect.
302 : : * @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
303 : : *
304 : : * @returns the connected socket if the operation succeeded, empty unique_ptr otherwise
305 : : */
306 : : std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection);
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
|