llvm-project
6fdd1ca6 - [libc] Move the netlink dump code out of if_nameindex (NFC) (#243771)

Commit
2 days ago
[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
Author
Parents
Loading