Bitcoin ABC 0.33.3
P2P Digital Currency
netif.cpp
Go to the documentation of this file.
1// Copyright (c) 2024 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 <config/bitcoin-config.h> // IWYU pragma: keep
6
7#include <common/netif.h>
8
9#include <logging.h>
10#include <netbase.h>
11#include <util/check.h>
12#include <util/sock.h>
13#include <util/syserror.h>
14
15#if defined(__linux__)
16#include <linux/rtnetlink.h>
17#elif defined(__FreeBSD__)
18#include <osreldate.h>
19#if __FreeBSD_version >= 1400000
20// Workaround https://github.com/freebsd/freebsd-src/pull/1070.
21#define typeof __typeof
22#include <netlink/netlink.h>
23#include <netlink/netlink_route.h>
24#endif
25#elif defined(WIN32)
26#include <iphlpapi.h>
27#elif defined(__APPLE__)
28#include <net/route.h>
29#include <sys/sysctl.h>
30#endif
31
32namespace {
33
37std::optional<CNetAddr> FromSockAddr(const struct sockaddr *addr,
38 std::optional<socklen_t> sa_len_opt) {
39 socklen_t sa_len = 0;
40 if (sa_len_opt.has_value()) {
41 sa_len = *sa_len_opt;
42 } else {
43 // If sockaddr length was not specified, determine it from the family.
44 switch (addr->sa_family) {
45 case AF_INET:
46 sa_len = sizeof(struct sockaddr_in);
47 break;
48 case AF_INET6:
49 sa_len = sizeof(struct sockaddr_in6);
50 break;
51 default:
52 return std::nullopt;
53 }
54 }
55 // Fill in a CService from the sockaddr, then drop the port part.
56 CService service;
57 if (service.SetSockAddr(addr, sa_len)) {
58 return (CNetAddr)service;
59 }
60 return std::nullopt;
61}
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
65// socket(AF_NETLINK,...) 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.
69static constexpr ssize_t NETLINK_MAX_RESPONSE_SIZE{1'048'576};
70
71std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) {
72 // Create a netlink socket.
73 auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)};
74 if (!sock) {
76 "socket(AF_NETLINK): %s\n", NetworkErrorString(errno));
77 return std::nullopt;
78 }
79
80 // Send request.
81 struct {
83 nlmsghdr hdr;
85 rtmsg data;
87 nlattr dst_hdr;
90 char dst_data[16];
91 } request{};
92
93 // Whether to use the first 4 or 16 bytes from request.dst_data.
94 const size_t dst_data_len = family == AF_INET ? 4 : 16;
95
96 request.hdr.nlmsg_type = RTM_GETROUTE;
97 request.hdr.nlmsg_flags = NLM_F_REQUEST;
98#ifdef __linux__
99 // Linux IPv4 / IPv6 - this must be present, otherwise no gateway is found
100 // FreeBSD IPv4 - does not matter, the gateway is found with or without this
101 // FreeBSD IPv6 - this must be absent, otherwise no gateway is found
102 request.hdr.nlmsg_flags |= NLM_F_DUMP;
103#endif
104 request.hdr.nlmsg_len =
105 NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len);
106 // Sequence number, used to match which reply is to which request.
107 // Irrelevant for us because we send just one request.
108 request.hdr.nlmsg_seq = 0;
109 request.data.rtm_family = family;
110 // Prefix length.
111 request.data.rtm_dst_len = 0;
112#ifdef __FreeBSD__
113 // Linux IPv4 / IPv6 this must be absent, otherwise no gateway is found
114 // FreeBSD IPv4 - does not matter, the gateway is found with or without this
115 // FreeBSD IPv6 - this must be present, otherwise no gateway is found
116 request.data.rtm_flags = RTM_F_PREFIX;
117#endif
118 request.dst_hdr.nla_type = RTA_DST;
119 request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len;
120
121 if (sock->Send(&request, request.hdr.nlmsg_len, 0) !=
122 static_cast<ssize_t>(request.hdr.nlmsg_len)) {
124 "send() to netlink socket: %s\n",
125 NetworkErrorString(errno));
126 return std::nullopt;
127 }
128
129 // Receive response.
130 char response[4096];
131 ssize_t total_bytes_read{0};
132 bool done{false};
133 while (!done) {
134 int64_t recv_result;
135 do {
136 recv_result = sock->Recv(response, sizeof(response), 0);
137 } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN));
138 if (recv_result < 0) {
140 "recv() from netlink socket: %s\n",
141 NetworkErrorString(errno));
142 return std::nullopt;
143 }
144
145 total_bytes_read += recv_result;
146 if (total_bytes_read > NETLINK_MAX_RESPONSE_SIZE) {
149 "Netlink response exceeded size limit (%zu bytes, family=%d)\n",
150 NETLINK_MAX_RESPONSE_SIZE, family);
151 return std::nullopt;
152 }
153
154// Suppress a false positive clang warning (NLMSG_NEXT uses NLMSG_ALIGN
155// to force alignment)
156#if defined(__clang__)
157#pragma clang diagnostic push
158#pragma clang diagnostic ignored "-Wcast-align"
159#endif
160 for (nlmsghdr *hdr = (nlmsghdr *)response; NLMSG_OK(hdr, recv_result);
161 hdr = NLMSG_NEXT(hdr, recv_result)) {
162#if defined(__clang__)
163#pragma clang diagnostic pop
164#endif
165 if (!(hdr->nlmsg_flags & NLM_F_MULTI)) {
166 done = true;
167 }
168
169 if (hdr->nlmsg_type == NLMSG_DONE) {
170 done = true;
171 break;
172 }
173
174 rtmsg *r = (rtmsg *)NLMSG_DATA(hdr);
175 int remaining_len = RTM_PAYLOAD(hdr);
176
177 // Skip non-route messages
178 if (hdr->nlmsg_type != RTM_NEWROUTE) {
179 continue;
180 }
181
182 // Only consider default routes (destination prefix length of 0).
183 if (r->rtm_dst_len != 0) {
184 continue;
185 }
186
187 // Iterate over the attributes.
188 rtattr *rta_gateway = nullptr;
189 int scope_id = 0;
190// Suppress a false positive clang warning (RTM_RTA and RTA_NEXT use NLMSG_ALIGN
191// and RTA_ALIGN to force alignment)
192#if defined(__clang__)
193#pragma clang diagnostic push
194#pragma clang diagnostic ignored "-Wcast-align"
195#endif
196 for (rtattr *attr = RTM_RTA(r); RTA_OK(attr, remaining_len);
197 attr = RTA_NEXT(attr, remaining_len)) {
198#if defined(__clang__)
199#pragma clang diagnostic pop
200#endif
201 if (attr->rta_type == RTA_GATEWAY) {
202 rta_gateway = attr;
203 } else if (attr->rta_type == RTA_OIF &&
204 sizeof(int) == RTA_PAYLOAD(attr)) {
205 std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id));
206 }
207 }
208
209 // Found gateway?
210 if (rta_gateway != nullptr) {
211 if (family == AF_INET &&
212 sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) {
213 in_addr gw;
214 std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw));
215 return CNetAddr(gw);
216 }
217 if (family == AF_INET6 &&
218 sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) {
219 in6_addr gw;
220 std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw));
221 return CNetAddr(gw, scope_id);
222 }
223 }
224 }
225 }
226
227 return std::nullopt;
228}
229
230#elif defined(WIN32)
231
232std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) {
233 NET_LUID interface_luid = {};
234 SOCKADDR_INET destination_address = {};
235 MIB_IPFORWARD_ROW2 best_route = {};
236 SOCKADDR_INET best_source_address = {};
237 DWORD best_if_idx = 0;
238 DWORD status = 0;
239
240 // Pass empty destination address of the requested type (:: or 0.0.0.0) to
241 // get interface of default route.
242 destination_address.si_family = family;
243 status = GetBestInterfaceEx((sockaddr *)&destination_address, &best_if_idx);
244 if (status != NO_ERROR) {
246 "Could not get best interface for default route: %s\n",
247 NetworkErrorString(status));
248 return std::nullopt;
249 }
250
251 // Get best route to default gateway.
252 // Leave interface_luid at all-zeros to use interface index instead.
253 status = GetBestRoute2(&interface_luid, best_if_idx, nullptr,
254 &destination_address, 0, &best_route,
255 &best_source_address);
256 if (status != NO_ERROR) {
258 "Could not get best route for default route for "
259 "interface index %d: %s\n",
260 best_if_idx, NetworkErrorString(status));
261 return std::nullopt;
262 }
263
264 Assume(best_route.NextHop.si_family == family);
265 if (family == AF_INET) {
266 return CNetAddr(best_route.NextHop.Ipv4.sin_addr);
267 }
268 if (family == AF_INET6) {
269 return CNetAddr(best_route.NextHop.Ipv6.sin6_addr,
270 best_route.InterfaceIndex);
271 }
272 return std::nullopt;
273}
274
275#elif defined(__APPLE__)
276
277#define ROUNDUP32(a) \
278 ((a) > 0 ? (1 + (((a)-1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t))
279
281std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) {
282 // net.route.0.inet[6].flags.gateway
283 int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY};
284 // The size of the available data is determined by calling sysctl() with
285 // oldp=nullptr. See sysctl(3).
286 size_t l = 0;
287 if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int),
288 /*oldp=*/nullptr, /*oldlenp=*/&l, /*newp=*/nullptr,
289 /*newlen=*/0) < 0) {
291 "Could not get sysctl length of routing table: %s\n",
292 SysErrorString(errno));
293 return std::nullopt;
294 }
295 std::vector<std::byte> buf(l);
296 if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int),
297 /*oldp=*/buf.data(), /*oldlenp=*/&l, /*newp=*/nullptr,
298 /*newlen=*/0) < 0) {
300 "Could not get sysctl data of routing table: %s\n",
301 SysErrorString(errno));
302 return std::nullopt;
303 }
304 // Iterate over messages (each message is a routing table entry).
305 for (size_t msg_pos = 0; msg_pos < buf.size();) {
306 if ((msg_pos + sizeof(rt_msghdr)) > buf.size()) {
307 return std::nullopt;
308 }
309 const struct rt_msghdr *rt =
310 (const struct rt_msghdr *)(buf.data() + msg_pos);
311 const size_t next_msg_pos = msg_pos + rt->rtm_msglen;
312 if (rt->rtm_msglen < sizeof(rt_msghdr) || next_msg_pos > buf.size()) {
313 return std::nullopt;
314 }
315 // Iterate over addresses within message, get destination and gateway
316 // (if present). Address data starts after header.
317 size_t sa_pos = msg_pos + sizeof(struct rt_msghdr);
318 std::optional<CNetAddr> dst, gateway;
319 for (int i = 0; i < RTAX_MAX; i++) {
320 if (rt->rtm_addrs & (1 << i)) {
321 // 2 is just sa_len + sa_family, the theoretical minimum size of
322 // a socket address.
323 if ((sa_pos + 2) > next_msg_pos) {
324 return std::nullopt;
325 }
326 const struct sockaddr *sa =
327 (const struct sockaddr *)(buf.data() + sa_pos);
328 if ((sa_pos + sa->sa_len) > next_msg_pos) {
329 return std::nullopt;
330 }
331 if (i == RTAX_DST) {
332 dst = FromSockAddr(sa, sa->sa_len);
333 } else if (i == RTAX_GATEWAY) {
334 gateway = FromSockAddr(sa, sa->sa_len);
335 }
336 // Skip sockaddr entries for bit flags we're not interested in,
337 // move cursor.
338 sa_pos += ROUNDUP32(sa->sa_len);
339 }
340 }
341 // Found default gateway?
342 // Route to 0.0.0.0 or :: ?
343 if (dst && gateway && dst->IsBindAny()) {
344 return *gateway;
345 }
346 // Skip to next message.
347 msg_pos = next_msg_pos;
348 }
349 return std::nullopt;
350}
351
352#else
353
354// Dummy implementation.
355std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t) {
356 return std::nullopt;
357}
358
359#endif
360
361} // namespace
362
363std::optional<CNetAddr> QueryDefaultGateway(Network network) {
364 Assume(network == NET_IPV4 || network == NET_IPV6);
365
366 sa_family_t family;
367 if (network == NET_IPV4) {
368 family = AF_INET;
369 } else if (network == NET_IPV6) {
370 family = AF_INET6;
371 } else {
372 return std::nullopt;
373 }
374
375 std::optional<CNetAddr> ret = QueryDefaultGatewayImpl(family);
376
377 // It's possible for the default gateway to be 0.0.0.0 or ::0 on at least
378 // Windows for some routing strategies. If so, return as if no default
379 // gateway was found.
380 if (ret && !ret->IsBindAny()) {
381 return ret;
382 }
383 return std::nullopt;
384}
385
386std::vector<CNetAddr> GetLocalAddresses() {
387 std::vector<CNetAddr> addresses;
388#ifdef WIN32
389 DWORD status = 0;
390 // Absolute maximum size of adapter addresses structure we're willing to
391 // handle, as a precaution.
392 constexpr size_t MAX_ADAPTER_ADDR_SIZE = 4 * 1000 * 1000;
393 // Start with 15KB allocation as recommended in GetAdaptersAddresses
394 // documentation.
395 std::vector<std::byte> out_buf(15000, {});
396 while (true) {
397 ULONG out_buf_len = out_buf.size();
398 status = GetAdaptersAddresses(
399 AF_UNSPEC,
400 GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
401 GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
402 nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(out_buf.data()),
403 &out_buf_len);
404 if (status == ERROR_BUFFER_OVERFLOW &&
405 out_buf.size() < MAX_ADAPTER_ADDR_SIZE) {
406 // If status == ERROR_BUFFER_OVERFLOW, out_buf_len will contain the
407 // needed size. Unfortunately, this cannot be fully relied on,
408 // because another process may have added interfaces. So to avoid
409 // getting stuck due to a race condition, double the buffer size at
410 // least once before retrying (but only up to the maximum allowed
411 // size).
412 out_buf.resize(
413 std::min(std::max<size_t>(out_buf_len, out_buf.size()) * 2,
414 MAX_ADAPTER_ADDR_SIZE));
415 } else {
416 break;
417 }
418 }
419
420 if (status != NO_ERROR) {
421 // This includes ERROR_NO_DATA if there are no addresses and thus
422 // there's not even one PIP_ADAPTER_ADDRESSES record in the returned
423 // structure.
425 "Could not get local adapter addresses: %s\n",
426 NetworkErrorString(status));
427 return addresses;
428 }
429
430 // Iterate over network adapters.
431 for (PIP_ADAPTER_ADDRESSES cur_adapter =
432 reinterpret_cast<PIP_ADAPTER_ADDRESSES>(out_buf.data());
433 cur_adapter != nullptr; cur_adapter = cur_adapter->Next) {
434 if (cur_adapter->OperStatus != IfOperStatusUp) {
435 continue;
436 }
437 if (cur_adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) {
438 continue;
439 }
440
441 // Iterate over unicast addresses for adapter, the only address type
442 // we're interested in.
443 for (PIP_ADAPTER_UNICAST_ADDRESS cur_address =
444 cur_adapter->FirstUnicastAddress;
445 cur_address != nullptr; cur_address = cur_address->Next) {
446 // "The IP address is a cluster address and should not be used by
447 // most applications."
448 if ((cur_address->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) != 0) {
449 continue;
450 }
451
452 if (std::optional<CNetAddr> addr =
453 FromSockAddr(cur_address->Address.lpSockaddr,
454 static_cast<socklen_t>(
455 cur_address->Address.iSockaddrLength))) {
456 addresses.push_back(*addr);
457 }
458 }
459 }
460#elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
461 struct ifaddrs *myaddrs;
462 if (getifaddrs(&myaddrs) == 0) {
463 for (struct ifaddrs *ifa = myaddrs; ifa != nullptr;
464 ifa = ifa->ifa_next) {
465 if (ifa->ifa_addr == nullptr) {
466 continue;
467 }
468 if ((ifa->ifa_flags & IFF_UP) == 0) {
469 continue;
470 }
471 if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) {
472 continue;
473 }
474
475 if (std::optional<CNetAddr> addr =
476 FromSockAddr(ifa->ifa_addr, std::nullopt)) {
477 addresses.push_back(*addr);
478 }
479 }
480 freeifaddrs(myaddrs);
481 }
482#endif
483 return addresses;
484}
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Network address.
Definition: netaddress.h:114
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:573
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
Definition: netaddress.cpp:993
#define LogPrintLevel(category, level,...)
Definition: logging.h:437
@ NET
Definition: logging.h:69
Network
A network type.
Definition: netaddress.h:37
@ NET_IPV6
IPv6.
Definition: netaddress.h:46
@ NET_IPV4
IPv4.
Definition: netaddress.h:43
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition: netbase.cpp:660
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition: netif.cpp:386
std::optional< CNetAddr > QueryDefaultGateway(Network network)
Query the OS for the default gateway for network.
Definition: netif.cpp:363
Response response
Definition: processor.cpp:536
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:438
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:20