Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/netbase.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8
#include <netbase.h>
9
10
#include <compat/compat.h>
11
#include <logging.h>
12
#include <sync.h>
13
#include <tinyformat.h>
14
#include <util/sock.h>
15
#include <util/strencodings.h>
16
#include <util/string.h>
17
#include <util/time.h>
18
19
#include <atomic>
20
#include <chrono>
21
#include <cstdint>
22
#include <functional>
23
#include <limits>
24
#include <memory>
25
26
#ifdef HAVE_SOCKADDR_UN
27
#include <sys/un.h>
28
#endif
29
30
using util::ContainsNoNUL;
31
32
// Settings
33
static GlobalMutex g_proxyinfo_mutex;
34
static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
35
static Proxy nameProxy GUARDED_BY(g_proxyinfo_mutex);
36
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
37
bool fNameLookup = DEFAULT_NAME_LOOKUP;
38
39
// Need ample time for negotiation for very slow proxies such as Tor
40
std::chrono::milliseconds g_socks5_recv_timeout = 20s;
41
CThreadInterrupt g_socks5_interrupt;
42
43
ReachableNets g_reachable_nets;
44
45
std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
46
0
{
47
0
    addrinfo ai_hint{};
48
    // We want a TCP port, which is a streaming socket type
49
0
    ai_hint.ai_socktype = SOCK_STREAM;
50
0
    ai_hint.ai_protocol = IPPROTO_TCP;
51
    // We don't care which address family (IPv4 or IPv6) is returned
52
0
    ai_hint.ai_family = AF_UNSPEC;
53
54
    // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
55
    // return addresses whose family we have an address configured for.
56
    //
57
    // If we don't allow lookups, then use the AI_NUMERICHOST flag for
58
    // getaddrinfo to only decode numerical network addresses and suppress
59
    // hostname lookups.
60
0
    ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
61
62
0
    addrinfo* ai_res{nullptr};
63
0
    const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
64
0
    if (n_err != 0) {
65
0
        if ((ai_hint.ai_flags & AI_ADDRCONFIG) == AI_ADDRCONFIG) {
66
            // AI_ADDRCONFIG on some systems may exclude loopback-only addresses
67
            // If first lookup failed we perform a second lookup without AI_ADDRCONFIG
68
0
            ai_hint.ai_flags = (ai_hint.ai_flags & ~AI_ADDRCONFIG);
69
0
            const int n_err_retry{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
70
0
            if (n_err_retry != 0) {
71
0
                return {};
72
0
            }
73
0
        } else {
74
0
            return {};
75
0
        }
76
0
    }
77
78
    // Traverse the linked list starting with ai_trav.
79
0
    addrinfo* ai_trav{ai_res};
80
0
    std::vector<CNetAddr> resolved_addresses;
81
0
    while (ai_trav != nullptr) {
82
0
        if (ai_trav->ai_family == AF_INET) {
83
0
            assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
84
0
            resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
85
0
        }
86
0
        if (ai_trav->ai_family == AF_INET6) {
87
0
            assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
88
0
            const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
89
0
            resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
90
0
        }
91
0
        ai_trav = ai_trav->ai_next;
92
0
    }
93
0
    freeaddrinfo(ai_res);
94
95
0
    return resolved_addresses;
96
0
}
97
98
DNSLookupFn g_dns_lookup{WrappedGetAddrInfo};
99
100
0
enum Network ParseNetwork(const std::string& net_in) {
101
0
    std::string net = ToLower(net_in);
102
0
    if (net == "ipv4") return NET_IPV4;
103
0
    if (net == "ipv6") return NET_IPV6;
104
0
    if (net == "onion") return NET_ONION;
105
0
    if (net == "i2p") {
106
0
        return NET_I2P;
107
0
    }
108
0
    if (net == "cjdns") {
109
0
        return NET_CJDNS;
110
0
    }
111
0
    return NET_UNROUTABLE;
112
0
}
113
114
std::string GetNetworkName(enum Network net)
115
0
{
116
0
    switch (net) {
117
0
    case NET_UNROUTABLE: return "not_publicly_routable";
118
0
    case NET_IPV4: return "ipv4";
119
0
    case NET_IPV6: return "ipv6";
120
0
    case NET_ONION: return "onion";
121
0
    case NET_I2P: return "i2p";
122
0
    case NET_CJDNS: return "cjdns";
123
0
    case NET_INTERNAL: return "internal";
124
0
    case NET_MAX: assert(false);
125
0
    } // no default case, so the compiler can warn about missing cases
126
127
0
    assert(false);
128
0
}
129
130
std::vector<std::string> GetNetworkNames(bool append_unroutable)
131
0
{
132
0
    std::vector<std::string> names;
133
0
    for (int n = 0; n < NET_MAX; ++n) {
134
0
        const enum Network network{static_cast<Network>(n)};
135
0
        if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
136
0
        names.emplace_back(GetNetworkName(network));
137
0
    }
138
0
    if (append_unroutable) {
139
0
        names.emplace_back(GetNetworkName(NET_UNROUTABLE));
140
0
    }
141
0
    return names;
142
0
}
143
144
static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
145
0
{
146
0
    if (!ContainsNoNUL(name)) return {};
147
0
    {
148
0
        CNetAddr addr;
149
        // From our perspective, onion addresses are not hostnames but rather
150
        // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
151
        // or IPv6 colon-separated hextet notation. Since we can't use
152
        // getaddrinfo to decode them and it wouldn't make sense to resolve
153
        // them, we return a network address representing it instead. See
154
        // CNetAddr::SetSpecial(const std::string&) for more details.
155
0
        if (addr.SetSpecial(name)) return {addr};
156
0
    }
157
158
0
    std::vector<CNetAddr> addresses;
159
160
0
    for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
161
0
        if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) {
162
0
            break;
163
0
        }
164
        /* Never allow resolving to an internal address. Consider any such result invalid */
165
0
        if (!resolved.IsInternal()) {
166
0
            addresses.push_back(resolved);
167
0
        }
168
0
    }
