/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 | | #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 <ifaddrs.h> |
34 | | #endif |
35 | | |
36 | | #include <type_traits> |
37 | | |
38 | | namespace { |
39 | | |
40 | | //! Return CNetAddr for the specified OS-level network address. |
41 | | //! If a length is not given, it is taken to be sizeof(struct sockaddr_*) for the family. |
42 | | std::optional<CNetAddr> FromSockAddr(const struct sockaddr* addr, std::optional<socklen_t> sa_len_opt) |
43 | 0 | { |
44 | 0 | socklen_t sa_len = 0; |
45 | 0 | if (sa_len_opt.has_value()) { Branch (45:9): [True: 0, False: 0]
|
46 | 0 | sa_len = *sa_len_opt; |
47 | 0 | } else { |
48 | | // If sockaddr length was not specified, determine it from the family. |
49 | 0 | switch (addr->sa_family) { |
50 | 0 | case AF_INET: sa_len = sizeof(struct sockaddr_in); break; Branch (50:9): [True: 0, False: 0]
|
51 | 0 | case AF_INET6: sa_len = sizeof(struct sockaddr_in6); break; Branch (51:9): [True: 0, False: 0]
|
52 | 0 | default: Branch (52:9): [True: 0, False: 0]
|
53 | 0 | return std::nullopt; |
54 | 0 | } |
55 | 0 | } |
56 | | // Fill in a CService from the sockaddr, then drop the port part. |
57 | 0 | CService service; |
58 | 0 | if (service.SetSockAddr(addr, sa_len)) { Branch (58:9): [True: 0, False: 0]
|
59 | 0 | return (CNetAddr)service; |
60 | 0 | } |
61 | 0 | return std::nullopt; |
62 | 0 | } |
63 | | |
64 | | // Linux and FreeBSD 14.0+. For FreeBSD 13.2 the code can be compiled but |
65 | | // running it requires loading a special kernel module, otherwise socket(AF_NETLINK,...) |
66 | | // will fail, so we skip that. |
67 | | #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 1400000) |
68 | | |
69 | | // Good for responses containing ~ 10,000-15,000 routes. |
70 | | static constexpr ssize_t NETLINK_MAX_RESPONSE_SIZE{1'048'576}; |
71 | | |
72 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
73 | 54 | { |
74 | | // Create a netlink socket. |
75 | 54 | auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)}; |
76 | 54 | if (!sock) { Branch (76:9): [True: 0, False: 54]
|
77 | 0 | LogError("socket(AF_NETLINK): %s\n", NetworkErrorString(errno)); |
78 | 0 | return std::nullopt; |
79 | 0 | } |
80 | | |
81 | | // Send request. |
82 | 54 | struct { |
83 | 54 | nlmsghdr hdr; ///< Request header. |
84 | 54 | rtmsg data; ///< Request data, a "route message". |
85 | 54 | nlattr dst_hdr; ///< One attribute, conveying the route destination address. |
86 | 54 | 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. |
87 | 54 | } request{}; |
88 | | |
89 | | // Whether to use the first 4 or 16 bytes from request.dst_data. |
90 | 54 | const size_t dst_data_len = family == AF_INET ? 4 : 16; Branch (90:33): [True: 27, False: 27]
|
91 | | |
92 | 54 | request.hdr.nlmsg_type = RTM_GETROUTE; |
93 | 54 | request.hdr.nlmsg_flags = NLM_F_REQUEST; |
94 | 54 | #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 | 54 | request.hdr.nlmsg_flags |= NLM_F_DUMP; |
99 | 54 | #endif |
100 | 54 | request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len); |
101 | 54 | 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 | 54 | request.data.rtm_family = family; |
103 | 54 | 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 | 54 | request.dst_hdr.nla_type = RTA_DST; |
111 | 54 | request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len; |
112 | | |
113 | 54 | if (sock->Send(&request, request.hdr.nlmsg_len, 0) != static_cast<ssize_t>(request.hdr.nlmsg_len)) { Branch (113:9): [True: 0, False: 54]
|
114 | 0 | LogError("send() to netlink socket: %s\n", NetworkErrorString(errno)); |
115 | 0 | return std::nullopt; |
116 | 0 | } |
117 | | |
118 | | // Receive response. |
119 | 54 | char response[4096]; |
120 | 54 | ssize_t total_bytes_read{0}; |
121 | 54 | bool done{false}; |
122 | 108 | while (!done) { Branch (122:12): [True: 81, False: 27]
|
123 | 81 | int64_t recv_result; |
124 | 81 | do { |
125 | 81 | recv_result = sock->Recv(response, sizeof(response), 0); |
126 | 81 | } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN)); Branch (126:18): [True: 0, False: 81]
Branch (126:38): [True: 0, False: 0]
Branch (126:56): [True: 0, False: 0]
|
127 | 81 | if (recv_result < 0) { Branch (127:13): [True: 0, False: 81]
|
128 | 0 | LogError("recv() from netlink socket: %s\n", NetworkErrorString(errno)); |
129 | 0 | return std::nullopt; |
130 | 0 | } |
131 | | |
132 | 81 | total_bytes_read += recv_result; |
133 | 81 | if (total_bytes_read > NETLINK_MAX_RESPONSE_SIZE) { Branch (133:13): [True: 0, False: 81]
|
134 | 0 | LogWarning("Netlink response exceeded size limit (%zu bytes, family=%d)\n", NETLINK_MAX_RESPONSE_SIZE, family); |
135 | 0 | return std::nullopt; |
136 | 0 | } |
137 | | |
138 | 81 | using recv_result_t = std::conditional_t<std::is_signed_v<decltype(NLMSG_HDRLEN)>, int64_t, decltype(NLMSG_HDRLEN)>; |
139 | | |
140 | 81 | for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, static_cast<recv_result_t>(recv_result)); hdr = NLMSG_NEXT(hdr, recv_result)) { Branch (140:51): [True: 81, False: 27]
|
141 | 81 | if (!(hdr->nlmsg_flags & NLM_F_MULTI)) { Branch (141:17): [True: 0, False: 81]
|
142 | 0 | done = true; |
143 | 0 | } |
144 | | |
145 | 81 | if (hdr->nlmsg_type == NLMSG_DONE) { Branch (145:17): [True: 27, False: 54]
|
146 | 27 | done = true; |
147 | 27 | break; |
148 | 27 | } |
149 | | |
150 | 54 | rtmsg* r = (rtmsg*)NLMSG_DATA(hdr); |
151 | 54 | int remaining_len = RTM_PAYLOAD(hdr); |
152 | | |
153 | 54 | if (hdr->nlmsg_type != RTM_NEWROUTE) { Branch (153:17): [True: 0, False: 54]
|
154 | 0 | continue; // Skip non-route messages |
155 | 0 | } |
156 | | |
157 | | // Only consider default routes (destination prefix length of 0). |
158 | 54 | if (r->rtm_dst_len != 0) { Branch (158:17): [True: 27, False: 27]
|
159 | 27 | continue; |
160 | 27 | } |
161 | | |
162 | | // Iterate over the attributes. |
163 | 27 | rtattr* rta_gateway = nullptr; |
164 | 27 | int scope_id = 0; |
165 | 81 | for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) { Branch (165:45): [True: 81, False: 27]
|
166 | 81 | if (attr->rta_type == RTA_GATEWAY) { Branch (166:21): [True: 27, False: 54]
|
167 | 27 | rta_gateway = attr; |
168 | 54 | } else if (attr->rta_type == RTA_OIF && sizeof(int) == RTA_PAYLOAD(attr)) { Branch (168:28): [True: 27, False: 27]
Branch (168:57): [True: 27, False: 0]
|
169 | 27 | std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id)); |
170 | 27 | } |
171 | 81 | } |
172 | | |
173 | | // Found gateway? |
174 | 27 | if (rta_gateway != nullptr) { Branch (174:17): [True: 27, False: 0]
|
175 | 27 | if (family == AF_INET && sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) { Branch (175:21): [True: 27, False: 0]
Branch (175:42): [True: 27, False: 0]
|
176 | 27 | in_addr gw; |
177 | 27 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
178 | 27 | return CNetAddr(gw); |
179 | 27 | } else if (family == AF_INET6 && sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) { Branch (179:28): [True: 0, False: 0]
Branch (179:50): [True: 0, False: 0]
|
180 | 0 | in6_addr gw; |
181 | 0 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
182 | 0 | return CNetAddr(gw, scope_id); |
183 | 0 | } |
184 | 27 | } |
185 | 27 | } |
186 | 81 | } |
187 | | |
188 | 27 | return std::nullopt; |
189 | 54 | } |
190 | | |
191 | | #elif defined(WIN32) |
192 | | |
193 | | std::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 | | |
233 | | //! MacOS: Get default gateway from route table. See route(4) for the format. |
234 | | std::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", SysErrorString(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", SysErrorString(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. |
288 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t) |
289 | | { |
290 | | return std::nullopt; |
291 | | } |
292 | | |
293 | | #endif |
294 | | |
295 | | } |
296 | | |
297 | | std::optional<CNetAddr> QueryDefaultGateway(Network network) |
298 | 54 | { |
299 | 54 | Assume(network == NET_IPV4 || network == NET_IPV6); |
300 | | |
301 | 54 | sa_family_t family; |
302 | 54 | if (network == NET_IPV4) { Branch (302:9): [True: 27, False: 27]
|
303 | 27 | family = AF_INET; |
304 | 27 | } else if(network == NET_IPV6) { Branch (304:15): [True: 27, False: 0]
|
305 | 27 | family = AF_INET6; |
306 | 27 | } else { |
307 | 0 | return std::nullopt; |
308 | 0 | } |
309 | | |
310 | 54 | 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 | 54 | if (ret && !ret->IsBindAny()) { Branch (314:9): [True: 27, False: 27]
Branch (314:16): [True: 27, False: 0]
|
315 | 27 | return ret; |
316 | 27 | } else { |
317 | 27 | return std::nullopt; |
318 | 27 | } |
319 | 54 | } |
320 | | |
321 | | std::vector<CNetAddr> GetLocalAddresses() |
322 | 0 | { |
323 | 0 | 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 | 0 | if (getifaddrs(&myaddrs) == 0) { Branch (369:9): [True: 0, False: 0]
|
370 | 0 | for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) Branch (370:45): [True: 0, False: 0]
|
371 | 0 | { |
372 | 0 | if (ifa->ifa_addr == nullptr) continue; Branch (372:17): [True: 0, False: 0]
|
373 | 0 | if ((ifa->ifa_flags & IFF_UP) == 0) continue; Branch (373:17): [True: 0, False: 0]
|
374 | 0 | if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; Branch (374:17): [True: 0, False: 0]
|
375 | | |
376 | 0 | if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) { Branch (376:41): [True: 0, False: 0]
|
377 | 0 | addresses.push_back(*addr); |
378 | 0 | } |
379 | 0 | } |
380 | 0 | freeifaddrs(myaddrs); |
381 | 0 | } |
382 | 0 | #endif |
383 | 0 | return addresses; |
384 | 0 | } |