|
| 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 <util/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 | +{ |
| 41 | + // Create a netlink socket. |
| 42 | + auto sock{CreateSock(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)}; |
| 43 | + if (!sock) { |
| 44 | + LogPrintLevel(BCLog::NET, BCLog::Level::Error, "socket(AF_NETLINK): %s\n", NetworkErrorString(errno)); |
| 45 | + return std::nullopt; |
| 46 | + } |
| 47 | + |
| 48 | + // Send request. |
| 49 | + struct { |
| 50 | + nlmsghdr hdr; ///< Request header. |
| 51 | + rtmsg data; ///< Request data, a "route message". |
| 52 | + nlattr dst_hdr; ///< One attribute, conveying the route destination address. |
| 53 | + 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 | + } request{}; |
| 55 | + |
| 56 | + // Whether to use the first 4 or 16 bytes from request.dst_data. |
| 57 | + const size_t dst_data_len = family == AF_INET ? 4 : 16; |
| 58 | + |
| 59 | + request.hdr.nlmsg_type = RTM_GETROUTE; |
| 60 | + request.hdr.nlmsg_flags = NLM_F_REQUEST; |
| 61 | +#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 | + request.hdr.nlmsg_flags |= NLM_F_DUMP; |
| 66 | +#endif |
| 67 | + request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg) + sizeof(nlattr) + dst_data_len); |
| 68 | + 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 | + request.data.rtm_family = family; |
| 70 | + 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 | + request.dst_hdr.nla_type = RTA_DST; |
| 78 | + request.dst_hdr.nla_len = sizeof(nlattr) + dst_data_len; |
| 79 | + |
| 80 | + if (sock->Send(&request, request.hdr.nlmsg_len, 0) != static_cast<ssize_t>(request.hdr.nlmsg_len)) { |
| 81 | + LogPrintLevel(BCLog::NET, BCLog::Level::Error, "send() to netlink socket: %s\n", NetworkErrorString(errno)); |
| 82 | + return std::nullopt; |
| 83 | + } |
| 84 | + |
| 85 | + // Receive response. |
| 86 | + char response[4096]; |
| 87 | + int64_t recv_result; |
| 88 | + do { |
| 89 | + recv_result = sock->Recv(response, sizeof(response), 0); |
| 90 | + } while (recv_result < 0 && (errno == EINTR || errno == EAGAIN)); |
| 91 | + if (recv_result < 0) { |
| 92 | + LogPrintLevel(BCLog::NET, BCLog::Level::Error, "recv() from netlink socket: %s\n", NetworkErrorString(errno)); |
| 93 | + return std::nullopt; |
| 94 | + } |
| 95 | + |
| 96 | + for (nlmsghdr* hdr = (nlmsghdr*)response; NLMSG_OK(hdr, recv_result); hdr = NLMSG_NEXT(hdr, recv_result)) { |
| 97 | + rtmsg* r = (rtmsg*)NLMSG_DATA(hdr); |
| 98 | + int remaining_len = RTM_PAYLOAD(hdr); |
| 99 | + |
| 100 | + // Iterate over the attributes. |
| 101 | + rtattr *rta_gateway = nullptr; |
| 102 | + int scope_id = 0; |
| 103 | + for (rtattr* attr = RTM_RTA(r); RTA_OK(attr, remaining_len); attr = RTA_NEXT(attr, remaining_len)) { |
| 104 | + if (attr->rta_type == RTA_GATEWAY) { |
| 105 | + rta_gateway = attr; |
| 106 | + } else if (attr->rta_type == RTA_OIF && sizeof(int) == RTA_PAYLOAD(attr)) { |
| 107 | + std::memcpy(&scope_id, RTA_DATA(attr), sizeof(scope_id)); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // Found gateway? |
| 112 | + if (rta_gateway != nullptr) { |
| 113 | + if (family == AF_INET && sizeof(in_addr) == RTA_PAYLOAD(rta_gateway)) { |
| 114 | + in_addr gw; |
| 115 | + std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
| 116 | + return CNetAddr(gw); |
| 117 | + } else if (family == AF_INET6 && sizeof(in6_addr) == RTA_PAYLOAD(rta_gateway)) { |
| 118 | + in6_addr gw; |
| 119 | + std::memcpy(&gw, RTA_DATA(rta_gateway), sizeof(gw)); |
| 120 | + return CNetAddr(gw, scope_id); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + return std::nullopt; |
| 126 | +} |
| 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 | + // Check valid length. Note that sa_len is not part of POSIX, and exists on MacOS and some BSDs only, so we can't |
| 173 | + // do this check in SetSockAddr. |
| 174 | + if (!(addr->sa_family == AF_INET && addr->sa_len == sizeof(struct sockaddr_in)) && |
| 175 | + !(addr->sa_family == AF_INET6 && addr->sa_len == sizeof(struct sockaddr_in6))) { |
| 176 | + return std::nullopt; |
| 177 | + } |
| 178 | + |
| 179 | + // Fill in a CService from the sockaddr, then drop the port part. |
| 180 | + CService service; |
| 181 | + if (service.SetSockAddr(addr)) { |
| 182 | + return (CNetAddr)service; |
| 183 | + } |
| 184 | + return std::nullopt; |
| 185 | +} |
| 186 | + |
| 187 | +//! MacOS: Get default gateway from route table. See route(4) for the format. |
| 188 | +std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t family) |
| 189 | +{ |
| 190 | + // net.route.0.inet[6].flags.gateway |
| 191 | + int mib[] = {CTL_NET, PF_ROUTE, 0, family, NET_RT_FLAGS, RTF_GATEWAY}; |
| 192 | + // The size of the available data is determined by calling sysctl() with oldp=nullptr. See sysctl(3). |
| 193 | + size_t l = 0; |
| 194 | + if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/nullptr, /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) { |
| 195 | + LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get sysctl length of routing table: %s\n", SysErrorString(errno)); |
| 196 | + return std::nullopt; |
| 197 | + } |
| 198 | + std::vector<std::byte> buf(l); |
| 199 | + if (sysctl(/*name=*/mib, /*namelen=*/sizeof(mib) / sizeof(int), /*oldp=*/buf.data(), /*oldlenp=*/&l, /*newp=*/nullptr, /*newlen=*/0) < 0) { |
| 200 | + LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Could not get sysctl data of routing table: %s\n", SysErrorString(errno)); |
| 201 | + return std::nullopt; |
| 202 | + } |
| 203 | + // Iterate over messages (each message is a routing table entry). |
| 204 | + for (size_t msg_pos = 0; msg_pos < buf.size(); ) { |
| 205 | + if ((msg_pos + sizeof(rt_msghdr)) > buf.size()) return std::nullopt; |
| 206 | + const struct rt_msghdr* rt = (const struct rt_msghdr*)(buf.data() + msg_pos); |
| 207 | + const size_t next_msg_pos = msg_pos + rt->rtm_msglen; |
| 208 | + if (rt->rtm_msglen < sizeof(rt_msghdr) || next_msg_pos > buf.size()) return std::nullopt; |
| 209 | + // Iterate over addresses within message, get destination and gateway (if present). |
| 210 | + // Address data starts after header. |
| 211 | + size_t sa_pos = msg_pos + sizeof(struct rt_msghdr); |
| 212 | + std::optional<CNetAddr> dst, gateway; |
| 213 | + for (int i = 0; i < RTAX_MAX; i++) { |
| 214 | + if (rt->rtm_addrs & (1 << i)) { |
| 215 | + // 2 is just sa_len + sa_family, the theoretical minimum size of a socket address. |
| 216 | + if ((sa_pos + 2) > next_msg_pos) return std::nullopt; |
| 217 | + const struct sockaddr* sa = (const struct sockaddr*)(buf.data() + sa_pos); |
| 218 | + if ((sa_pos + sa->sa_len) > next_msg_pos) return std::nullopt; |
| 219 | + if (i == RTAX_DST) { |
| 220 | + dst = FromSockAddr(sa); |
| 221 | + } else if (i == RTAX_GATEWAY) { |
| 222 | + gateway = FromSockAddr(sa); |
| 223 | + } |
| 224 | + // Skip sockaddr entries for bit flags we're not interested in, |
| 225 | + // move cursor. |
| 226 | + sa_pos += ROUNDUP32(sa->sa_len); |
| 227 | + } |
| 228 | + } |
| 229 | + // Found default gateway? |
| 230 | + if (dst && gateway && dst->IsBindAny()) { // Route to 0.0.0.0 or :: ? |
| 231 | + return *gateway; |
| 232 | + } |
| 233 | + // Skip to next message. |
| 234 | + msg_pos = next_msg_pos; |
| 235 | + } |
| 236 | + return std::nullopt; |
| 237 | +} |
| 238 | + |
| 239 | +#else |
| 240 | + |
| 241 | +// Dummy implementation. |
| 242 | +std::optional<CNetAddr> QueryDefaultGatewayImpl(sa_family_t) |
| 243 | +{ |
| 244 | + return std::nullopt; |
| 245 | +} |
| 246 | + |
| 247 | +#endif |
| 248 | + |
| 249 | +} |
| 250 | + |
| 251 | +std::optional<CNetAddr> QueryDefaultGateway(Network network) |
| 252 | +{ |
| 253 | + Assume(network == NET_IPV4 || network == NET_IPV6); |
| 254 | + |
| 255 | + sa_family_t family; |
| 256 | + if (network == NET_IPV4) { |
| 257 | + family = AF_INET; |
| 258 | + } else if(network == NET_IPV6) { |
| 259 | + family = AF_INET6; |
| 260 | + } else { |
| 261 | + return std::nullopt; |
| 262 | + } |
| 263 | + |
| 264 | + std::optional<CNetAddr> ret = QueryDefaultGatewayImpl(family); |
| 265 | + |
| 266 | + // It's possible for the default gateway to be 0.0.0.0 or ::0 on at least Windows |
| 267 | + // for some routing strategies. If so, return as if no default gateway was found. |
| 268 | + if (ret && !ret->IsBindAny()) { |
| 269 | + return ret; |
| 270 | + } else { |
| 271 | + return std::nullopt; |
| 272 | + } |
| 273 | +} |
| 274 | + |
| 275 | +std::vector<CNetAddr> GetLocalAddresses() |
| 276 | +{ |
| 277 | + std::vector<CNetAddr> addresses; |
| 278 | +#ifdef WIN32 |
| 279 | + char pszHostName[256] = ""; |
| 280 | + if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { |
| 281 | + addresses = LookupHost(pszHostName, 0, true); |
| 282 | + } |
| 283 | +#elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS) |
| 284 | + struct ifaddrs* myaddrs; |
| 285 | + if (getifaddrs(&myaddrs) == 0) { |
| 286 | + for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) |
| 287 | + { |
| 288 | + if (ifa->ifa_addr == nullptr) continue; |
| 289 | + if ((ifa->ifa_flags & IFF_UP) == 0) continue; |
| 290 | + if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; |
| 291 | + if (ifa->ifa_addr->sa_family == AF_INET) { |
| 292 | + struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); |
| 293 | + addresses.emplace_back(s4->sin_addr); |
| 294 | + } else if (ifa->ifa_addr->sa_family == AF_INET6) { |
| 295 | + struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); |
| 296 | + addresses.emplace_back(s6->sin6_addr); |
| 297 | + } |
| 298 | + } |
| 299 | + freeifaddrs(myaddrs); |
| 300 | + } |
| 301 | +#endif |
| 302 | + return addresses; |
| 303 | +} |
0 commit comments