[libc] Add if_nameindex and if_freenameindex as an experimental entrypoint (#208438)
This is a fairly complex function, so this patch implements bare minimum
needed to demonstrate the overall direction. The functionality is
implemented by communicating with the linux kernel over a netlink
socket, and the complexity comes from parsing the messages. In this
patch, parsing stops at the first interface, and we don't handle
multiple messages or deduplication resulting from restarted dumps.
Some notable implementation choices are:
- using a single allocation (including both the interface vector and the
strings it points to). This makes deallocation fast, reduces heap
fragmentation, and doesn't make the final code much more complex since
we still need auxiliary data structures for deduplication.
- using linux kernel headers for all the netlink structures. I think
this is fine as we're not exposing that to the user.
- while this information is available via /sys, that would mean we
require /sys to be mounted, and it wouldn't make the code much simpler.
This also matches other libc implementations.
Testing is a completely separate story, and the main source of
complexity of this patch. To make the code testable without requiring
root or live interfaces, the core function
(`net::if_nameindex<Policy>()`) is templated on a syscall policy class
(`NetworkSyscallPolicy`). The production entrypoint uses
`DefaultNetworkSyscallPolicy` forwarding directly to syscall wrappers
(`socket`, `sendto`, `recvfrom`, `close`), while the unit tests use
`FakeNetworkSyscallPolicy` to feed crafted netlink buffers from memory
and verify `sendto` request formation.
The fake policy is set up such that one can program the mock to return
certain values, and validate arguments. It does not resemble the
googletest functionality (mocks) very closely, but I've tried to put it
in a form where it is possible to morph it into that -- if that's the
direction we desire to go.
While doing this, I ran into the limitations of various container
classes (mainly the inability to handle non-trivial types). To avoid
growing the scope of this even further, I worked around those
limitations locally, and left TODOs which I intend to resolve in
follow-ups. The only thing I couldn't avoid is the addition of
cpp::expected default constructor (which is actually a consequence of
how FixedVector constructs elements). However, this is a simple addition
and it is consistent with the STL class it is emulating.
The patch also add the [AP]F_NETLINK constants needed for creating
netlink sockets.
GitOrigin-RevId: b2cca30e126db355314677852f2b6139be1c2f3b
22 files changed