169
170
0
    return addresses;
171
0
}
172
173
std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
174
0
{
175
0
    if (!ContainsNoNUL(name)) return {};
176
0
    std::string strHost = name;
177
0
    if (strHost.empty()) return {};
178
0
    if (strHost.front() == '[' && strHost.back() == ']') {
179
0
        strHost = strHost.substr(1, strHost.size() - 2);
180
0
    }
181
182
0
    return LookupIntern(strHost, nMaxSolutions, fAllowLookup, dns_lookup_function);
183
0
}
184
185
std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function)
186
0
{
187
0
    const std::vector<CNetAddr> addresses{LookupHost(name, 1, fAllowLookup, dns_lookup_function)};
188
0
    return addresses.empty() ? std::nullopt : std::make_optional(addresses.front());
189
0
}
190
191
std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
192
0
{
193
0
    if (name.empty() || !ContainsNoNUL(name)) {
194
0
        return {};
195
0
    }
196
0
    uint16_t port{portDefault};
197
0
    std::string hostname;
198
0
    SplitHostPort(name, port, hostname);
199
200
0
    const std::vector<CNetAddr> addresses{LookupIntern(hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)};
201
0
    if (addresses.empty()) return {};
202
0
    std::vector<CService> services;
203
0
    services.reserve(addresses.size());
204
0
    for (const auto& addr : addresses)
205
0
        services.emplace_back(addr, port);
206
0
    return services;
207
0
}
208
209
std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
210
0
{
211
0
    const std::vector<CService> services{Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)};
212
213
0
    return services.empty() ? std::nullopt : std::make_optional(services.front());
