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