netif.cpp raw

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