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