/root/bitcoin/src/common/netif.cpp
Line | Count | Source |
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 | | |
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 | 0 | { |
43 | 0 | socklen_t sa_len = 0; |
44 | 0 | if (sa_len_opt.has_value()) { |
45 | 0 | sa_len = *sa_len_opt; |
46 | 0 | } else { |
47 | | // If sockaddr length was not specified, determine it from the family. |
48 | 0 | switch (addr->sa_family) { |
49 | 0 | case AF_INET: sa_len = sizeof(struct sockaddr_in); break; |
50 | 0 | case AF_INET6: sa_len = sizeof(struct sockaddr_in6); break; |
51 | 0 | default: |
52 | 0 | return std::nullopt; |
53 | 0 | } |
54 | 0 | } |
55 | | // Fill in a CService from the sockaddr, then drop the port part. |
56 | 0 | CService service; |
57 | 0 | if (service.SetSockAddr(addr, sa_len)) { |
58 | 0 | return (CNetAddr)service; |
59 | 0 | } |
60 | 0 | return std::nullopt; |
61 | 0 | } |
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 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
69 | 0 | { |
70 | | // Create a netlink socket. |
71 | 0 | auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)}; |
72 | 0 | if (!sock) { |
73 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "socket(AF_NETLINK): %s\n", NetworkErrorString(errno)); |
74 | 0 | return std::nullopt; |
75 | 0 | } |
76 | | |
77 | | // Send request. |
78 | 0 | struct { |
79 | 0 | nlmsghdr hdr; ///< Request header. |
80 | 0 | rtmsg data; ///< Request data, a "route message". |
81 | 0 | nlattr dst_hdr; ///< One attribute, conveying the route destination address. |
82 | 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. |
83 | 0 | } request{}; |
84 | | |
85 | | // Whether to use the first 4 or 16 bytes from request.dst_data. |
86 | 0 | const size_t dst_data_len = family == AF_INET ? 4 : 16; |
87 | |
|
88 | 0 | request.hdr.nlmsg_type = RTM_GETROUTE; |
89 | 0 | request.hdr.nlmsg_flags = NLM_F_REQUEST; |
90 | 0 | #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 | 0 | request.hdr.nlmsg_flags |= NLM_F_DUMP; |
95 | 0 | #endif |
96 | 0 | request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len); |
97 | 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. |
98 | 0 | request.data.rtm_family = family; |
99 | 0 | 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 | 0 | request.dst_hdr.nla_type = RTA_DST; |
107 | 0 | request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len; |
108 | |
|
109 | 0 | if (sock->Send(&request, request.hdr.nlmsg_len, 0) != static_cast<ssize_t>(request.hdr.nlmsg_len)) { |
110 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "send() to netlink socket: %s\n", NetworkErrorString(errno)); |
111 | 0 | return std::nullopt; |
112 | 0 | } |
113 | | |
114 | | // Receive response. |
115 | 0 | char response[4096]; |
116 | 0 | int64_t recv_result; |
117 | 0 | do { |
118 | 0 | recv_result = sock->Recv(response, sizeof(response), 0); |
119 | 0 | } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN)); |
120 | 0 | if (recv_result < 0) { |
121 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "recv() from netlink socket: %s\n", NetworkErrorString(errno)); |
122 | 0 | return std::nullopt; |
123 | 0 | } |
124 | | |
125 | 0 | for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, recv_result); hdr = NLMSG_NEXT(hdr, recv_result)) { |
126 | 0 | rtmsg* r = (rtmsg*)NLMSG_DATA(hdr); |
127 | 0 | int remaining_len = RTM_PAYLOAD(hdr); |
128 | | |
129 | | // Iterate over the attributes. |
130 | 0 | rtattr *rta_gateway = nullptr; |
131 | 0 | int scope_id = 0; |
132 | 0 | for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) { |
133 | 0 | if (attr->rta_type == RTA_GATEWAY) { |
134 | 0 | rta_gateway = attr; |
135 | 0 | } else if (attr->rta_type == RTA_OIF && sizeof(int) == RTA_PAYLOAD(attr)) { |
136 | 0 | std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id)); |
137 | 0 | } |
138 | 0 | } |
139 | | |
140 | | // Found gateway? |
141 | 0 | if (rta_gateway != nullptr) { |
142 | 0 | if (family == AF_INET && sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) { |
143 | 0 | in_addr gw; |
144 | 0 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
145 | 0 | return CNetAddr(gw); |
146 | 0 | } else if (family == AF_INET6 && sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) { |
147 | 0 | in6_addr gw; |
148 | 0 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
149 | 0 | return CNetAddr(gw, scope_id); |
150 | 0 | } |
151 | 0 | } |
152 | 0 | } |
153 | | |
154 | 0 | return std::nullopt; |
155 | 0 | } |
156 | | |
157 | | #elif defined(WIN32) |
158 | | |
159 | | std::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 | | |
199 | | //! MacOS: Get default gateway from route table. See route(4) for the format. |
200 | | std::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. |
254 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t) |
255 | | { |
256 | | return std::nullopt; |
257 | | } |
258 | | |
259 | | #endif |
260 | | |
261 | | } |
262 | | |
263 | | std::optional<CNetAddr> QueryDefaultGateway(Network network) |
264 | 0 | { |
265 | 0 | Assume(network == NET_IPV4 || network == NET_IPV6); |
266 | |
|
267 | 0 | sa_family_t family; |
268 | 0 | if (network == NET_IPV4) { |
269 | 0 | family = AF_INET; |
270 | 0 | } else if(network == NET_IPV6) { |
271 | 0 | family = AF_INET6; |
272 | 0 | } else { |
273 | 0 | return std::nullopt; |
274 | 0 | } |
275 | | |
276 | 0 | 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 | 0 | if (ret && !ret->IsBindAny()) { |
281 | 0 | return ret; |
282 | 0 | } else { |
283 | 0 | return std::nullopt; |
284 | 0 | } |
285 | 0 | } |
286 | | |
287 | | std::vector<CNetAddr> GetLocalAddresses() |
288 | 0 | { |
289 | 0 | 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 | 0 | if (getifaddrs(&myaddrs) == 0) { |
336 | 0 | for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) |
337 | 0 | { |
338 | 0 | if (ifa->ifa_addr == nullptr) continue; |
339 | 0 | if ((ifa->ifa_flags & IFF_UP) == 0) continue; |
340 | 0 | if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; |
341 | | |
342 | 0 | if (std::optional<CNetAddr> addr = FromSockAddr(ifa->ifa_addr, std::nullopt)) { |
343 | 0 | addresses.push_back(*addr); |
344 | 0 | } |
345 | 0 | } |
346 | 0 | freeifaddrs(myaddrs); |
347 | 0 | } |
348 | 0 | #endif |
349 | 0 | return addresses; |
350 | 0 | } |