Coverage Report

Created: 2026-07-08 14:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/common/netif.cpp
Line
Count
Source
1
// Copyright (c) 2024-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
4
5
#include <bitcoin-build-config.h> // IWYU pragma: keep
6
7
#include <common/netif.h>
8
9
#include <netbase.h>
10
#include <util/check.h>
11
#include <util/log.h>
12
#include <util/sock.h>
13
14
#if defined(__linux__)
15
#include <linux/rtnetlink.h>
16
#elif defined(__FreeBSD__)
17
#include <osreldate.h>
18
#if __FreeBSD_version >= 1400000
19
// Workaround https://github.com/freebsd/freebsd-src/pull/1070.
20
#define typeof __typeof
21
#include <netlink/netlink.h>
22
#include <netlink/netlink_route.h>
23
#endif
24
#elif defined(WIN32)
25
#include <iphlpapi.h>
26
#elif defined(__APPLE__)
27
#include <net/route.h>
28
#include <sys/sysctl.h>
29
#endif
30
31
#ifdef HAVE_IFADDRS
32
#include <ifaddrs.h>
33
#endif
34
35
#include <type_traits>
36
37
namespace {
38
39
//! Return CNetAddr for the specified OS-level network address.
40
//! If a length is not given, it is taken to be sizeof(struct sockaddr_*) for the family.
41
std::optional<CNetAddr> FromSockAddr(const struct sockaddr* addr, std::optional<socklen_t> sa_len_opt)
42
30
{
43
30
    socklen_t sa_len = 0;
44
30
    if (sa_len_opt.has_value()) {
45
0
        sa_len = *sa_len_opt;
46
30
    } else {
47
        // If sockaddr length was not specified, determine it from the family.
48
30
        switch (addr->sa_family) {
49
12
        case AF_INET: sa_len = sizeof(struct sockaddr_in); break;
50
6
        case AF_INET6: sa_len = sizeof(struct sockaddr_in6); break;
51
12
        default:
52
12
            return std::nullopt;
53
30
        }
54
30
    }
55
    // Fill in a CService from the sockaddr, then drop the port part.
56
18
    CService service;
57
18
    if (service.SetSockAddr(addr, sa_len)) {
58
18
        return (CNetAddr)service;
59
18
    }
60
0
    return std::nullopt;
61
18
}
62
63
// Linux and FreeBSD 14.0+. For FreeBSD 13.2 the code can be compiled but
64
// running it requires loading a special kernel module, otherwise socket(AF_NETLINK,...)
65
// will fail, so we skip that.
66
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 1400000)
67
68
// Good for responses containing ~ 10,000-15,000 routes.
69
static constexpr ssize_t NETLINK_MAX_RESPONSE_SIZE{1'048'576};
70
71
std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
72
0
{
73
    // Create a netlink socket.
74
0
    auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)};
75
0
    if (!sock) {
76
0
        LogError("socket(AF_NETLINK): %s\n", NetworkErrorString(errno));
77
0
        return std::nullopt;
78
0
    }
79
80
    // Send request.
81
0
    struct {
82
0
        nlmsghdr hdr; ///< Request header.
83
0
        rtmsg data; ///< Request data, a "route message".
84
0
        nlattr dst_hdr; ///< One attribute, conveying the route destination address.
85
0
        char dst_data[16]; ///< Route destination address. To query the default route we use 0.0.0.0/0 or [::]/0. For IPv4 the first 4 bytes are used.
86
0
    } request{};
87
88
    // Whether to use the first 4 or 16 bytes from request.dst_data.
89
0
    const size_t dst_data_len = family == AF_INET ? 4 : 16;
90
91
0
    request.hdr.nlmsg_type = RTM_GETROUTE;
92
0
    request.hdr.nlmsg_flags = NLM_F_REQUEST;
93
0
#ifdef __linux__
94
    // Linux IPv4 / IPv6 - this must be present, otherwise no gateway is found
95
    // FreeBSD IPv4 - does not matter, the gateway is found with or without this
96
    // FreeBSD IPv6 - this must be absent, otherwise no gateway is found
97
0
    request.hdr.nlmsg_flags |= NLM_F_DUMP;
98
0
#endif
99
0
    request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len);
100
0
    request.hdr.nlmsg_seq = 0; // Sequence number, used to match which reply is to which request. Irrelevant for us because we send just one request.
