/root/bitcoin/src/common/netif.cpp
Line | Count | Source (jump to first uncovered line) |
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 | | namespace { |
33 | | |
34 | | // Linux and FreeBSD 14.0+. For FreeBSD 13.2 the code can be compiled but |
35 | | // running it requires loading a special kernel module, otherwise socket(AF_NETLINK,...) |
36 | | // will fail, so we skip that. |
37 | | #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 1400000) |
38 | | |
39 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
40 | 0 | { |
41 | | // Create a netlink socket. |
42 | 0 | auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)}; |
43 | 0 | if (!sock) { Branch (43:9): [True: 0, False: 0]
|
44 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "socket(AF_NETLINK): %s\n", NetworkErrorString(errno)); |
45 | 0 | return std::nullopt; |
46 | 0 | } |
47 | | |
48 | | // Send request. |
49 | 0 | struct { |
50 | 0 | nlmsghdr hdr; ///< Request header. |
51 | 0 | rtmsg data; ///< Request data, a "route message". |
52 | 0 | nlattr dst_hdr; ///< One attribute, conveying the route destination address. |
53 | 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. |
54 | 0 | } request{}; |
55 | | |
56 | | // Whether to use the first 4 or 16 bytes from request.dst_data. |
57 | 0 | const size_t dst_data_len = family == AF_INET ? 4 : 16; Branch (57:33): [True: 0, False: 0]
|
58 | |
|
59 | 0 | request.hdr.nlmsg_type = RTM_GETROUTE; |
60 | 0 | request.hdr.nlmsg_flags = NLM_F_REQUEST; |
61 | 0 | #ifdef __linux__ |
62 | | // Linux IPv4 / IPv6 - this must be present, otherwise no gateway is found |
63 | | // FreeBSD IPv4 - does not matter, the gateway is found with or without this |
64 | | // FreeBSD IPv6 - this must be absent, otherwise no gateway is found |
65 | 0 | request.hdr.nlmsg_flags |= NLM_F_DUMP; |
66 | 0 | #endif |
67 | 0 | request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len); |
68 | 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. |
69 | 0 | request.data.rtm_family = family; |
70 | 0 | request.data.rtm_dst_len = 0; // Prefix length. |
71 | | #ifdef __FreeBSD__ |
72 | | // Linux IPv4 / IPv6 this must be absent, otherwise no gateway is found |
73 | | // FreeBSD IPv4 - does not matter, the gateway is found with or without this |
74 | | // FreeBSD IPv6 - this must be present, otherwise no gateway is found |
75 | | request.data.rtm_flags = RTM_F_PREFIX; |
76 | | #endif |
77 | 0 | request.dst_hdr.nla_type = RTA_DST; |
78 | 0 | request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len; |
79 | |
|
80 | 0 | if (sock->Send(&request, request.hdr.nlmsg_len, 0) != static_cast<ssize_t>(request.hdr.nlmsg_len)) { Branch (80:9): [True: 0, False: 0]
|
81 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "send() to netlink socket: %s\n", NetworkErrorString(errno)); |
82 | 0 | return std::nullopt; |
83 | 0 | } |
84 | | |
85 | | // Receive response. |
86 | 0 | char response[4096]; |
87 | 0 | int64_t recv_result; |
88 | 0 | do { |
89 | 0 | recv_result = sock->Recv(response, sizeof(response), 0); |
90 | 0 | } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN)); Branch (90:14): [True: 0, False: 0]
Branch (90:34): [True: 0, False: 0]
Branch (90:52): [True: 0, False: 0]
|
91 | 0 | if (recv_result < 0) { Branch (91:9): [True: 0, False: 0]
|
92 | 0 | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "recv() from netlink socket: %s\n", NetworkErrorString(errno)); |
93 | 0 | return std::nullopt; |
94 | 0 | } |
95 | | |
96 | 0 | for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, recv_result); hdr = NLMSG_NEXT(hdr, recv_result)) { |
97 | 0 | rtmsg* r = (rtmsg*)NLMSG_DATA(hdr); |
98 | 0 | int remaining_len = RTM_PAYLOAD(hdr); |
99 | | |
100 | | // Iterate over the attributes. |
101 | 0 | rtattr *rta_gateway = nullptr; |
102 | 0 | int scope_id = 0; |
103 | 0 | for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) { |
104 | 0 | if (attr->rta_type == RTA_GATEWAY) { Branch (104:17): [True: 0, False: 0]
|
105 | 0 | rta_gateway = attr; |
106 | 0 | } else if (attr->rta_type == RTA_OIF && sizeof(int) == RTA_PAYLOAD(attr)) { Branch (106:24): [True: 0, False: 0]
Branch (106:53): [True: 0, False: 0]
|
107 | 0 | std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id)); |
108 | 0 | } |
109 | 0 | } |
110 | | |
111 | | // Found gateway? |
112 | 0 | if (rta_gateway != nullptr) { Branch (112:13): [True: 0, False: 0]
|
113 | 0 | if (family == AF_INET && sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) { Branch (113:17): [True: 0, False: 0]
Branch (113:38): [True: 0, False: 0]
|
114 | 0 | in_addr gw; |
115 | 0 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
116 | 0 | return CNetAddr(gw); |
117 | 0 | } else if (family == AF_INET6 && sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) { Branch (117:24): [True: 0, False: 0]
Branch (117:46): [True: 0, False: 0]
|
118 | 0 | in6_addr gw; |
119 | 0 | std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
120 | 0 | return CNetAddr(gw, scope_id); |
121 | 0 | } |
122 | 0 | } |
123 | 0 | } |
124 | | |
125 | 0 | return std::nullopt; |
126 | 0 | } |
127 | | |
128 | | #elif defined(WIN32) |
129 | | |
130 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
131 | | { |
132 | | NET_LUID interface_luid = {}; |
133 | | SOCKADDR_INET destination_address = {}; |
134 | | MIB_IPFORWARD_ROW2 best_route = {}; |
135 | | SOCKADDR_INET best_source_address = {}; |
136 | | DWORD best_if_idx = 0; |
137 | | DWORD status = 0; |
138 | | |
139 | | // Pass empty destination address of the requested type (:: or 0.0.0.0) to get interface of default route. |
140 | | destination_address.si_family = family; |
141 | | status = GetBestInterfaceEx((sockaddr*)&destination_address, &best_if_idx); |
142 | | if (status != NO_ERROR) { |
143 | | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get best interface for default route: %s\n", NetworkErrorString(status)); |
144 | | return std::nullopt; |
145 | | } |
146 | | |
147 | | // Get best route to default gateway. |
148 | | // Leave interface_luid at all-zeros to use interface index instead. |
149 | | status = GetBestRoute2(&interface_luid, best_if_idx, nullptr, &destination_address, 0, &best_route, &best_source_address); |
150 | | if (status != NO_ERROR) { |
151 | | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get best route for default route for interface index %d: %s\n", |
152 | | best_if_idx, NetworkErrorString(status)); |
153 | | return std::nullopt; |
154 | | } |
155 | | |
156 | | Assume(best_route.NextHop.si_family == family); |
157 | | if (family == AF_INET) { |
158 | | return CNetAddr(best_route.NextHop.Ipv4.sin_addr); |
159 | | } else if(family == AF_INET6) { |
160 | | return CNetAddr(best_route.NextHop.Ipv6.sin6_addr, best_route.InterfaceIndex); |
161 | | } |
162 | | return std::nullopt; |
163 | | } |
164 | | |
165 | | #elif defined(__APPLE__) |
166 | | |
167 | | #define ROUNDUP32(a) \ |
168 | | ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t)) |
169 | | |
170 | | std::optional<CNetAddr> FromSockAddr(const struct sockaddr* addr) |
171 | | { |
172 | | // Fill in a CService from the sockaddr, then drop the port part. |
173 | | CService service; |
174 | | if (service.SetSockAddr(addr, addr->sa_len)) { |
175 | | return (CNetAddr)service; |
176 | | } |
177 | | return std::nullopt; |
178 | | } |
179 | | |
180 | | //! MacOS: Get default gateway from route table. See route(4) for the format. |
181 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
182 | | { |
183 | | // net.route.0.inet[6].flags.gateway |
184 | | int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY}; |
185 | | // The size of the available data is determined by calling sysctl() with oldp=nullptr. See sysctl(3). |
186 | | size_t l = 0; |
187 | | if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/nullptr, /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) { |
188 | | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get sysctl length of routing table: %s\n", SysErrorString(errno)); |
189 | | return std::nullopt; |
190 | | } |
191 | | std::vector<std::byte> buf(l); |
192 | | if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/buf.data(), /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) { |
193 | | LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get sysctl data of routing table: %s\n", SysErrorString(errno)); |
194 | | return std::nullopt; |
195 | | } |
196 | | // Iterate over messages (each message is a routing table entry). |
197 | | for (size_t msg_pos = 0; msg_pos < buf.size(); ) { |
198 | | if ((msg_pos + sizeof(rt_msghdr)) > buf.size()) return std::nullopt; |
199 | | const struct rt_msghdr* rt = (const struct rt_msghdr*)(buf.data() + msg_pos); |
200 | | const size_t next_msg_pos = msg_pos + rt->rtm_msglen; |
201 | | if (rt->rtm_msglen < sizeof(rt_msghdr) || next_msg_pos > buf.size()) return std::nullopt; |
202 | | // Iterate over addresses within message, get destination and gateway (if present). |
203 | | // Address data starts after header. |
204 | | size_t sa_pos = msg_pos + sizeof(struct rt_msghdr); |
205 | | std::optional<CNetAddr> dst, gateway; |
206 | | for (int i = 0; i < RTAX_MAX; i++) { |
207 | | if (rt->rtm_addrs & (1 << i)) { |
208 | | // 2 is just sa_len + sa_family, the theoretical minimum size of a socket address. |
209 | | if ((sa_pos + 2) > next_msg_pos) return std::nullopt; |
210 | | const struct sockaddr* sa = (const struct sockaddr*)(buf.data() + sa_pos); |
211 | | if ((sa_pos + sa->sa_len) > next_msg_pos) return std::nullopt; |
212 | | if (i == RTAX_DST) { |
213 | | dst = FromSockAddr(sa); |
214 | | } else if (i == RTAX_GATEWAY) { |
215 | | gateway = FromSockAddr(sa); |
216 | | } |
217 | | // Skip sockaddr entries for bit flags we're not interested in, |
218 | | // move cursor. |
219 | | sa_pos += ROUNDUP32(sa->sa_len); |
220 | | } |
221 | | } |
222 | | // Found default gateway? |
223 | | if (dst && gateway && dst->IsBindAny()) { // Route to 0.0.0.0 or :: ? |
224 | | return *gateway; |
225 | | } |
226 | | // Skip to next message. |
227 | | msg_pos = next_msg_pos; |
228 | | } |
229 | | return std::nullopt; |
230 | | } |
231 | | |
232 | | #else |
233 | | |
234 | | // Dummy implementation. |
235 | | std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t) |
236 | | { |
237 | | return std::nullopt; |
238 | | } |
239 | | |
240 | | #endif |
241 | | |
242 | | } |
243 | | |
244 | | std::optional<CNetAddr> QueryDefaultGateway(Network network) |
245 | 0 | { |
246 | 0 | Assume(network == NET_IPV4 || network == NET_IPV6); |
247 | |
|
248 | 0 | sa_family_t family; |
249 | 0 | if (network == NET_IPV4) { Branch (249:9): [True: 0, False: 0]
|
250 | 0 | family = AF_INET; |
251 | 0 | } else if(network == NET_IPV6) { Branch (251:15): [True: 0, False: 0]
|
252 | 0 | family = AF_INET6; |
253 | 0 | } else { |
254 | 0 | return std::nullopt; |
255 | 0 | } |
256 | | |
257 | 0 | std::optional<CNetAddr> ret = QueryDefaultGatewayImpl(family); |
258 | | |
259 | | // It's possible for the default gateway to be 0.0.0.0 or ::0 on at least Windows |
260 | | // for some routing strategies. If so, return as if no default gateway was found. |
261 | 0 | if (ret && !ret->IsBindAny()) { Branch (261:9): [True: 0, False: 0]
Branch (261:16): [True: 0, False: 0]
|
262 | 0 | return ret; |
263 | 0 | } else { |
264 | 0 | return std::nullopt; |
265 | 0 | } |
266 | 0 | } |
267 | | |
268 | | std::vector<CNetAddr> GetLocalAddresses() |
269 | 0 | { |
270 | 0 | std::vector<CNetAddr> addresses; |
271 | | #ifdef WIN32 |
272 | | char pszHostName[256] = ""; |
273 | | if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { |
274 | | addresses = LookupHost(pszHostName, 0, true); |
275 | | } |
276 | | #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS) |
277 | | struct ifaddrs* myaddrs; |
278 | 0 | if (getifaddrs(&myaddrs) == 0) { Branch (278:9): [True: 0, False: 0]
|
279 | 0 | for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) Branch (279:45): [True: 0, False: 0]
|
280 | 0 | { |
281 | 0 | if (ifa->ifa_addr == nullptr) continue; Branch (281:17): [True: 0, False: 0]
|
282 | 0 | if ((ifa->ifa_flags & IFF_UP) == 0) continue; Branch (282:17): [True: 0, False: 0]
|
283 | 0 | if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; Branch (283:17): [True: 0, False: 0]
|
284 | 0 | if (ifa->ifa_addr->sa_family == AF_INET) { Branch (284:17): [True: 0, False: 0]
|
285 | 0 | struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); |
286 | 0 | addresses.emplace_back(s4->sin_addr); |
287 | 0 | } else if (ifa->ifa_addr->sa_family == AF_INET6) { Branch (287:24): [True: 0, False: 0]
|
288 | 0 | struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); |
289 | 0 | addresses.emplace_back(s6->sin6_addr); |
290 | 0 | } |
291 | 0 | } |
292 | 0 | freeifaddrs(myaddrs); |
293 | 0 | } |
294 | 0 | #endif |
295 | 0 | return addresses; |
296 | 0 | } |