smoltcp-rs / smoltcp

a smol tcp/ip stack
BSD Zero Clause License
3.63k stars 402 forks source link

feature request: impl AsFd for {RawSocket, TunTapInterface} #916

Open kennytm opened 2 months ago

kennytm commented 2 months ago

I/O Safety (rust-lang/rfcs#3128, rust-lang/rust#87074) was introduced in Rust 1.63 which associated lifetime to file descriptors.

Some packages, in particular smol, only accepted the I/O-safety-based types instead of RawFd-based types.

While it is possible to convert a RawFd to the I/O-safe counterparts via the unsafe functions BorrowedFd::borrow_raw and OwnedFd::from_raw_fd, it is better if the unsafe operation can be hidden from the library user.

As of 0.11, only the following public types implemented AsRawFd:

Note that if we do impl AsFd for TunTapInterface, TunTapInterface::from_fd will need to be turned into an unsafe fn or accept an OwnedFd to avoid constructing a BorrowedFd from -1.

// this breaks the invariant that BorrowedFd != -1 without invoking unsafe
let device = TunTapInterface::from_fd(-1, Medium::Ip, 1400)?;
let fd = device.as_fd();