214
0
}
215
216
CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
217
0
{
218
0
    if (!ContainsNoNUL(name)) {
219
0
        return {};
220
0
    }
221
    // "1.2:345" will fail to resolve the ip, but will still set the port.
222
    // If the ip fails to resolve, re-init the result.
223
0
    return Lookup(name, portDefault, /*fAllowLookup=*/false, dns_lookup_function).value_or(CService{});
224
0
}
225
226
bool IsUnixSocketPath(const std::string& name)
227
0
{
228
0
#ifdef HAVE_SOCKADDR_UN
229
0
    if (!name.starts_with(ADDR_PREFIX_UNIX)) return false;
230
231
    // Split off "unix:" prefix
232
0
    std::string str{name.substr(ADDR_PREFIX_UNIX.length())};
233
234
    // Path size limit is platform-dependent
235
    // see https://manpages.ubuntu.com/manpages/xenial/en/man7/unix.7.html
236
0
    if (str.size() + 1 > sizeof(((sockaddr_un*)nullptr)->sun_path)) return false;
237
238
0
    return true;
239
#else
240
    return false;
241
#endif
242
0
}
243
244
/** SOCKS version */
245
enum SOCKSVersion: uint8_t {
246
    SOCKS4 = 0x04,
247
    SOCKS5 = 0x05
248
};
249
250
/** Values defined for METHOD in RFC1928 */
251
enum SOCKS5Method: uint8_t {
252
    NOAUTH = 0x00,        //!< No authentication required
253
    GSSAPI = 0x01,        //!< GSSAPI
254
    USER_PASS = 0x02,     //!< Username/password
255
    NO_ACCEPTABLE = 0xff, //!< No acceptable methods
256
};
257
258
/** Values defined for CMD in RFC1928 */
259
enum SOCKS5Command: uint8_t {
260
    CONNECT = 0x01,
261
    BIND = 0x02,
262
    UDP_ASSOCIATE = 0x03
263
};
264
265
/** Values defined for REP in RFC1928 and https://spec.torproject.org/socks-extensions.html */
266
enum SOCKS5Reply: uint8_t {
267
    SUCCEEDED = 0x00,                  //!< RFC1928: Succeeded
268
    GENFAILURE = 0x01,                 //!< RFC1928: General failure
269
    NOTALLOWED = 0x02,                 //!< RFC1928: Connection not allowed by ruleset
270
    NETUNREACHABLE = 0x03,             //!< RFC1928: Network unreachable
271
    HOSTUNREACHABLE = 0x04,            //!< RFC1928: Network unreachable
272
    CONNREFUSED = 0x05,                //!< RFC1928: Connection refused
273
    TTLEXPIRED = 0x06,                 //!< RFC1928: TTL expired
274
    CMDUNSUPPORTED = 0x07,             //!< RFC1928: Command not supported
275
    ATYPEUNSUPPORTED = 0x08,           //!< RFC1928: Address type not supported
276
    TOR_HS_DESC_NOT_FOUND = 0xf0,      //!< Tor: Onion service descriptor can not be found
277
    TOR_HS_DESC_INVALID = 0xf1,        //!< Tor: Onion service descriptor is invalid
278
    TOR_HS_INTRO_FAILED = 0xf2,        //!< Tor: Onion service introduction failed
279
    TOR_HS_REND_FAILED = 0xf3,         //!< Tor: Onion service rendezvous failed
280
    TOR_HS_MISSING_CLIENT_AUTH = 0xf4, //!< Tor: Onion service missing client authorization
281
    TOR_HS_WRONG_CLIENT_AUTH = 0xf5,   //!< Tor: Onion service wrong client authorization
282
    TOR_HS_BAD_ADDRESS = 0xf6,         //!< Tor: Onion service invalid address
283
    TOR_HS_INTRO_TIMEOUT = 0xf7,       //!< Tor: Onion service introduction timed out
284
};
285
286
/** Values defined for ATYPE in RFC1928 */
287
enum SOCKS5Atyp: uint8_t {
288
    IPV4 = 0x01,
289
    DOMAINNAME = 0x03,
290
    IPV6 = 0x04,
291
};
292
293
/** Status codes that can be returned by InterruptibleRecv */
294
enum class IntrRecvError {
295
    OK,
296
    Timeout,
297
    Disconnected,
298
    NetworkError,
299
    Interrupted
300
};
301
302
/**
303
 * Try to read a specified number of bytes from a socket. Please read the "see
304
 * also" section for more detail.
305
 *
306
 * @param data The buffer where the read bytes should be stored.
307
 * @param len The number of bytes to read into the specified buffer.
308
 * @param timeout The total timeout for this read.
309
 * @param sock The socket (has to be in non-blocking mode) from which to read bytes.
310
 *
311
 * @returns An IntrRecvError indicating the resulting status of this read.
312
 *          IntrRecvError::OK only if all of the specified number of bytes were
313
 *          read.
314
 *
315
 * @see This function can be interrupted by calling g_socks5_interrupt().
316
 *      Sockets can be made non-blocking with Sock::SetNonBlocking().
317
 */
318
static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, std::chrono::milliseconds timeout, const Sock& sock)
319
0
{
320
0
    auto curTime{Now<SteadyMilliseconds>()};
321
0
    const auto endTime{curTime + timeout};
322
0
    while (len > 0 && curTime < endTime) {
323
0
        ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
324
0
        if (ret > 0) {
325
0
            len -= ret;
326
0
            data += ret;
327
0
        } else if (ret == 0) { // Unexpected disconnection
328
0
            return IntrRecvError::Disconnected;
329
0
        } else { // Other error or blocking
330
0
            int nErr = WSAGetLastError();
Line
Count
Source
59
0
#define WSAGetLastError()   errno
331
0
            if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
Line
Count
Source
65
0
#define WSAEINPROGRESS      EINPROGRESS
            if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
Line
Count
Source
61
0
#define WSAEWOULDBLOCK      EWOULDBLOCK
            if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
Line
Count
Source
60
0
#define WSAEINVAL           EINVAL
332
                // Only wait at most MAX_WAIT_FOR_IO at a time, unless
333
                // we're approaching the end of the specified total timeout
334
0
                const auto remaining = std::chrono::milliseconds{endTime - curTime};
335
0
                const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
336
0
                if (!sock.Wait(timeout, Sock::RECV)) {
337
0
                    return IntrRecvError::NetworkError;
338
0
                }
339
0
            } else {
340
0
                return IntrRecvError::NetworkError;
341
0
            }
342
0
        }
343
0
        if (g_socks5_interrupt) {
344
0
            return IntrRecvError::Interrupted;
345
0
        }
346
0
        curTime = Now<SteadyMilliseconds>();
347
0
    }
348
0
    return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
