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