101
0
    request.data.rtm_family = family;
102
0
    request.data.rtm_dst_len = 0; // Prefix length.
103
#ifdef __FreeBSD__
104
    // Linux IPv4 / IPv6 this must be absent, otherwise no gateway is found
105
    // FreeBSD IPv4 - does not matter, the gateway is found with or without this
106
    // FreeBSD IPv6 - this must be present, otherwise no gateway is found
107
    request.data.rtm_flags = RTM_F_PREFIX;
108
#endif
109
0
    request.dst_hdr.nla_type = RTA_DST;
110
0
    request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len;
111
112
0
    if (sock->Send(&request, request.hdr.nlmsg_len, 0) != static_cast<ssize_t>(request.hdr.nlmsg_len)) {
113
0
        LogError("send() to netlink socket: %s\n", NetworkErrorString(errno));
114
0
        return std::nullopt;
115
0
    }
116
117
    // Receive response.
118
0
    char response[4096];
119
0
    ssize_t total_bytes_read{0};
120
0
    bool done{false};
121
0
    while (!done) {
122
0
        int64_t recv_result;
123
0
        do {
124
0
            recv_result = sock->Recv(response, sizeof(response), 0);
125
0
        } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN));
126
0
        if (recv_result < 0) {
127
0
            LogError("recv() from netlink socket: %s\n", NetworkErrorString(errno));
128
0
            return std::nullopt;
129
0
        }
130
131
0
        total_bytes_read += recv_result;
132
0
        if (total_bytes_read > NETLINK_MAX_RESPONSE_SIZE) {
133
0
            LogWarning("Netlink response exceeded size limit (%zu bytes, family=%d)\n", NETLINK_MAX_RESPONSE_SIZE, family);
134
0
            return std::nullopt;
135
0
        }
136
137
0
        using recv_result_t = std::conditional_t<std::is_signed_v<decltype(NLMSG_HDRLEN)>, int64_t, decltype(NLMSG_HDRLEN)>;
138
139
0
        for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, static_cast<recv_result_t>(recv_result)); hdr = NLMSG_NEXT(hdr, recv_result)) {
140
0
            if (!(hdr->nlmsg_flags & NLM_F_MULTI)) {
141
0
                done = true;
142
0
            }
143
144
0
            if (hdr->nlmsg_type == NLMSG_DONE) {
145
0
                done = true;
146
0
                break;
147
0
            }
148
149
0
            rtmsg* r = (rtmsg*)NLMSG_DATA(hdr);
150
0
            int remaining_len = RTM_PAYLOAD(hdr);
151
152
0
            if (hdr->nlmsg_type != RTM_NEWROUTE) {
153
0
                continue; // Skip non-route messages
154
0
            }
155
156
            // Only consider default routes (destination prefix length of 0).
157
0
            if (r->rtm_dst_len != 0) {
158
0
                continue;
159
0
            }
160
161
            // Iterate over the attributes.
162
0
            rtattr* rta_gateway = nullptr;
163
0
            int scope_id = 0;
164
0
            for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) {
165
0
                if (attr->rta_type == RTA_GATEWAY) {
166
0
                    rta_gateway = attr;
167
0
                } else if (attr->rta_type == RTA_OIF && sizeof(int) == RTA_PAYLOAD(attr)) {
168
0
                    std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id));
169
0
                }
170
0
            }
171
172
            // Found gateway?
173
0
            if (rta_gateway != nullptr) {
174
0
                if (family == AF_INET && sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) {
175
0
                    in_addr gw;
176
0
                    std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw));
177
0
                    return CNetAddr(gw);
178
0
                } else if (family == AF_INET6 && sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) {
179
0
                    in6_addr gw;
180
0
                    std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw));
181
0
                    return CNetAddr(gw, scope_id);
182
0
                }
183
0
            }
184
0
        }
185
0
    }
186
187
0
    return std::nullopt;