349
0
}
350
351
/** Convert SOCKS5 reply to an error message */
352
static std::string Socks5ErrorString(uint8_t err)
353
0
{
354
0
    switch(err) {
355
0
        case SOCKS5Reply::GENFAILURE:
356
0
            return "general failure";
357
0
        case SOCKS5Reply::NOTALLOWED:
358
0
            return "connection not allowed";
359
0
        case SOCKS5Reply::NETUNREACHABLE:
360
0
            return "network unreachable";
361
0
        case SOCKS5Reply::HOSTUNREACHABLE:
362
0
            return "host unreachable";
363
0
        case SOCKS5Reply::CONNREFUSED:
364
0
            return "connection refused";
365
0
        case SOCKS5Reply::TTLEXPIRED:
366
0
            return "TTL expired";
367
0
        case SOCKS5Reply::CMDUNSUPPORTED:
368
0
            return "protocol error";
369
0
        case SOCKS5Reply::ATYPEUNSUPPORTED:
370
0
            return "address type not supported";
371
0
        case SOCKS5Reply::TOR_HS_DESC_NOT_FOUND:
372
0
            return "onion service descriptor can not be found";
373
0
        case SOCKS5Reply::TOR_HS_DESC_INVALID:
374
0
            return "onion service descriptor is invalid";
375
0
        case SOCKS5Reply::TOR_HS_INTRO_FAILED:
376
0
            return "onion service introduction failed";
377
0
        case SOCKS5Reply::TOR_HS_REND_FAILED:
378
0
            return "onion service rendezvous failed";
379
0
        case SOCKS5Reply::TOR_HS_MISSING_CLIENT_AUTH:
380
0
            return "onion service missing client authorization";
381
0
        case SOCKS5Reply::TOR_HS_WRONG_CLIENT_AUTH:
382
0
            return "onion service wrong client authorization";
383
0
        case SOCKS5Reply::TOR_HS_BAD_ADDRESS:
384
0
            return "onion service invalid address";
385
0
        case SOCKS5Reply::TOR_HS_INTRO_TIMEOUT:
386
0
            return "onion service introduction timed out";
387
0
        default:
388
0
            return strprintf("unknown (0x%02x)", err);
Line
Count
Source
1172
0
#define strprintf tfm::format
389
0
    }
390
0
}
391
392
bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
393
0
{
394
0
    try {
395
0
        IntrRecvError recvr;
396
0
        LogDebug(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
397
0
        if (strDest.size() > 255) {
398
0
            LogError("Hostname too long\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
399
0
            return false;
400
0
        }
401
        // Construct the version identifier/method selection message
402
0
        std::vector<uint8_t> vSocks5Init;
403
0
        vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
404
0
        if (auth) {
405
0
            vSocks5Init.push_back(0x02); // 2 method identifiers follow...
406
0
            vSocks5Init.push_back(SOCKS5Method::NOAUTH);
407
0
            vSocks5Init.push_back(SOCKS5Method::USER_PASS);
408
0
        } else {
409
0
            vSocks5Init.push_back(0x01); // 1 method identifier follows...
410
0
            vSocks5Init.push_back(SOCKS5Method::NOAUTH);
411
0
        }
412
0
        sock.SendComplete(vSocks5Init, g_socks5_recv_timeout, g_socks5_interrupt);
413
0
        uint8_t pchRet1[2];
414
0
        if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
415
0
            LogInfo("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
416
0
            return false;
417
0
        }
418
0
        if (pchRet1[0] != SOCKSVersion::SOCKS5) {
419
0
            LogError("Proxy failed to initialize\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
420
0
            return false;
421
0
        }
422
0
        if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
423
            // Perform username/password authentication (as described in RFC1929)
424
0
            std::vector<uint8_t> vAuth;
425
0
            vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
426
0
            if (auth->username.size() > 255 || auth->password.size() > 255) {
427
0
                LogError("Proxy username or password too long\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
428
0
                return false;
429
0
            }
430
0
            vAuth.push_back(auth->username.size());
431
0
            vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
432
0
            vAuth.push_back(auth->password.size());
433
0
            vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
434
0
            sock.SendComplete(vAuth, g_socks5_recv_timeout, g_socks5_interrupt);
435
0
            LogDebug(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
436
0
            uint8_t pchRetA[2];
437
0
            if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
438
0
                LogError("Error reading proxy authentication response\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
439
0
                return false;
440
0
            }
441
0
            if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
442
0
                LogError("Proxy authentication unsuccessful\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
443
0
                return false;
444
0
            }
445
0
        } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
446
            // Perform no authentication
447
0
        } else {
448
0
            LogError("Proxy requested wrong authentication method %02x\n", pchRet1[1]);
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
449
0
            return false;
450
0
        }
451
0
        std::vector<uint8_t> vSocks5;
452
0
        vSocks5.push_back(SOCKSVersion::SOCKS5);   // VER protocol version
453
0
        vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
454
0
        vSocks5.push_back(0x00);                   // RSV Reserved must be 0
455
0
        vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
456
0
        vSocks5.push_back(strDest.size());         // Length<=255 is checked at beginning of function
457
0
        vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
458
0
        vSocks5.push_back((port >> 8) & 0xFF);
459
0
        vSocks5.push_back((port >> 0) & 0xFF);
460
0
        sock.SendComplete(vSocks5, g_socks5_recv_timeout, g_socks5_interrupt);
461
0
        uint8_t pchRet2[4];
462
0
        if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
463
0
            if (recvr == IntrRecvError::Timeout) {
464
                /* If a timeout happens here, this effectively means we timed out while connecting
465
                 * to the remote node. This is very common for Tor, so do not print an
466
                 * error message. */
467
0
                return false;
468
0
            } else {
469
0
                LogError("Error while reading proxy response\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
470
0
                return false;
471
0
            }
472
0
        }
473
0
        if (pchRet2[0] != SOCKSVersion::SOCKS5) {
474
0
            LogError("Proxy failed to accept request\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
475
0
            return false;
476
0
        }
477
0
        if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
478
            // Failures to connect to a peer that are not proxy errors
479
0
            LogDebug(BCLog::NET,
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
480
0
                          "Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
481
0
            return false;
482
0
        }
483
0
        if (pchRet2[2] != 0x00) { // Reserved field must be 0
484
0
            LogError("Error: malformed proxy response\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
485
0
            return false;
486
0
        }
487
0
        uint8_t pchRet3[256];
488
0
        switch (pchRet2[3]) {
489
0
        case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
490
0
        case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
491
0
        case SOCKS5Atyp::DOMAINNAME: {
492
0
            recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
493
0
            if (recvr != IntrRecvError::OK) {
494
0
                LogError("Error reading from proxy\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
495
0
                return false;
496
0
            }
497
0
            int nRecv = pchRet3[0];
498
0
            recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
499
0
            break;
500
0
        }
501
0
        default: {
502
0
            LogError("Error: malformed proxy response\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
503
0
            return false;
504
0
        }
505
0
        }
506
0
        if (recvr != IntrRecvError::OK) {
507
0
            LogError("Error reading from proxy\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
508
0
            return false;
509
0
        }
510
0
        if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
511
0
            LogError("Error reading from proxy\n");
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
512
0
            return false;
513
0
        }
514
0
        LogDebug(BCLog::NET, "SOCKS5 connected %s\n", strDest);
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
515
0
        return true;
516
0
    } catch (const std::runtime_error& e) {
517
0
        LogError("Error during SOCKS5 proxy handshake: %s\n", e.what());
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
518
0
        return false;
519
0
    }
520
0
}
521
522
std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol)
523
0
{
524
    // Not IPv4, IPv6 or UNIX
525
0
    if (domain == AF_UNSPEC) return nullptr;
526
527
    // Create a socket in the specified address family.
528
0
    SOCKET hSocket = socket(domain, type, protocol);
529
0
    if (hSocket == INVALID_SOCKET) {
Line
Count
Source
67
0
#define INVALID_SOCKET      (SOCKET)(~0)
530
0
        return nullptr;
531
0
    }
532
533
0
    auto sock = std::make_unique<Sock>(hSocket);
534
535
0
    if (domain != AF_INET && domain != AF_INET6 && domain != AF_UNIX) {
536
0
        return sock;
537
0
    }
538
539
    // Ensure that waiting for I/O on this socket won't result in undefined
540
    // behavior.
541
0
    if (!sock->IsSelectable()) {
542
0
        LogInfo("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
543
0
        return nullptr;
544
0
    }
545
546
#ifdef SO_NOSIGPIPE
547
    int set = 1;
548
    // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
549
    // should use the MSG_NOSIGNAL flag for every send.
550
    if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof(int)) == SOCKET_ERROR) {
551
        LogInfo("Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n",
552
                  NetworkErrorString(WSAGetLastError()));
553
    }
554
#endif
555
556
    // Set the non-blocking option on the socket.
557
0
    if (!sock->SetNonBlocking()) {
558
0
        LogInfo("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
559
0
        return nullptr;
560
0
    }
561
562
0
#ifdef HAVE_SOCKADDR_UN
563
0
    if (domain == AF_UNIX) return sock;
564
0
#endif
565
566
0
    if (protocol == IPPROTO_TCP) {
567
        // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
568
0
        const int on{1};
569
0
        if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
Line
Count
Source
68
0
#define SOCKET_ERROR        -1
570
0
            LogDebug(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
571
0
        }
572
0
    }
573
574
0
    return sock;
575
0
}
576
577
std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock = CreateSockOS;
578
579
template<typename... Args>
580
static void LogConnectFailure(bool manual_connection, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
581
0
{
582
0
    std::string error_message = tfm::format(fmt, args...);
583
0
    if (manual_connection) {
584
0
        LogInfo("%s\n", error_message);
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
585
0
    } else {
586
0
        LogDebug(BCLog::NET, "%s\n", error_message);
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
587
0
    }
588
0
}
589
590
static bool ConnectToSocket(const Sock& sock, struct sockaddr* sockaddr, socklen_t len, const std::string& dest_str, bool manual_connection)
591
0
{
592
    // Connect to `sockaddr` using `sock`.
593
0
    if (sock.Connect(sockaddr, len) == SOCKET_ERROR) {
Line
Count
Source
68
0
#define SOCKET_ERROR        -1
594
0
        int nErr = WSAGetLastError();
Line
Count
Source
59
0
#define WSAGetLastError()   errno
595
        // WSAEINVAL is here because some legacy version of winsock uses it
596
0
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
Line
Count
Source
65
0
#define WSAEINPROGRESS      EINPROGRESS
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
Line
Count
Source
61
0
#define WSAEWOULDBLOCK      EWOULDBLOCK
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
Line
Count
Source
60
0
#define WSAEINVAL           EINVAL
597
0
        {
598
            // Connection didn't actually fail, but is being established
599
            // asynchronously. Thus, use async I/O api (select/poll)
600
            // synchronously to check for successful connection with a timeout.
601
0
            const Sock::Event requested = Sock::RECV | Sock::SEND;
602
0
            Sock::Event occurred;
603
0
            if (!sock.Wait(std::chrono::milliseconds{nConnectTimeout}, requested, &occurred)) {
604
0
                LogInfo("wait for connect to %s failed: %s\n",
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
605
0
                          dest_str,
606
0
                          NetworkErrorString(WSAGetLastError()));
607
0
                return false;
608
0
            } else if (occurred == 0) {
609
0
                LogDebug(BCLog::NET, "connection attempt to %s timed out\n", dest_str);
Line
Count
Source
115
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
106
0
    do {                                                               \
107
0
        if (util::log::ShouldLog((category), (level))) {               \
108
0
            bool rate_limit{level >= BCLog::Level::Info};              \
109
0
            Assume(!rate_limit); /*Only called with the levels below*/ \
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
110
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__);  \
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
111
0
        }                                                              \
112
0
    } while (0)
610
0
                return false;
611
0
            }
612
613
            // Even if the wait was successful, the connect might not
614
            // have been successful. The reason for this failure is hidden away
615
            // in the SO_ERROR for the socket in modern systems. We read it into
616
            // sockerr here.
617
0
            int sockerr;
618
0
            socklen_t sockerr_len = sizeof(sockerr);
619
0
            if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, &sockerr, &sockerr_len) ==
620
0
                SOCKET_ERROR) {
Line
Count
Source
68
0
#define SOCKET_ERROR        -1
621
0
                LogInfo("getsockopt() for %s failed: %s\n", dest_str, NetworkErrorString(WSAGetLastError()));
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
622
0
                return false;
623
0
            }
624
0
            if (sockerr != 0) {
625
0
                LogConnectFailure(manual_connection,
626
0
                                  "connect() to %s failed after wait: %s",
627
0
                                  dest_str,
628
0
                                  NetworkErrorString(sockerr));
629
0
                return false;
630
0
            }
631
0
        }
632
#ifdef WIN32
633
        else if (WSAGetLastError() != WSAEISCONN)
634
#else
635
0
        else
636
0
#endif
637
0
        {
638
0
            LogConnectFailure(manual_connection, "connect() to %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError()));
Line
Count
Source
59
0
#define WSAGetLastError()   errno
639
0
            return false;
640
0
        }
641
0
    }
642
0
    return true;
643
0
}
644
645
std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection)
646
0
{
647
0
    auto sock = CreateSock(dest.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP);
648
0
    if (!sock) {
649
0
        LogError("Cannot create a socket for connecting to %s\n", dest.ToStringAddrPort());
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
650
0
        return {};
651
0
    }
652
653
    // Create a sockaddr from the specified service.
654
0
    struct sockaddr_storage sockaddr;
655
0
    socklen_t len = sizeof(sockaddr);
656
0
    if (!dest.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
657
0
        LogInfo("Cannot get sockaddr for %s: unsupported network\n", dest.ToStringAddrPort());
Line
Count
Source
95
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
658
0
        return {};
659
0
    }
660
661
0
    if (!ConnectToSocket(*sock, (struct sockaddr*)&sockaddr, len, dest.ToStringAddrPort(), manual_connection)) {
662
0
        return {};
663
0
    }
664
665
0
    return sock;
666
0
}
667
668
std::unique_ptr<Sock> Proxy::Connect() const
669
0
{
670
0
    if (!IsValid()) return {};
671
672
0
    if (!m_is_unix_socket) return ConnectDirectly(proxy, /*manual_connection=*/true);
673
674
0
#ifdef HAVE_SOCKADDR_UN
675
0
    auto sock = CreateSock(AF_UNIX, SOCK_STREAM, 0);
676
0
    if (!sock) {
677
0
        LogError("Cannot create a socket for connecting to %s\n", m_unix_socket_path);
Line
Count
Source
97
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
678
0
        return {};
679
0
    }
680
681
0
    const std::string path{m_unix_socket_path.substr(ADDR_PREFIX_UNIX.length())};
682
683
0
    struct sockaddr_un addrun;
684
0
    memset(&addrun, 0, sizeof(addrun));
685
0
    addrun.sun_family = AF_UNIX;
686
    // leave the last char in addrun.sun_path[] to be always '\0'
687
0
    memcpy(addrun.sun_path, path.c_str(), std::min(sizeof(addrun.sun_path) - 1, path.length()));
688
0
    socklen_t len = sizeof(addrun);
689
690
0
    if(!ConnectToSocket(*sock, (struct sockaddr*)&addrun, len, path, /*manual_connection=*/true)) {
691
0
        return {};
692
0
    }
693
694
0
    return sock;
695
#else
696
    return {};
697
#endif
698
0
}
699
700
0
bool SetProxy(enum Network net, const Proxy &addrProxy) {
701
0
    assert(net >= 0 && net < NET_MAX);
702
0
    if (!addrProxy.IsValid())
703
0
        return false;
704
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
705
0
    proxyInfo[net] = addrProxy;
706
0
    return true;
707
0
}
708
709
0
bool GetProxy(enum Network net, Proxy &proxyInfoOut) {
710
0
    assert(net >= 0 && net < NET_MAX);
711
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
712
0
    if (!proxyInfo[net].IsValid())
713
0
        return false;
714
0
    proxyInfoOut = proxyInfo[net];
715
0
    return true;
716
0
}
717
718
0
bool SetNameProxy(const Proxy &addrProxy) {
719
0
    if (!addrProxy.IsValid())
720
0
        return false;
721
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
722
0
    nameProxy = addrProxy;
723
0
    return true;
724
0
}
725
726
0
bool GetNameProxy(Proxy &nameProxyOut) {
727
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
728
0
    if(!nameProxy.IsValid())
729
0
        return false;
730
0
    nameProxyOut = nameProxy;
731
0
    return true;
732
0
}
733
734
0
bool HaveNameProxy() {
735
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
736
0
    return nameProxy.IsValid();
737
0
}
738
739
0
bool IsProxy(const CNetAddr &addr) {
740
0
    LOCK(g_proxyinfo_mutex);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
741
0
    for (int i = 0; i < NET_MAX; i++) {
742
0
        if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
743
0
            return true;
744
0
    }
745
0
    return false;
746
0
}
747
748
/**
749
 * Generate unique credentials for Tor stream isolation. Tor will create
750
 * separate circuits for SOCKS5 proxy connections with different credentials, which
751
 * makes it harder to correlate the connections.
752
 */
753
class TorStreamIsolationCredentialsGenerator
754
{
755
public:
756
    TorStreamIsolationCredentialsGenerator():
757
0
        m_prefix(GenerateUniquePrefix()) {
758
0
    }
759
760
    /** Return the next unique proxy credentials. */
761
0
    ProxyCredentials Generate() {
762
0
        ProxyCredentials auth;
763
0
        auth.username = auth.password = strprintf("%s%i", m_prefix, m_counter);
Line
Count
Source
1172
0
#define strprintf tfm::format
764
0
        ++m_counter;
765
0
        return auth;
766
0
    }
767
768
    /** Size of session prefix in bytes. */
769
    static constexpr size_t PREFIX_BYTE_LENGTH = 8;
770
private:
771
    const std::string m_prefix;
772
    std::atomic<uint64_t> m_counter;
773
774
    /** Generate a random prefix for each of the credentials returned by this generator.
775
     * This makes sure that different launches of the application (either successively or in parallel)
776
     * will not share the same circuits, as would be the case with a bare counter.
777
     */
778
0
    static std::string GenerateUniquePrefix() {
779
0
        std::array<uint8_t, PREFIX_BYTE_LENGTH> prefix_bytes;
780
0
        GetRandBytes(prefix_bytes);
781
0
        return HexStr(prefix_bytes) + "-";
782
0
    }
783
};
784
785
std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
786
                                          const std::string& dest,
787
                                          uint16_t port,
788
                                          bool& proxy_connection_failed)
789
0
{
790
    // first connect to proxy server
791
0
    auto sock = proxy.Connect();
792
0
    if (!sock) {
793
0
        proxy_connection_failed = true;
794
0
        return {};
795
0
    }
796
797
    // do socks negotiation
798
0
    if (proxy.m_tor_stream_isolation) {
799
0
        static TorStreamIsolationCredentialsGenerator generator;
800
0
        ProxyCredentials random_auth{generator.Generate()};
801
0
        if (!Socks5(dest, port, &random_auth, *sock)) {
802
0
            return {};
803
0
        }
804
0
    } else {
805
0
        if (!Socks5(dest, port, nullptr, *sock)) {
806
0
            return {};
807
0
        }
808
0
    }
809
0
    return sock;
810
0
}
811
812
CSubNet LookupSubNet(const std::string& subnet_str)
813
0
{
814
0
    CSubNet subnet;
815
0
    assert(!subnet.IsValid());
816
0
    if (!ContainsNoNUL(subnet_str)) {
817
0
        return subnet;
818
0
    }
819
820
0
    const size_t slash_pos{subnet_str.find_last_of('/')};
821
0
    const std::string str_addr{subnet_str.substr(0, slash_pos)};
822
0
    std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)};
823
824
0
    if (addr.has_value()) {
825
0
        addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
826
0
        if (slash_pos != subnet_str.npos) {
827
0
            const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
828
0
            if (const auto netmask{ToIntegral<uint8_t>(netmask_str)}) {
829
                // Valid number; assume CIDR variable-length subnet masking.
830
0
                subnet = CSubNet{addr.value(), *netmask};
831
0
            } else {
832
                // Invalid number; try full netmask syntax. Never allow lookup for netmask.
833
0
                const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)};
834
0
                if (full_netmask.has_value()) {
835
0
                    subnet = CSubNet{addr.value(), full_netmask.value()};
836
0
                }
837
0
            }
838
0
        } else {
839
            // Single IP subnet (<ipv4>/32 or <ipv6>/128).
840
0
            subnet = CSubNet{addr.value()};
841
0
        }
842
0
    }
