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