netif.cpp raw

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