[libc-commits] [libc] 6fdd1ca - [libc] Move the netlink dump code out of if_nameindex (NFC) (#243771)
via libc-commits
libc-commits at lists.llvm.org
Wed Nov 18 04:54:46 PST 2026
Author: Pavel Labath
Date: 2026-11-18T13:54:41+01:00
New Revision: 6fdd1ca696f5ac33ea22ad9f053d2d193ca31a0e
URL: https://github.com/llvm/llvm-project/commit/6fdd1ca696f5ac33ea22ad9f053d2d193ca31a0e
DIFF: https://github.com/llvm/llvm-project/commit/6fdd1ca696f5ac33ea22ad9f053d2d193ca31a0e.diff
LOG: [libc] Move the netlink dump code out of if_nameindex (NFC) (#243771)
getifaddrs needs to talk to the kernel the same way as if_nameindex (it
needs to dump interfaces and addresses over a NETLINK_ROUTE socket), so
this patch moves the parts which aren't specific to if_nameindex into
src/__support/net/linux/netlink.h:
- NetlinkSocket, which owns the socket. Its dump function sends the
request and passes the reply messages to a callback, taking care of
NLMSG_DONE and NLMSG_ERROR along the way. If the kernel reports that the
dump was interrupted, it still reads it to the end, and returns
DumpResult::Interrupted so that the caller can retry (up to
MAX_DUMP_ATTEMPTS times, which moves here as well).
- get_nlmsg_header and for_each_rtattr for parsing the messages.
- parse_ifname, which getifaddrs will also use for IFA_LABEL.
The receive buffer handling changes a bit: the stack buffer is now local
to the dump function, and the socket only owns the large buffer, once we
need it. This keeps the socket object small, and makes it easy to keep
using the large buffer for any following dumps (getifaddrs will do two).
Since the socket can now be used for more than one dump, dump closes it
if it fails. Otherwise, the rest of the failed dump would still be
waiting in the socket, and the next dump would receive it instead of its
own reply. This way, any further dumps fail with EBADF. if_nameindex
doesn't care, as it gives up after the first error anyway.
The message handler gets a non-const reference to the message, as the
netlink macros (NLMSG_DATA, RTA_DATA, ...) cast to char *, which makes
-Wcast-qual complain if they're given a const pointer.
The length variables we pass to the NLMSG and RTA macros are now signed,
which is what the macros expect, as NLMSG_NEXT and RTA_NEXT can take
them below zero if the length of the last message (attribute) is not
aligned. The old code used a size_t, which would wrap around, and we
would go on to parse whatever was in the buffer after the message.
That's not something the kernel should send, so this only matters for
malformed input. The NLMSG one is an int64_t rather than an int, as
NLMSG_OK compares it with the (unsigned) nlmsg_len, and -Wsign-compare
doesn't like that.
The fake syscall policy and the functions for building netlink messages
move to a header in test/src/__support/net/linux, so that the getifaddrs
tests can use them too. Along the way, they get generalized a bit, so
that they can build other kinds of rtnetlink messages.
Assisted-by: Claude
Added:
libc/src/__support/net/linux/CMakeLists.txt
libc/src/__support/net/linux/netlink.h
libc/test/src/__support/net/linux/CMakeLists.txt
libc/test/src/__support/net/linux/netlink_test_support.h
Modified:
libc/src/__support/net/CMakeLists.txt
libc/src/net/if/linux/CMakeLists.txt
libc/src/net/if/linux/if_nameindex_impl.h
libc/test/src/__support/net/CMakeLists.txt
libc/test/src/net/if/linux/CMakeLists.txt
libc/test/src/net/if/linux/if_nameindex_test.cpp
Removed:
################################################################################
diff --git a/libc/src/__support/net/CMakeLists.txt b/libc/src/__support/net/CMakeLists.txt
index 20f373c71cc0d..4421f8b21573e 100644
--- a/libc/src/__support/net/CMakeLists.txt
+++ b/libc/src/__support/net/CMakeLists.txt
@@ -1,3 +1,7 @@
+if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
+ add_subdirectory(${LIBC_TARGET_OS})
+endif()
+
add_header_library(
byte_order
HDRS
diff --git a/libc/src/__support/net/linux/CMakeLists.txt b/libc/src/__support/net/linux/CMakeLists.txt
new file mode 100644
index 0000000000000..8618523325a7f
--- /dev/null
+++ b/libc/src/__support/net/linux/CMakeLists.txt
@@ -0,0 +1,20 @@
+add_header_library(
+ netlink
+ HDRS
+ netlink.h
+ DEPENDS
+ libc.hdr.errno_macros
+ libc.hdr.net_if_macros
+ libc.hdr.sys_socket_macros
+ libc.hdr.types.ssize_t
+ libc.src.__support.CPP.functional
+ libc.src.__support.CPP.scope
+ libc.src.__support.CPP.span
+ libc.src.__support.CPP.string_view
+ libc.src.__support.CPP.unique_ptr
+ libc.src.__support.checked_ptr
+ libc.src.__support.common
+ libc.src.__support.error_or
+ libc.src.__support.libc_assert
+ libc.src.string.string_utils
+)
diff --git a/libc/src/__support/net/linux/netlink.h b/libc/src/__support/net/linux/netlink.h
new file mode 100644
index 0000000000000..e922902c32e09
--- /dev/null
+++ b/libc/src/__support/net/linux/netlink.h
@@ -0,0 +1,338 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Helpers for retrieving information from the kernel over NETLINK_ROUTE
+/// sockets.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_NET_LINUX_NETLINK_H
+#define LLVM_LIBC_SRC___SUPPORT_NET_LINUX_NETLINK_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/net_if_macros.h"
+#include "hdr/sys_socket_macros.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/CPP/functional.h"
+#include "src/__support/CPP/scope.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/CPP/unique_ptr.h"
+#include "src/__support/checked_ptr.h"
+#include "src/__support/common.h"
+#include "src/__support/error_or.h"
+#include "src/__support/libc_assert.h"
+#include "src/string/string_utils.h"
+
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+namespace LIBC_NAMESPACE_DECL {
+namespace net {
+
+/// How many times callers of NetlinkSocket::dump() should try to get a
+/// consistent dump (one that was not interrupted) before giving up.
+LIBC_INLINE_VAR constexpr size_t MAX_DUMP_ATTEMPTS = 3;
+
+/// The handler which NetlinkSocket::dump() calls for every reply message of the
+/// requested type. If the handler returns an error, the dump stops, and dump()
+/// returns that error.
+///
+/// The message lives in the receive buffer, so it is only valid until the
+/// handler returns. The same goes for anything pointing into it, such as the
+/// attribute payloads passed to the for_each_rtattr callback, or the names
+/// returned by parse_ifname. Anything that needs to outlive the handler must be
+/// copied.
+///
+/// The message is not const, as the netlink macros (NLMSG_DATA, RTA_DATA, etc.)
+/// cast it to char *, which -Wcast-qual flags for const pointers.
+using NetlinkMessageHandler =
+ cpp::function_ref<ErrorOr<void>(struct nlmsghdr &)>;
+
+/// The outcome of a successful NetlinkSocket::dump().
+enum class DumpResult {
+ /// We have received all of the data, and it is consistent.
+ Complete,
+ /// The kernel reported that the data changed during the dump, so the
+ /// messages passed to the handler may be inconsistent. The caller should
+ /// discard them and try again.
+ Interrupted,
+};
+
+/// A NETLINK_ROUTE socket, which we use to get information (e.g. the list of
+/// network interfaces) from the kernel via dump requests.
+template <typename Policy> class NetlinkSocket {
+public:
+ /// Size of the initial receive buffer. The kernel limits the size of dump
+ /// datagrams to the larger of NLMSG_GOODSIZE (which is at most 8K) and the
+ /// largest buffer we have passed to recvfrom, so they always fit.
+ /// (RTM_GETLINK dumps requesting extended information via IFLA_EXT_MASK can
+ /// be larger, but that requires an attribute in the request, and dump()
+ /// never sends any.)
+ static constexpr size_t NLMSG_BUFFER_SIZE = 8192;
+
+ /// Size of the buffer we switch to if the dump gets interrupted. A larger
+ /// buffer means fewer datagrams, and so less time for the data to change
+ /// while we are reading it. The kernel caps the size of dump datagrams at (a
+ /// bit less than) 32K, so there is no point in going any higher.
+ static constexpr size_t NLMSG_LARGE_BUFFER_SIZE = 32768;
+
+ LIBC_INLINE NetlinkSocket() = default;
+ NetlinkSocket(const NetlinkSocket &) = delete;
+ NetlinkSocket &operator=(const NetlinkSocket &) = delete;
+
+ /// Closes the socket (if it is open), ignoring any errors.
+ LIBC_INLINE ~NetlinkSocket() { close_ignoring_errors(); }
+
+ /// Opens a new NETLINK_ROUTE socket. The socket must not be open already.
+ LIBC_INLINE ErrorOr<void> open() {
+ LIBC_ASSERT(fd < 0 && "socket is already open");
+ ErrorOr<int> res =
+ Policy::socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
+ if (!res.has_value())
+ return Error(res.error());
+ fd = *res;
+ return {};
+ }
+
+ /// Closes the socket, and reports any errors. The socket cannot be used
+ /// afterwards. Does nothing if the socket is not open (e.g. because it has
+ /// been closed by a failed dump()).
+ LIBC_INLINE ErrorOr<void> close() {
+ if (fd < 0)
+ return {};
+ // Linux releases the descriptor even if close() fails, so we must not try
+ // closing it again.
+ int old_fd = fd;
+ fd = -1;
+ if (ErrorOr<int> res = Policy::close(old_fd); !res.has_value())
+ return Error(res.error());
+ return {};
+ }
+
+ /// Sends a dump request of the given type, using the provided struct (e.g.
+ /// struct ifinfomsg) as the payload, and calls the handler for every message
+ /// of type `reply_type` in the response. Returns DumpResult::Interrupted if
+ /// the kernel reported that the data changed during the dump. In that case,
+ /// the following dumps on this socket use a larger receive buffer (if we
+ /// manage to allocate it), to reduce the chance of another interruption.
+ ///
+ /// Returns an error if sending the request or receiving the response fails,
+ /// if the kernel or the handler reported an error, or if the response is
+ /// malformed. The handler may have been called for some of the messages by
+ /// then. Since the rest of the dump may be left unread, and the kernel won't
+ /// start another dump on this socket until it is, dump() also closes the
+ /// socket in this case. Any further dumps then fail with EBADF, instead of
+ /// receiving the leftovers of this one.
+ template <typename Header>
+ LIBC_INLINE ErrorOr<DumpResult> dump(uint16_t type, const Header &payload,
+ uint16_t reply_type,
+ NetlinkMessageHandler handler);
+
+private:
+ int fd = -1;
+ /// The buffer we switch to after an interrupted dump. Once we have used it,
+ /// we have to keep using it, as the kernel may now send datagrams of up to
+ /// that size.
+ cpp::unique_ptr<uint8_t[]> large_buf;
+
+ /// Sends a dump request of the given type, with the given payload.
+ template <typename Header>
+ LIBC_INLINE ErrorOr<ssize_t> send_dump_request(uint16_t type,
+ const Header &payload);
+
+ /// Parses the netlink messages in the buffer and passes the ones of type
+ /// `reply_type` to the handler. Returns true if the buffer contained the
+ /// NLMSG_DONE message terminating the dump, or false if more messages should
+ /// follow. Returns an error if the kernel or the handler reported one, or if
+ /// the data is malformed. Sets `interrupted` if the kernel indicated that the
+ /// data changed during the dump.
+ LIBC_INLINE static ErrorOr<bool>
+ parse_netlink_messages(cpp::span<uint8_t> buf, uint16_t reply_type,
+ NetlinkMessageHandler handler, bool &interrupted);
+
+ /// Closes the socket (if it is open), ignoring any errors.
+ LIBC_INLINE void close_ignoring_errors() {
+ if (fd >= 0)
+ Policy::close(fd);
+ fd = -1;
+ }
+};
+
+template <typename Policy>
+template <typename Header>
+LIBC_INLINE ErrorOr<DumpResult>
+NetlinkSocket<Policy>::dump(uint16_t type, const Header &payload,
+ uint16_t reply_type,
+ NetlinkMessageHandler handler) {
+ if (fd < 0)
+ return Error(EBADF);
+ // If anything below fails, close the socket, so that the next dump doesn't
+ // receive the rest of this one.
+ cpp::scope_exit close_on_error([this]() { close_ignoring_errors(); });
+
+ ErrorOr<ssize_t> send_res = send_dump_request(type, payload);
+ if (!send_res.has_value())
+ return Error(send_res.error());
+
+ alignas(struct nlmsghdr) uint8_t stack_buf[NLMSG_BUFFER_SIZE];
+ cpp::span<uint8_t> buf(stack_buf);
+ if (large_buf)
+ buf = {large_buf.get(), NLMSG_LARGE_BUFFER_SIZE};
+
+ bool interrupted = false;
+ // The dump can come in multiple datagrams. Keep reading until we get the
+ // NLMSG_DONE message. We need to do that even if the dump was interrupted,
+ // as the kernel won't start a new dump on this socket until this one is
+ // done.
+ while (true) {
+ ErrorOr<ssize_t> recv_res =
+ Policy::recvfrom(fd, buf.data(), buf.size(), 0, nullptr, nullptr);
+ if (!recv_res.has_value())
+ return Error(recv_res.error());
+ // A netlink socket should never return an empty datagram. Bail out
+ // instead of spinning if it does.
+ if (*recv_res == 0)
+ return Error(EIO);
+
+ ErrorOr<bool> parse_res =
+ parse_netlink_messages(buf.first(static_cast<size_t>(*recv_res)),
+ reply_type, handler, interrupted);
+ if (!parse_res.has_value())
+ return Error(parse_res.error());
+ if (*parse_res)
+ break;
+ }
+ close_on_error.release();
+
+ if (!interrupted)
+ return DumpResult::Complete;
+
+ if (!large_buf) {
+ // The caller will probably want to try again. Use a larger buffer for
+ // that, to reduce the chance of another interruption. If the allocation
+ // fails, we keep using the stack buffer.
+ CheckedPtr<uint8_t[]> new_buf =
+ make_unique_for_overwrite<uint8_t[]>(NLMSG_LARGE_BUFFER_SIZE);
+ if (new_buf)
+ large_buf = new_buf.take_unique();
+ }
+ return DumpResult::Interrupted;
+}
+
+template <typename Policy>
+template <typename Header>
+LIBC_INLINE ErrorOr<ssize_t>
+NetlinkSocket<Policy>::send_dump_request(uint16_t type, const Header &payload) {
+ struct {
+ struct nlmsghdr nlh;
+ Header hdr;
+ } req = {};
+ static_assert(sizeof(req) >= NLMSG_LENGTH(sizeof(Header)));
+ req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(Header));
+ req.nlh.nlmsg_type = type;
+ req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
+ req.hdr = payload;
+
+ return Policy::sendto(fd, &req, req.nlh.nlmsg_len, 0, nullptr, 0);
+}
+
+template <typename Policy>
+LIBC_INLINE ErrorOr<bool> NetlinkSocket<Policy>::parse_netlink_messages(
+ cpp::span<uint8_t> buf, uint16_t reply_type, NetlinkMessageHandler handler,
+ bool &interrupted) {
+ // NLMSG_NEXT can take the length below zero if the length of the last
+ // message is not aligned, so it must be signed. It is wider than int so
+ // that NLMSG_OK can compare it with the unsigned nlmsg_len.
+ int64_t len = static_cast<int64_t>(buf.size());
+ for (auto *nh = reinterpret_cast<struct nlmsghdr *>(buf.data());
+ NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) {
+ if (nh->nlmsg_flags & NLM_F_DUMP_INTR)
+ interrupted = true;
+ if (nh->nlmsg_type == NLMSG_DONE) {
+ // The payload contains the result of the dump. This is how the kernel
+ // reports errors which happen in the middle of the dump.
+ if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(int)))
+ return Error(EIO);
+ int error = *reinterpret_cast<int *>(NLMSG_DATA(nh));
+ if (error < 0)
+ return Error(-error);
+ return true;
+ }
+ if (nh->nlmsg_type == NLMSG_ERROR) {
+ if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
+ return Error(EINVAL);
+ auto *err = reinterpret_cast<struct nlmsgerr *>(NLMSG_DATA(nh));
+ if (err->error == 0) {
+ // Zero means an ACK, which we shouldn't get because we didn't ask for
+ // it...
+ continue;
+ }
+ return Error(-err->error);
+ }
+ if (nh->nlmsg_type != reply_type)
+ continue;
+ if (ErrorOr<void> res = handler(*nh); !res.has_value())
+ return Error(res.error());
+ }
+ // Anything left over is garbage or a truncated message.
+ if (len != 0)
+ return Error(EIO);
+ return false;
+}
+
+/// Returns the fixed-size header (e.g. struct ifinfomsg) at the start of the
+/// message payload, or nullptr if the message is too short to contain it.
+template <typename Header>
+LIBC_INLINE Header *get_nlmsg_header(struct nlmsghdr &nh) {
+ if (nh.nlmsg_len < NLMSG_LENGTH(sizeof(Header)))
+ return nullptr;
+ return static_cast<Header *>(NLMSG_DATA(&nh));
+}
+
+/// Calls `fn(type, payload)` for every attribute (struct rtattr) in the `len`
+/// bytes starting at `rta`. These should come from the macros for the type of
+/// the message, e.g.:
+///
+/// for_each_rtattr(IFLA_RTA(ifm), IFLA_PAYLOAD(&nh), fn);
+///
+/// The message must be large enough to contain the fixed-size header (see
+/// get_nlmsg_header), as the *_PAYLOAD macros don't check that.
+template <typename Fn>
+LIBC_INLINE void for_each_rtattr(struct rtattr *rta, size_t len, Fn fn) {
+ // The RTA_* macros expect a signed length, as RTA_NEXT can take it below
+ // zero if the message length is not aligned.
+ int attr_len = static_cast<int>(len);
+ for (; RTA_OK(rta, attr_len); rta = RTA_NEXT(rta, attr_len)) {
+ fn(rta->rta_type,
+ cpp::span<const uint8_t>(static_cast<uint8_t *>(RTA_DATA(rta)),
+ RTA_PAYLOAD(rta)));
+ }
+}
+
+/// Returns the interface name stored in an IFLA_IFNAME or IFA_LABEL attribute.
+/// The name ends at the first null byte (or at the end of the payload), and is
+/// truncated to IF_NAMESIZE - 1 characters, so that it fits into IF_NAMESIZE
+/// bytes together with a null terminator. Callers rely on this when copying it
+/// into fixed-size buffers. The result points into `payload`, and is not
+/// null-terminated.
+LIBC_INLINE cpp::string_view parse_ifname(cpp::span<const uint8_t> payload) {
+ const char *name = reinterpret_cast<const char *>(payload.data());
+ size_t len = internal::strnlen(name, payload.size());
+ // Defensive check: kernel should not be providing us with names that don't
+ // fit.
+ if (len >= IF_NAMESIZE)
+ len = IF_NAMESIZE - 1;
+ return cpp::string_view(name, len);
+}
+
+} // namespace net
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_NET_LINUX_NETLINK_H
diff --git a/libc/src/net/if/linux/CMakeLists.txt b/libc/src/net/if/linux/CMakeLists.txt
index 5c59e18880ffe..7b12112cfa148 100644
--- a/libc/src/net/if/linux/CMakeLists.txt
+++ b/libc/src/net/if/linux/CMakeLists.txt
@@ -51,20 +51,18 @@ add_header_library(
libc.hdr.errno_macros
libc.hdr.net_if_macros
libc.hdr.sys_socket_macros
- libc.hdr.types.socklen_t
- libc.hdr.types.ssize_t
libc.hdr.types.struct_if_nameindex
libc.src.__support.CPP.new
+ libc.src.__support.CPP.optional
libc.src.__support.CPP.scope
libc.src.__support.CPP.span
- libc.src.__support.CPP.unique_ptr
+ libc.src.__support.CPP.string_view
libc.src.__support.alloc_checker
libc.src.__support.blockstore
- libc.src.__support.checked_ptr
libc.src.__support.common
libc.src.__support.error_or
+ libc.src.__support.net.linux.netlink
libc.src.string.memory_utils.inline_memcpy
- libc.src.string.string_utils
)
add_entrypoint_object(
diff --git a/libc/src/net/if/linux/if_nameindex_impl.h b/libc/src/net/if/linux/if_nameindex_impl.h
index 0e3daf4ea801d..567b772dc4786 100644
--- a/libc/src/net/if/linux/if_nameindex_impl.h
+++ b/libc/src/net/if/linux/if_nameindex_impl.h
@@ -17,20 +17,18 @@
#include "hdr/errno_macros.h"
#include "hdr/net_if_macros.h"
#include "hdr/sys_socket_macros.h"
-#include "hdr/types/socklen_t.h"
-#include "hdr/types/ssize_t.h"
#include "hdr/types/struct_if_nameindex.h"
#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/optional.h"
#include "src/__support/CPP/scope.h"
#include "src/__support/CPP/span.h"
-#include "src/__support/CPP/unique_ptr.h"
+#include "src/__support/CPP/string_view.h"
#include "src/__support/alloc-checker.h"
#include "src/__support/blockstore.h"
-#include "src/__support/checked_ptr.h"
#include "src/__support/common.h"
#include "src/__support/error_or.h"
+#include "src/__support/net/linux/netlink.h"
#include "src/string/memory_utils/inline_memcpy.h"
-#include "src/string/string_utils.h"
#include <linux/if_link.h>
#include <linux/netlink.h>
@@ -40,41 +38,6 @@ namespace LIBC_NAMESPACE_DECL {
namespace net {
namespace detail {
-/// Sends a RTM_GETLINK dump request packet on the given socket. The kernel will
-/// respond with one or more messages containing the list of network interfaces
-/// and their attributes.
-template <typename Policy>
-LIBC_INLINE ErrorOr<ssize_t> send_netlink_dump_request(int sockfd) {
- // The message consists of a standard netlink header followed by the
- // RTM_GETLINK payload.
- struct {
- struct nlmsghdr nlh;
- struct ifinfomsg ifm;
- } req = {};
- static_assert(sizeof(req) >= NLMSG_LENGTH(sizeof(req.ifm)));
- req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifm));
- req.nlh.nlmsg_type = RTM_GETLINK;
- req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
- req.ifm.ifi_family = AF_UNSPEC;
-
- return Policy::sendto(sockfd, &req, req.nlh.nlmsg_len, 0, nullptr, 0);
-}
-
-/// Size of the initial receive buffer. As long as we don't request any
-/// extended information (IFLA_EXT_MASK), the kernel limits the size of dump
-/// datagrams to the larger of NLMSG_GOODSIZE (which is at most 8K) and the
-/// largest buffer we have passed to recvfrom, so they always fit.
-constexpr size_t NLMSG_BUFFER_SIZE = 8192;
-
-/// Size of the buffer we switch to if the dump gets interrupted. A larger
-/// buffer means fewer datagrams, and so less time for the interface list to
-/// change while we are reading it. The kernel caps the size of dump datagrams
-/// at (a bit less than) 32K, so there is no point in going any higher.
-constexpr size_t NLMSG_LARGE_BUFFER_SIZE = 32768;
-
-/// How many times we try to get a consistent dump before giving up.
-constexpr size_t MAX_DUMP_ATTEMPTS = 3;
-
struct InterfaceEntry {
unsigned int index;
uint8_t name_length; // Length of next field.
@@ -82,76 +45,33 @@ struct InterfaceEntry {
static_assert(IF_NAMESIZE - 1 < (1u << 8));
};
-/// Parses the netlink messages in the buffer and adds the interfaces they
-/// describe to the store. Returns true if the buffer contained the NLMSG_DONE
-/// message terminating the dump, or false if more messages should follow.
-/// Returns an error if the kernel reported one or if the data is malformed.
-/// Sets `interrupted` if the kernel indicated that the interface list changed
-/// during the dump.
-LIBC_INLINE ErrorOr<bool>
-parse_netlink_messages(cpp::span<uint8_t> buf,
- BlockStore<InterfaceEntry, 16> &store,
- bool &interrupted) {
- size_t len = buf.size();
- for (auto *nh = reinterpret_cast<struct nlmsghdr *>(buf.data());
- NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) {
- if (nh->nlmsg_flags & NLM_F_DUMP_INTR)
- interrupted = true;
- if (nh->nlmsg_type == NLMSG_DONE) {
- // The payload contains the result of the dump. This is how the kernel
- // reports errors which happen in the middle of the dump.
- if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(int)))
- return Error(EIO);
- int error = *reinterpret_cast<int *>(NLMSG_DATA(nh));
- if (error < 0)
- return Error(-error);
- return true;
- }
- if (nh->nlmsg_type == NLMSG_ERROR) {
- if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
- return Error(EINVAL);
- auto *err = reinterpret_cast<struct nlmsgerr *>(NLMSG_DATA(nh));
- if (err->error == 0) {
- // Zero means an ACK, which we shouldn't get because we didn't ask for
- // it...
- continue;
- }
- return Error(-err->error);
- }
- if (nh->nlmsg_type != RTM_NEWLINK)
- continue;
- if (nh->nlmsg_len < NLMSG_LENGTH(sizeof(struct ifinfomsg)))
- continue;
-
- auto *ifm = reinterpret_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
- size_t attrlen = nh->nlmsg_len - NLMSG_LENGTH(sizeof(struct ifinfomsg));
- struct rtattr *rta = IFLA_RTA(ifm);
- for (; RTA_OK(rta, attrlen); rta = RTA_NEXT(rta, attrlen)) {
- if (rta->rta_type != IFLA_IFNAME)
- continue;
-
- size_t rta_payload_len = RTA_PAYLOAD(rta);
- const char *name_data = reinterpret_cast<const char *>(RTA_DATA(rta));
- size_t name_len = internal::strnlen(name_data, rta_payload_len);
- // Defensive check: kernel should not be providing us with names that
- // don't fit.
- if (name_len >= IF_NAMESIZE)
- name_len = IF_NAMESIZE - 1;
-
- InterfaceEntry entry;
- entry.index = static_cast<unsigned int>(ifm->ifi_index);
- entry.name_length = static_cast<uint8_t>(name_len);
- inline_memcpy(entry.name, name_data, name_len);
-
- if (!store.push_back(entry))
- return Error(ENOBUFS);
- break;
- }
- }
- // Anything left over is garbage or a truncated message.
- if (len != 0)
- return Error(EIO);
- return false;
+/// Adds the interface described by an RTM_NEWLINK message to the store.
+/// Messages which are too short, or which don't have an IFLA_IFNAME attribute,
+/// are ignored. Returns ENOBUFS if the store cannot grow.
+LIBC_INLINE ErrorOr<void> add_interface(struct nlmsghdr &nh,
+ BlockStore<InterfaceEntry, 16> &store) {
+ auto *ifm = get_nlmsg_header<struct ifinfomsg>(nh);
+ if (!ifm)
+ return {};
+
+ cpp::optional<cpp::string_view> name;
+ for_each_rtattr(IFLA_RTA(ifm), IFLA_PAYLOAD(&nh),
+ [&](unsigned short type, cpp::span<const uint8_t> payload) {
+ if (type == IFLA_IFNAME && !name)
+ name = cpp::optional<cpp::string_view>(
+ parse_ifname(payload));
+ });
+ if (!name)
+ return {};
+
+ InterfaceEntry entry;
+ entry.index = static_cast<unsigned int>(ifm->ifi_index);
+ // parse_ifname truncates the name to IF_NAMESIZE - 1 characters, so it fits.
+ entry.name_length = static_cast<uint8_t>(name->size());
+ inline_memcpy(entry.name, name->data(), name->size());
+ if (!store.push_back(entry))
+ return Error(ENOBUFS);
+ return {};
}
LIBC_INLINE ErrorOr<struct if_nameindex *>
@@ -189,89 +109,40 @@ build_if_nameindex_list(BlockStore<InterfaceEntry, 16> &store) {
return result.data();
}
-/// Receives the response to a dump request and adds the interfaces it describes
-/// to the store. Returns true if the dump was interrupted, in which case the
-/// result may be inconsistent.
-template <typename Policy>
-LIBC_INLINE ErrorOr<bool>
-receive_netlink_dump(int fd, cpp::span<uint8_t> buf,
- BlockStore<InterfaceEntry, 16> &store) {
- bool interrupted = false;
- // The dump can come in multiple datagrams. Keep reading until we get the
- // NLMSG_DONE message. We need to do that even if the dump was interrupted, as
- // the kernel won't start a new dump on this socket until this one is done.
- while (true) {
- ErrorOr<ssize_t> recv_res =
- Policy::recvfrom(fd, buf.data(), buf.size(), 0, nullptr, nullptr);
- if (!recv_res.has_value())
- return Error(recv_res.error());
- // A netlink socket should never return an empty datagram. Bail out instead
- // of spinning if it does.
- if (*recv_res == 0)
- return Error(EIO);
-
- ErrorOr<bool> parse_res = parse_netlink_messages(
- buf.first(static_cast<size_t>(*recv_res)), store, interrupted);
- if (!parse_res.has_value())
- return Error(parse_res.error());
- if (*parse_res)
- return interrupted;
- }
-}
-
} // namespace detail
template <typename Policy>
LIBC_INLINE ErrorOr<struct if_nameindex *> if_nameindex() {
- ErrorOr<int> fd_or_err =
- Policy::socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
- if (!fd_or_err.has_value())
- return Error(fd_or_err.error());
- int fd = *fd_or_err;
- cpp::scope_exit close_fd([fd]() { Policy::close(fd); });
+ NetlinkSocket<Policy> sock;
+ if (ErrorOr<void> res = sock.open(); !res.has_value())
+ return Error(res.error());
- alignas(struct nlmsghdr) uint8_t stack_buf[detail::NLMSG_BUFFER_SIZE];
- cpp::span<uint8_t> buf(stack_buf);
- cpp::unique_ptr<uint8_t[]> heap_buf;
+ // AF_UNSPEC means we want all interfaces.
+ struct ifinfomsg request = {};
+ request.ifi_family = AF_UNSPEC;
// If the interface list changes while the kernel is sending it to us, the
// result may be inconsistent: it can contain stale or duplicate entries, or
// miss some interfaces altogether. In that case, we throw it away and try
// again.
- for (size_t attempt = 0; attempt < detail::MAX_DUMP_ATTEMPTS; ++attempt) {
- ErrorOr<ssize_t> send_res = detail::send_netlink_dump_request<Policy>(fd);
- if (!send_res.has_value())
- return Error(send_res.error());
-
+ for (size_t attempt = 0; attempt < MAX_DUMP_ATTEMPTS; ++attempt) {
BlockStore<detail::InterfaceEntry, 16> store;
cpp::scope_exit destroy_store([&store]() {
BlockStore<detail::InterfaceEntry, 16>::destroy(&store);
});
- ErrorOr<bool> interrupted =
- detail::receive_netlink_dump<Policy>(fd, buf, store);
- if (!interrupted.has_value())
- return Error(interrupted.error());
-
- if (!*interrupted) {
- close_fd.release();
- if (ErrorOr<int> close_res = Policy::close(fd); !close_res.has_value())
- return Error(close_res.error());
- return detail::build_if_nameindex_list(store);
- }
+ ErrorOr<DumpResult> dump_res = sock.dump(
+ RTM_GETLINK, request, RTM_NEWLINK, [&store](struct nlmsghdr &nh) {
+ return detail::add_interface(nh, store);
+ });
+ if (!dump_res.has_value())
+ return Error(dump_res.error());
+ if (*dump_res == DumpResult::Interrupted)
+ continue;
- // Use a larger buffer for the next attempt to reduce the chance of another
- // interruption. If the allocation fails, we keep using the stack buffer.
- // Once we've switched to the larger buffer, we must not switch back, as the
- // kernel may now send datagrams of up to that size.
- if (!heap_buf) {
- CheckedPtr<uint8_t[]> new_buf =
- make_unique_for_overwrite<uint8_t[]>(detail::NLMSG_LARGE_BUFFER_SIZE);
- if (new_buf) {
- buf = {new_buf.get(), detail::NLMSG_LARGE_BUFFER_SIZE};
- heap_buf = new_buf.take_unique();
- }
- }
+ if (ErrorOr<void> close_res = sock.close(); !close_res.has_value())
+ return Error(close_res.error());
+ return detail::build_if_nameindex_list(store);
}
return Error(EAGAIN);
}
diff --git a/libc/test/src/__support/net/CMakeLists.txt b/libc/test/src/__support/net/CMakeLists.txt
index 5cade8d940e6f..2669e40f2691a 100644
--- a/libc/test/src/__support/net/CMakeLists.txt
+++ b/libc/test/src/__support/net/CMakeLists.txt
@@ -1,5 +1,9 @@
add_libc_testsuite(libc-support-net-tests PARENT libc-support-tests)
+if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
+ add_subdirectory(${LIBC_TARGET_OS})
+endif()
+
add_libc_test(
byte_order_test
SUITE
diff --git a/libc/test/src/__support/net/linux/CMakeLists.txt b/libc/test/src/__support/net/linux/CMakeLists.txt
new file mode 100644
index 0000000000000..0e76da484bcc0
--- /dev/null
+++ b/libc/test/src/__support/net/linux/CMakeLists.txt
@@ -0,0 +1,20 @@
+add_header_library(
+ netlink_test_support
+ HDRS
+ netlink_test_support.h
+ DEPENDS
+ libc.hdr.errno_macros
+ libc.hdr.types.socklen_t
+ libc.hdr.types.ssize_t
+ libc.hdr.types.struct_sockaddr
+ libc.src.__support.CPP.optional
+ libc.src.__support.CPP.span
+ libc.src.__support.CPP.string
+ libc.src.__support.CPP.string_view
+ libc.src.__support.CPP.tuple
+ libc.src.__support.common
+ libc.src.__support.error_or
+ libc.src.__support.fixedvector
+ libc.src.string.memory_utils.inline_memcpy
+ libc.src.string.memory_utils.inline_memset
+)
diff --git a/libc/test/src/__support/net/linux/netlink_test_support.h b/libc/test/src/__support/net/linux/netlink_test_support.h
new file mode 100644
index 0000000000000..0bd42b3013c9a
--- /dev/null
+++ b/libc/test/src/__support/net/linux/netlink_test_support.h
@@ -0,0 +1,199 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Helpers for testing code which talks to the kernel over netlink sockets: a
+/// fake network syscall policy, and functions for constructing the netlink
+/// messages it should return.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_TEST_SRC___SUPPORT_NET_LINUX_NETLINK_TEST_SUPPORT_H
+#define LLVM_LIBC_TEST_SRC___SUPPORT_NET_LINUX_NETLINK_TEST_SUPPORT_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/types/socklen_t.h"
+#include "hdr/types/ssize_t.h"
+#include "hdr/types/struct_sockaddr.h"
+#include "src/__support/CPP/optional.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/CPP/tuple.h"
+#include "src/__support/common.h"
+#include "src/__support/error_or.h"
+#include "src/__support/fixedvector.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+#include "src/string/memory_utils/inline_memset.h"
+
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+namespace LIBC_NAMESPACE_DECL {
+namespace testing {
+
+template <typename T, size_t CAPACITY>
+LIBC_INLINE cpp::optional<T> pop_front(FixedVector<T, CAPACITY> &vec) {
+ if (vec.empty())
+ return cpp::nullopt;
+ // TODO: Add front() and erase() to FixedVector, then clean this up.
+ T first = vec[0];
+ for (size_t i = 1; i < vec.size(); ++i)
+ vec[i - 1] = vec[i];
+ vec.pop_back();
+ return first;
+}
+
+struct FakeNetworkSyscallPolicyData {
+ FixedVector<cpp::tuple<int, int, int>, 10> socket_calls;
+ FixedVector<ErrorOr<int>, 10> socket_results;
+ FixedVector<cpp::tuple<int, size_t, int>, 10> sendto_calls;
+ FixedVector<ErrorOr<ssize_t>, 10> sendto_results;
+ // TODO: Move this into sendto_calls when FixedVector and tuple support
+ // non-trivial types.
+ cpp::string sendto_data;
+ FixedVector<int, 10> close_calls;
+ FixedVector<ErrorOr<int>, 10> close_results;
+ FixedVector<cpp::tuple<int, size_t, int>, 10> recv_calls;
+ // TODO: Make this ErrorOr<string> when ErrorOr and FixedVector support
+ // non-trivial types.
+ FixedVector<ErrorOr<cpp::span<const uint8_t>>, 10> recv_results;
+};
+
+/// A replacement for net::DefaultNetworkSyscallPolicy, which records the calls
+/// in, and returns the results programmed into, the object pointed to by DATA.
+template <FakeNetworkSyscallPolicyData *DATA> struct FakeNetworkSyscallPolicy {
+ static ErrorOr<int> socket(int domain, int type, int protocol) {
+ DATA->socket_calls.push_back(
+ cpp::tuple<int, int, int>(domain, type, protocol));
+ return pop_front(DATA->socket_results).value_or(Error(ENFILE));
+ }
+
+ static ErrorOr<ssize_t> sendto(int fd, const void *buf, size_t len, int flags,
+ const struct sockaddr *, socklen_t) {
+ DATA->sendto_calls.push_back(cpp::tuple<int, size_t, int>(fd, len, flags));
+ DATA->sendto_data += cpp::string_view(static_cast<const char *>(buf), len);
+ return pop_front(DATA->sendto_results).value_or(static_cast<ssize_t>(len));
+ }
+
+ static ErrorOr<ssize_t> recvfrom(int fd, void *buf, size_t len, int flags,
+ struct sockaddr *, socklen_t *) {
+ DATA->recv_calls.push_back(cpp::tuple<int, size_t, int>(fd, len, flags));
+ ErrorOr<cpp::span<const uint8_t>> chunk =
+ pop_front(DATA->recv_results).value_or(cpp::span<const uint8_t>());
+ if (!chunk.has_value())
+ return Error(chunk.error());
+ if (chunk->size() > len)
+ return Error(EINVAL);
+ inline_memcpy(buf, chunk->data(), chunk->size());
+ return static_cast<ssize_t>(chunk->size());
+ }
+
+ static ErrorOr<int> close(int fd) {
+ DATA->close_calls.push_back(fd);
+ return pop_front(DATA->close_results).value_or(0);
+ }
+};
+
+/// Helper structs for constructing netlink attributes. AttrString holds a
+/// string (e.g. an interface name), which may or may not be null-terminated.
+template <uint16_t ATTR_TYPE> struct AttrString {
+ cpp::string_view value;
+ bool null_terminate = true;
+ size_t payload_len() const { return value.size() + (null_terminate ? 1 : 0); }
+ void write(uint8_t *dest) const {
+ inline_memcpy(dest, value.data(), value.size());
+ if (null_terminate)
+ dest[value.size()] = '\0';
+ }
+ static constexpr uint16_t TYPE = ATTR_TYPE;
+};
+
+template <uint16_t ATTR_TYPE> struct AttrInt {
+ unsigned int value;
+ size_t payload_len() const { return sizeof(unsigned int); }
+ void write(uint8_t *dest) const {
+ inline_memcpy(dest, &value, sizeof(unsigned int));
+ }
+ static constexpr uint16_t TYPE = ATTR_TYPE;
+};
+
+/// Writes a netlink message of the given type, consisting of the fixed-size
+/// header (e.g. struct ifinfomsg) followed by the attributes, into the buffer.
+/// Returns the length of the message.
+template <typename Header, typename... Attrs>
+LIBC_INLINE size_t build_nlmsg_packet(uint8_t *buf, uint16_t type,
+ const Header &hdr,
+ const Attrs &...attrs) {
+ size_t total_len = NLMSG_SPACE(sizeof(Header)) +
+ (0 + ... + RTA_ALIGN(RTA_LENGTH(attrs.payload_len())));
+
+ inline_memset(buf, 0, total_len);
+
+ struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
+ nh->nlmsg_len = static_cast<uint32_t>(total_len);
+ nh->nlmsg_type = type;
+ inline_memcpy(NLMSG_DATA(nh), &hdr, sizeof(Header));
+
+ uint8_t *attr_ptr = buf + NLMSG_SPACE(sizeof(Header));
+
+ auto write_attr = [&attr_ptr](const auto &attr) {
+ size_t rta_len = RTA_LENGTH(attr.payload_len());
+ struct rtattr *rta = reinterpret_cast<struct rtattr *>(attr_ptr);
+ rta->rta_len = static_cast<unsigned short>(rta_len);
+ rta->rta_type = attr.TYPE;
+ attr.write(reinterpret_cast<uint8_t *>(RTA_DATA(rta)));
+ attr_ptr += RTA_ALIGN(rta_len);
+ };
+
+ if constexpr (sizeof...(Attrs) > 0)
+ (..., write_attr(attrs));
+
+ return total_len;
+}
+
+LIBC_INLINE size_t build_nlmsg_done_packet(uint8_t *buf, int errcode = 0) {
+ size_t total_len = NLMSG_LENGTH(sizeof(int));
+ inline_memset(buf, 0, total_len);
+ struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
+ nh->nlmsg_len = static_cast<uint32_t>(total_len);
+ nh->nlmsg_type = NLMSG_DONE;
+ *reinterpret_cast<int *>(NLMSG_DATA(nh)) = errcode;
+ return total_len;
+}
+
+LIBC_INLINE size_t build_nlmsg_error_packet(uint8_t *buf, int errcode) {
+ size_t total_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
+ inline_memset(buf, 0, total_len);
+ struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
+ nh->nlmsg_len = static_cast<uint32_t>(total_len);
+ nh->nlmsg_type = NLMSG_ERROR;
+ struct nlmsgerr *err = reinterpret_cast<struct nlmsgerr *>(NLMSG_DATA(nh));
+ err->error = errcode;
+ return total_len;
+}
+
+LIBC_INLINE size_t build_generic_nlmsg_packet(uint8_t *buf, uint16_t type) {
+ size_t total_len = NLMSG_LENGTH(0);
+ inline_memset(buf, 0, total_len);
+ struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
+ nh->nlmsg_len = static_cast<uint32_t>(total_len);
+ nh->nlmsg_type = type;
+ return total_len;
+}
+
+/// Marks the packet in the buffer the way the kernel does when the dump was
+/// interrupted by a change to the data.
+LIBC_INLINE void mark_interrupted(uint8_t *buf) {
+ reinterpret_cast<struct nlmsghdr *>(buf)->nlmsg_flags |= NLM_F_DUMP_INTR;
+}
+
+} // namespace testing
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_TEST_SRC___SUPPORT_NET_LINUX_NETLINK_TEST_SUPPORT_H
diff --git a/libc/test/src/net/if/linux/CMakeLists.txt b/libc/test/src/net/if/linux/CMakeLists.txt
index 8d57838bbb0ae..e13cfff68be4b 100644
--- a/libc/test/src/net/if/linux/CMakeLists.txt
+++ b/libc/test/src/net/if/linux/CMakeLists.txt
@@ -33,20 +33,15 @@ add_libc_test(
DEPENDS
libc.hdr.errno_macros
libc.hdr.net_if_macros
- libc.hdr.types.socklen_t
- libc.hdr.types.ssize_t
libc.hdr.types.struct_if_nameindex
- libc.src.__support.CPP.optional
libc.src.__support.CPP.span
- libc.src.__support.CPP.string
libc.src.__support.CPP.string_view
libc.src.__support.CPP.tuple
libc.src.__support.error_or
- libc.src.__support.fixedvector
+ libc.src.__support.net.linux.netlink
libc.src.net.if.if_freenameindex
libc.src.net.if.if_nameindex
libc.src.net.if.linux.if_nameindex_impl
- libc.src.string.memory_utils.inline_memcpy
- libc.src.string.memory_utils.inline_memset
+ libc.test.src.__support.net.linux.netlink_test_support
libc.test.UnitTest.ErrnoCheckingTest
)
diff --git a/libc/test/src/net/if/linux/if_nameindex_test.cpp b/libc/test/src/net/if/linux/if_nameindex_test.cpp
index 647b433fe5cc6..f6afa2e1432f7 100644
--- a/libc/test/src/net/if/linux/if_nameindex_test.cpp
+++ b/libc/test/src/net/if/linux/if_nameindex_test.cpp
@@ -13,108 +13,45 @@
#include "hdr/errno_macros.h"
#include "hdr/net_if_macros.h"
-#include "hdr/types/socklen_t.h"
-#include "hdr/types/ssize_t.h"
#include "hdr/types/struct_if_nameindex.h"
-#include "src/__support/CPP/optional.h"
#include "src/__support/CPP/span.h"
-#include "src/__support/CPP/string.h"
#include "src/__support/CPP/string_view.h"
#include "src/__support/CPP/tuple.h"
#include "src/__support/error_or.h"
-#include "src/__support/fixedvector.h"
+#include "src/__support/net/linux/netlink.h"
#include "src/net/if/if_freenameindex.h"
#include "src/net/if/if_nameindex.h"
#include "src/net/if/linux/if_nameindex_impl.h"
-#include "src/string/memory_utils/inline_memcpy.h"
-#include "src/string/memory_utils/inline_memset.h"
#include "test/UnitTest/ErrnoCheckingTest.h"
#include "test/UnitTest/Test.h"
+#include "test/src/__support/net/linux/netlink_test_support.h"
+#include <linux/if_link.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
using LIBC_NAMESPACE::Error;
-using LIBC_NAMESPACE::ErrorOr;
-using LIBC_NAMESPACE::FixedVector;
using LIBC_NAMESPACE::cpp::get;
-using LIBC_NAMESPACE::cpp::nullopt;
-using LIBC_NAMESPACE::cpp::optional;
using LIBC_NAMESPACE::cpp::span;
-using LIBC_NAMESPACE::cpp::string;
-using LIBC_NAMESPACE::cpp::string_view;
-using LIBC_NAMESPACE::cpp::tuple;
-using LIBC_NAMESPACE::net::detail::MAX_DUMP_ATTEMPTS;
-using LIBC_NAMESPACE::net::detail::NLMSG_BUFFER_SIZE;
-using LIBC_NAMESPACE::net::detail::NLMSG_LARGE_BUFFER_SIZE;
-
-template <typename T, size_t CAPACITY>
-static optional<T> pop_front(FixedVector<T, CAPACITY> &vec) {
- if (vec.empty())
- return nullopt;
- // TODO: Add front() and erase() to FixedVector, then clean this up.
- T first = vec[0];
- for (size_t i = 1; i < vec.size(); ++i)
- vec[i - 1] = vec[i];
- vec.pop_back();
- return first;
-}
+using LIBC_NAMESPACE::net::MAX_DUMP_ATTEMPTS;
+using LIBC_NAMESPACE::testing::AttrInt;
+using LIBC_NAMESPACE::testing::AttrString;
+using LIBC_NAMESPACE::testing::build_generic_nlmsg_packet;
+using LIBC_NAMESPACE::testing::build_nlmsg_done_packet;
+using LIBC_NAMESPACE::testing::build_nlmsg_error_packet;
+using LIBC_NAMESPACE::testing::build_nlmsg_packet;
+using LIBC_NAMESPACE::testing::FakeNetworkSyscallPolicy;
+using LIBC_NAMESPACE::testing::FakeNetworkSyscallPolicyData;
+using LIBC_NAMESPACE::testing::mark_interrupted;
namespace {
-struct FakeNetworkSyscallPolicyData {
- FixedVector<tuple<int, int, int>, 10> socket_calls;
- FixedVector<ErrorOr<int>, 10> socket_results;
- FixedVector<tuple<int, size_t, int>, 10> sendto_calls;
- FixedVector<ErrorOr<ssize_t>, 10> sendto_results;
- // TODO: Move this into sendto_calls when FixedVector and tuple support
- // non-trivial types.
- string sendto_data;
- FixedVector<int, 10> close_calls;
- FixedVector<ErrorOr<int>, 10> close_results;
- FixedVector<tuple<int, size_t, int>, 10> recv_calls;
- // TODO: Make this ErrorOr<string> when ErrorOr and FixedVector support
- // non-trivial types.
- FixedVector<ErrorOr<span<const uint8_t>>, 10> recv_results;
-};
-
-template <FakeNetworkSyscallPolicyData *DATA> struct FakeNetworkSyscallPolicy {
- static ErrorOr<int> socket(int domain, int type, int protocol) {
- DATA->socket_calls.push_back(tuple<int, int, int>(domain, type, protocol));
- return pop_front(DATA->socket_results).value_or(Error(ENFILE));
- }
-
- static ErrorOr<ssize_t> sendto(int fd, const void *buf, size_t len, int flags,
- const struct sockaddr *, socklen_t) {
- DATA->sendto_calls.push_back(tuple<int, size_t, int>(fd, len, flags));
- DATA->sendto_data += string_view(static_cast<const char *>(buf), len);
- return pop_front(DATA->sendto_results).value_or(static_cast<ssize_t>(len));
- }
-
- static ErrorOr<ssize_t> recvfrom(int fd, void *buf, size_t len, int flags,
- struct sockaddr *, socklen_t *) {
- DATA->recv_calls.push_back(tuple<int, size_t, int>(fd, len, flags));
- ErrorOr<span<const uint8_t>> chunk =
- pop_front(DATA->recv_results).value_or(span<const uint8_t>());
- if (!chunk.has_value())
- return Error(chunk.error());
- if (chunk->size() > len)
- return Error(EINVAL);
- LIBC_NAMESPACE::inline_memcpy(buf, chunk->data(), chunk->size());
- return static_cast<ssize_t>(chunk->size());
- }
-
- static ErrorOr<int> close(int fd) {
- DATA->close_calls.push_back(fd);
- return pop_front(DATA->close_results).value_or(0);
- }
-};
-
struct LlvmLibcIfNameIndexTest
: public LIBC_NAMESPACE::testing::ErrnoCheckingTest {
static constexpr int FAKE_SOCKET = 47;
static FakeNetworkSyscallPolicyData policy_data;
using Policy = FakeNetworkSyscallPolicy<&policy_data>;
+ using Socket = LIBC_NAMESPACE::net::NetlinkSocket<Policy>;
void SetUp() override {
ErrnoCheckingTest::SetUp();
@@ -160,31 +97,9 @@ struct LlvmLibcIfNameIndexSocketTest : public LlvmLibcIfNameIndexTest {
}
};
-/// A helper struct used to construct netlink messages. Name is the attribute
-/// we're most interested in.
-struct AttrName {
- string_view name;
- bool null_terminate = true;
- size_t payload_len() const { return name.size() + (null_terminate ? 1 : 0); }
- void write(uint8_t *dest) const {
- LIBC_NAMESPACE::inline_memcpy(dest, name.data(), name.size());
- if (null_terminate)
- dest[name.size()] = '\0';
- }
- static constexpr uint16_t TYPE = IFLA_IFNAME;
-};
-
-/// A helper struct used to construct netlink messages with integer attributes.
-/// The attributes themselves are not important. We're just testing that we can
-/// skip over them correctly.
-template <uint16_t ATTR_TYPE> struct AttrInt {
- unsigned int value;
- size_t payload_len() const { return sizeof(unsigned int); }
- void write(uint8_t *dest) const {
- LIBC_NAMESPACE::inline_memcpy(dest, &value, sizeof(unsigned int));
- }
- static constexpr uint16_t TYPE = ATTR_TYPE;
-};
+/// Name is the attribute we're most interested in. The others are not
+/// important. We're just testing that we can skip over them correctly.
+using AttrName = AttrString<IFLA_IFNAME>;
using AttrMtu = AttrInt<IFLA_MTU>;
using AttrTxqlen = AttrInt<IFLA_TXQLEN>;
@@ -195,70 +110,10 @@ FakeNetworkSyscallPolicyData LlvmLibcIfNameIndexTest::policy_data;
template <typename... Attrs>
static size_t build_ifinfomsg_packet(uint8_t *buf, unsigned int index,
const Attrs &...attrs) {
- size_t total_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)) +
- (0 + ... + RTA_ALIGN(RTA_LENGTH(attrs.payload_len())));
-
- LIBC_NAMESPACE::inline_memset(buf, 0, total_len);
-
- struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
- nh->nlmsg_len = static_cast<uint32_t>(total_len);
- nh->nlmsg_type = RTM_NEWLINK;
-
- struct ifinfomsg *ifm = reinterpret_cast<struct ifinfomsg *>(NLMSG_DATA(nh));
- ifm->ifi_family = AF_UNSPEC;
- ifm->ifi_index = static_cast<int>(index);
-
- uint8_t *attr_ptr = reinterpret_cast<uint8_t *>(IFLA_RTA(ifm));
-
- auto write_attr = [&attr_ptr](const auto &attr) {
- size_t rta_len = RTA_LENGTH(attr.payload_len());
- struct rtattr *rta = reinterpret_cast<struct rtattr *>(attr_ptr);
- rta->rta_len = static_cast<unsigned short>(rta_len);
- rta->rta_type = attr.TYPE;
- attr.write(reinterpret_cast<uint8_t *>(RTA_DATA(rta)));
- attr_ptr += RTA_ALIGN(rta_len);
- };
-
- if constexpr (sizeof...(Attrs) > 0)
- (..., write_attr(attrs));
-
- return total_len;
-}
-
-static size_t build_nlmsg_done_packet(uint8_t *buf, int errcode = 0) {
- size_t total_len = NLMSG_LENGTH(sizeof(int));
- LIBC_NAMESPACE::inline_memset(buf, 0, total_len);
- struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
- nh->nlmsg_len = static_cast<uint32_t>(total_len);
- nh->nlmsg_type = NLMSG_DONE;
- *reinterpret_cast<int *>(NLMSG_DATA(nh)) = errcode;
- return total_len;
-}
-
-static size_t build_nlmsg_error_packet(uint8_t *buf, int errcode) {
- size_t total_len = NLMSG_LENGTH(sizeof(struct nlmsgerr));
- LIBC_NAMESPACE::inline_memset(buf, 0, total_len);
- struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
- nh->nlmsg_len = static_cast<uint32_t>(total_len);
- nh->nlmsg_type = NLMSG_ERROR;
- struct nlmsgerr *err = reinterpret_cast<struct nlmsgerr *>(NLMSG_DATA(nh));
- err->error = errcode;
- return total_len;
-}
-
-static size_t build_generic_nlmsg_packet(uint8_t *buf, uint16_t type) {
- size_t total_len = NLMSG_LENGTH(0);
- LIBC_NAMESPACE::inline_memset(buf, 0, total_len);
- struct nlmsghdr *nh = reinterpret_cast<struct nlmsghdr *>(buf);
- nh->nlmsg_len = static_cast<uint32_t>(total_len);
- nh->nlmsg_type = type;
- return total_len;
-}
-
-/// Marks the packet in the buffer the way the kernel does when the dump was
-/// interrupted by a change to the interface list.
-static void mark_interrupted(uint8_t *buf) {
- reinterpret_cast<struct nlmsghdr *>(buf)->nlmsg_flags |= NLM_F_DUMP_INTR;
+ struct ifinfomsg ifm = {};
+ ifm.ifi_family = AF_UNSPEC;
+ ifm.ifi_index = static_cast<int>(index);
+ return build_nlmsg_packet(buf, RTM_NEWLINK, ifm, attrs...);
}
TEST_F(LlvmLibcIfNameIndexTest, SocketCreationFailure) {
@@ -434,9 +289,9 @@ TEST_F(LlvmLibcIfNameIndexSocketTest, InterruptedDump) {
// The second attempt uses a larger buffer.
ASSERT_EQ(policy_data.recv_calls.size(), size_t(3));
- ASSERT_EQ(get<1>(policy_data.recv_calls[0]), NLMSG_BUFFER_SIZE);
- ASSERT_EQ(get<1>(policy_data.recv_calls[1]), NLMSG_BUFFER_SIZE);
- ASSERT_EQ(get<1>(policy_data.recv_calls[2]), NLMSG_LARGE_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[0]), Socket::NLMSG_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[1]), Socket::NLMSG_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[2]), Socket::NLMSG_LARGE_BUFFER_SIZE);
LIBC_NAMESPACE::if_freenameindex(list);
}
@@ -480,9 +335,10 @@ TEST_F(LlvmLibcIfNameIndexSocketTest, InterruptedDumpUnflaggedDone) {
// Both datagrams of the second attempt are received into the larger buffer.
ASSERT_EQ(policy_data.recv_calls.size(), size_t(5));
for (size_t i = 0; i < 3; ++i)
- ASSERT_EQ(get<1>(policy_data.recv_calls[i]), NLMSG_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[i]), Socket::NLMSG_BUFFER_SIZE);
for (size_t i = 3; i < 5; ++i)
- ASSERT_EQ(get<1>(policy_data.recv_calls[i]), NLMSG_LARGE_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[i]),
+ Socket::NLMSG_LARGE_BUFFER_SIZE);
LIBC_NAMESPACE::if_freenameindex(list);
}
@@ -533,9 +389,10 @@ TEST_F(LlvmLibcIfNameIndexSocketTest, TooManyInterruptions) {
// We switch to the larger buffer after the first attempt and keep using it.
ASSERT_EQ(policy_data.recv_calls.size(), MAX_DUMP_ATTEMPTS);
- ASSERT_EQ(get<1>(policy_data.recv_calls[0]), NLMSG_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[0]), Socket::NLMSG_BUFFER_SIZE);
for (size_t i = 1; i < MAX_DUMP_ATTEMPTS; ++i)
- ASSERT_EQ(get<1>(policy_data.recv_calls[i]), NLMSG_LARGE_BUFFER_SIZE);
+ ASSERT_EQ(get<1>(policy_data.recv_calls[i]),
+ Socket::NLMSG_LARGE_BUFFER_SIZE);
}
TEST_F(LlvmLibcIfNameIndexSocketTest, RecvFailure) {
More information about the libc-commits
mailing list