843
844
0
    return subnet;
845
0
}
846
847
bool IsBadPort(uint16_t port)
848
0
{
849
    /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */
850
851
0
    switch (port) {
852
0
    case 1:     // tcpmux
853
0
    case 7:     // echo
854
0
    case 9:     // discard
855
0
    case 11:    // systat
856
0
    case 13:    // daytime
857
0
    case 15:    // netstat
858
0
    case 17:    // qotd
859
0
    case 19:    // chargen
860
0
    case 20:    // ftp data
861
0
    case 21:    // ftp access
862
0
    case 22:    // ssh
863
0
    case 23:    // telnet
864
0
    case 25:    // smtp
865
0
    case 37:    // time
866
0
    case 42:    // name
867
0
    case 43:    // nicname
868
0
    case 53:    // domain
869
0
    case 69:    // tftp
870
0
    case 77:    // priv-rjs
871
0
    case 79:    // finger
872
0
    case 87:    // ttylink
873
0
    case 95:    // supdup
874
0
    case 101:   // hostname
875
0
    case 102:   // iso-tsap
876
0
    case 103:   // gppitnp
877
0
    case 104:   // acr-nema
878
0
    case 109:   // pop2
879
0
    case 110:   // pop3
880
0
    case 111:   // sunrpc
881
0
    case 113:   // auth
882
0
    case 115:   // sftp
883
0
    case 117:   // uucp-path
884
0
    case 119:   // nntp
885
0
    case 123:   // NTP
886
0
    case 135:   // loc-srv /epmap
887
0
    case 137:   // netbios
888
0
    case 139:   // netbios
889
0
    case 143:   // imap2
890
0
    case 161:   // snmp
891
0
    case 179:   // BGP
892
0
    case 389:   // ldap
893
0
    case 427:   // SLP (Also used by Apple Filing Protocol)
894
0
    case 465:   // smtp+ssl
895
0
    case 512:   // print / exec
896
0
    case 513:   // login
897
0
    case 514:   // shell
898
0
    case 515:   // printer
899
0
    case 526:   // tempo
900
0
    case 530:   // courier
901
0
    case 531:   // chat
902
0
    case 532:   // netnews
903
0
    case 540:   // uucp
904
0
    case 548:   // AFP (Apple Filing Protocol)
905
0
    case 554:   // rtsp
906
0
    case 556:   // remotefs
907
0
    case 563:   // nntp+ssl
908
0
    case 587:   // smtp (rfc6409)
909
0
    case 601:   // syslog-conn (rfc3195)
910
0
    case 636:   // ldap+ssl
911
0
    case 989:   // ftps-data
912
0
    case 990:   // ftps
913
0
    case 993:   // ldap+ssl
914
0
    case 995:   // pop3+ssl
915
0
    case 1719:  // h323gatestat
916
0
    case 1720:  // h323hostcall
917
0
    case 1723:  // pptp
918
0
    case 2049:  // nfs
919
0
    case 3306:  // MySQL
920
0
    case 3389:  // RDP / Windows Remote Desktop
921
0
    case 3659:  // apple-sasl / PasswordServer
922
0
    case 4045:  // lockd
923
0
    case 5060:  // sip
924
0
    case 5061:  // sips
925
0
    case 5432:  // PostgreSQL
926
0
    case 5900:  // VNC
927
0
    case 6000:  // X11
928
0
    case 6566:  // sane-port
929
0
    case 6665:  // Alternate IRC
930
0
    case 6666:  // Alternate IRC
931
0
    case 6667:  // Standard IRC
932
0
    case 6668:  // Alternate IRC
933
0
    case 6669:  // Alternate IRC
934
0
    case 6697:  // IRC + TLS
935
0
    case 10080: // Amanda
936
0
    case 27017: // MongoDB
937
0
        return true;
938
0
    }
939
0
    return false;
940
0
}
941
942
CService MaybeFlipIPv6toCJDNS(const CService& service)
943
0
{
944
0
    CService ret{service};
945
0
    if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) {
946
0
        ret.m_net = NET_CJDNS;
947
0
    }
948
0
    return ret;
949
0
}
950
951
CService GetBindAddress(const Sock& sock)
952
0
{
953
0
    CService addr_bind;
954
0
    sockaddr_storage storage;
955
0
    socklen_t len = sizeof(storage);
956
957
0
    auto sa = reinterpret_cast<sockaddr*>(&storage);
958
959
0
    if (sock.GetSockName(sa, &len) == 0) {
960
0
        addr_bind.SetSockAddr(sa, len);
961
0
    } else {
962
0
        LogWarning("getsockname failed\n");
Line
Count
Source
96
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
89
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
963
0
    }
964
0
    return addr_bind;
965
0
}