Coverage Report

Created: 2024-08-21 05:08

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