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