188
0
}
189
190
#elif defined(WIN32)
191
192
std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
193
{
194
    NET_LUID interface_luid = {};
195
    SOCKADDR_INET destination_address = {};
196
    MIB_IPFORWARD_ROW2 best_route = {};
197
    SOCKADDR_INET best_source_address = {};
198
    DWORD best_if_idx = 0;
199
    DWORD status = 0;
200
201
    // Pass empty destination address of the requested type (:: or 0.0.0.0) to get interface of default route.
202
    destination_address.si_family = family;
203
    status = GetBestInterfaceEx((sockaddr*)&destination_address, &best_if_idx);
204
    if (status != NO_ERROR) {
205
        LogError("Could not get best interface for default route: %s\n", NetworkErrorString(status));
206
        return std::nullopt;
207
    }
208
209
    // Get best route to default gateway.
210
    // Leave interface_luid at all-zeros to use interface index instead.
211
    status = GetBestRoute2(&interface_luid, best_if_idx, nullptr, &destination_address, 0, &best_route, &best_source_address);
212
    if (status != NO_ERROR) {
213
        LogError("Could not get best route for default route for interface index %d: %s\n",
214
                best_if_idx, NetworkErrorString(status));
215
        return std::nullopt;
216
    }
217
218
    Assume(best_route.NextHop.si_family == family);
219
    if (family == AF_INET) {
220
        return CNetAddr(best_route.NextHop.Ipv4.sin_addr);
221
    } else if(family == AF_INET6) {
222
        return CNetAddr(best_route.NextHop.Ipv6.sin6_addr, best_route.InterfaceIndex);
223
    }
224
    return std::nullopt;
225
}
226
227
#elif defined(__APPLE__)
228
229
#define ROUNDUP32(a) \
230
    ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))
231
232
//! MacOS: Get default gateway from route table. See route(4) for the format.
233
std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family)
234
{
235
    // net.route.0.inet[6].flags.gateway
236
    int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY};
237
    // The size of the available data is determined by calling sysctl() with oldp=nullptr. See sysctl(3).
238
    size_t l = 0;
239
    if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/nullptr, /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) {
240
        LogError("Could not get sysctl length of routing table: %s\n", NetworkErrorString(errno));
241
        return std::nullopt;
242
    }
243
    std::vector<std::byte> buf(l);
244
    if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/buf.data(), /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) {
245
        LogError("Could not get sysctl data of routing table: %s\n", NetworkErrorString(errno));
246
        return std::nullopt;
247
    }
248
    // Iterate over messages (each message is a routing table entry).
249
    for (size_t msg_pos = 0; msg_pos < buf.size(); ) {
250
        if ((msg_pos + sizeof(rt_msghdr)) > buf.size()) return std::nullopt;
251
        const struct rt_msghdr* rt = (const struct rt_msghdr*)(buf.data() + msg_pos);
252
        const size_t next_msg_pos = msg_pos + rt->rtm_msglen;
253
        if (rt->rtm_msglen < sizeof(rt_msghdr) || next_msg_pos > buf.size()) return std::nullopt;
254
        // Iterate over addresses within message, get destination and gateway (if present).
255
        // Address data starts after header.
256
        size_t sa_pos = msg_pos + sizeof(struct rt_msghdr);
257
        std::optional<CNetAddr> dst, gateway;
258
        for (int i = 0; i < RTAX_MAX; i++) {
259
            if (rt->rtm_addrs & (1 << i)) {
260
                // 2 is just sa_len + sa_family, the theoretical minimum size of a socket address.
261
                if ((sa_pos + 2) > next_msg_pos) return std::nullopt;
262
                const struct sockaddr* sa = (const struct sockaddr*)(buf.data() + sa_pos);
263
                if ((sa_pos + sa->sa_len) > next_msg_pos) return std::nullopt;
264
                if (i == RTAX_DST) {
265
                    dst = FromSockAddr(sa, sa->sa_len);
266
                } else if (i == RTAX_GATEWAY) {
267
                    gateway = FromSockAddr(sa, sa->sa_len);
268
                }
269
                // Skip sockaddr entries for bit flags we're not interested in,
270
                // move cursor.
271
                sa_pos += ROUNDUP32(sa->sa_len);
272
            }
273
        }
274
        // Found default gateway?
275
        if (dst && gateway && dst->IsBindAny()) { // Route to 0.0.0.0 or :: ?
276
            return *gateway;
277
        }
278
        // Skip to next message.
279
        msg_pos = next_msg_pos;
280
    }
281
    return std::nullopt;
282
}
283
284
#else
285
286
// Dummy implementation.
287
std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t)
288
{
289
    return std::nullopt;
290
}
291
292
#endif
293
294
}
295
296
std::optional<CNetAddr> QueryDefaultGateway(Network network)
297
0
{
298
0
    Assume(network == NET_IPV4 || network == NET_IPV6);
299
300
0
    sa_family_t family;
301
0
    if (network == NET_IPV4) {
302
0
        family = AF_INET;
303
0
    } else if(network == NET_IPV6) {
304
0
        family = AF_INET6;
305
0
    } else {
306
0
        return std::nullopt;
307
0
    }
308
309
0
    std::optional<CNetAddr> ret = QueryDefaultGatewayImpl(family);
310
311
    // It's possible for the default gateway to be 0.0.0.0 or ::0 on at least Windows
312
    // for some routing strategies. If so, return as if no default gateway was found.
313
0
    if (ret && !ret->IsBindAny()) {
314
0
        return ret;
315
0
    } else {
316
0
        return std::nullopt;
317
0
    }
318
0
}
319
320
std::vector<CNetAddr> GetLocalAddresses()
321
6
{
322
6
    std::vector<CNetAddr> addresses;
323
#ifdef WIN32
324
    DWORD status = 0;
325
    constexpr size_t MAX_ADAPTER_ADDR_SIZE = 4 * 1000 * 1000; // Absolute maximum size of adapter addresses structure we're willing to handle, as a precaution.
326
    std::vector<std::byte> out_buf(15000, {}); // Start with 15KB allocation as recommended in GetAdaptersAddresses documentation.
327
    while (true) {
328
        ULONG out_buf_len = out_buf.size();
329
        status = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
330
                nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(out_buf.data()), &out_buf_len);
331
        if (status == ERROR_BUFFER_OVERFLOW && out_buf.size() < MAX_ADAPTER_ADDR_SIZE) {
332
            // If status == ERROR_BUFFER_OVERFLOW, out_buf_len will contain the needed size.
333
            // Unfortunately, this cannot be fully relied on, because another process may have added interfaces.
334
            // So to avoid getting stuck due to a race condition, double the buffer size at least
335
            // once before retrying (but only up to the maximum allowed size).
336
            out_buf.resize(std::min(std::max<size_t>(out_buf_len, out_buf.size()) * 2, MAX_ADAPTER_ADDR_SIZE));
337
        } else {
338
            break;
339
        }
340
    }
341
342
    if (status != NO_ERROR) {
343
        // This includes ERROR_NO_DATA if there are no addresses and thus there's not even one PIP_ADAPTER_ADDRESSES
344
        // record in the returned structure.
345
        LogError("Could not get local adapter addresses: %s\n", NetworkErrorString(status));
346
        return addresses;
347
    }
348
349
    // Iterate over network adapters.
350
    for (PIP_ADAPTER_ADDRESSES cur_adapter = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(out_buf.data());
351
         cur_adapter != nullptr; cur_adapter = cur_adapter->Next) {
352
        if (cur_adapter->OperStatus != IfOperStatusUp) continue;
353
        if (cur_adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
354
355
        // Iterate over unicast addresses for adapter, the only address type we're interested in.
356
        for (PIP_ADAPTER_UNICAST_ADDRESS cur_address = cur_adapter->FirstUnicastAddress;
357
             cur_address != nullptr; cur_address = cur_address->Next) {
358
            // "The IP address is a cluster address and should not be used by most applications."
359
            if ((cur_address->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) != 0) continue;
360
361
            if (std::optional<CNetAddr> addr = FromSockAddr(cur_address->Address.lpSockaddr, static_cast<socklen_t>(cur_address->Address.iSockaddrLength))) {
362
                addresses.push_back(*addr);
363
            }
364
        }
365
    }
366
#elif defined(HAVE_IFADDRS)
367
    struct ifaddrs* myaddrs;
368
6
    if (getifaddrs(&myaddrs) == 0) {
369
54
        for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
370
48
        {
371
48
            if (ifa->ifa_addr == nullptr) continue;
372
48
            if ((ifa->ifa_flags & IFF_UP) == 0) continue;
373
48
            if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue;
374
375
30
            if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) {
376
18
                addresses.push_back(*addr);
377
18
            }
378
30
        }
379
6
        freeifaddrs(myaddrs);
380
6
    }
381
6
#endif
382
6
    return addresses;
383
6
}