I was using libc FFI crate, I'm transforming i32 -> OwnedFd -> TcpListener and instead of writing from_raw_fd(&fd) I've accidentally used from(fd): (something like this)
let socket: OwnedFd = socket(/* ... */);
let listener = unsafe { std::net::TcpListener::from(socket) };
And I've got unused_unsafe. Looking at the documentation it's Just From<T> implementation.
Why it is implemented? We don't know whether it actually refers to a socket, whether it's a TCP socket, or whether it has been configured correctly for use as a TcpListener.
My question is more about the API design: why From<OwnedFd> is implemented at all? API suggests that conversion is safe for any OwnedFd, even though an arbitrary OwnedFd might not represent a valid TCP listening socket. Seems easy to misuse.
The short answer is that, on Unix-like OSes using file descriptors (FDs), the FD is "just" an integer handle that the OS understands, and if you convert an FD that represents (say) a File to a TcpListener, nothing unsafe happens - you get clean errors when you try and do things that only make sense for a listening TCP socket and not a file.
OwnedFd represents one of the cases where we know it's a valid FD and owned by the caller (so no-one else can be using it right now), so we don't have to worry about the concerns discussed in the I/O safety RFC - the worst possible outcome is that all the operations you try and use on your TcpListener fail with an error.
In contrast, from_raw_rd is potentially dangerous, because a RawFd is literally just an integer, and might not represent a valid FD, or might represent an FD belonging to someone else, or otherwise result in "spooky action at a distance". That's why the unsafe, because you need to ensure that you're not just making up a number and hoping it's accepted as an FD.
I understand that OwnedFd represents valid descriptor and probably (I'm not so smart to think how to do otherwise) you can't enforce that OwnedFd is pointing into the right descriptor (i.e. configured TCP socket), but giving user a safe way to provide random descriptor (even if it's I/O safe and validated by borrow checked) is a weird choice from my perspective.
first, a OwnedFd is not a "random" descriptor, either it is converted from a safe abstraction like File, TcpStream, or it must be created unsafely.
second, rust unsafe is all about memory safety, it's not about other aspect of "safety"/"corrctness" in the code. for example, if a function cannot cause UB in safe code, then it is, by definition, NOT unsafe.
The question is why From<OwnedFd> is implemented if simply not providing it would allow only FromRawFd construction and it will show to the user that operation may lead to runtime error. I'm okay if it's just "because it's ergonomic", but curious if it's not.
It's like that because unsafe is meant to protect you from "spooky action at a distance" bugs, where a bug in your unsafe code can result in otherwise bug-free code misbehaving on inputs that would not normally cause it to misbehave. Memory safety is the big one, and I/O safety is a more recent addition.
from_raw_fd is unsafe because if you convert someone else's FD to an OwnedFd and then close it, there's a sudden failure in the code that owned that FD - but no amount of looking at the code that starts reporting errors and the inputs to that code will explain why it suddenly stopped working, because it's not that code or its inputs at fault, it's code elsewhere in the program
In contrast, if you convert a File to a TcpListener via OwnedFd, there's a clear trail from the code that failed to the root cause of the failure - you will find the TcpListener that you created this way doesn't work, and when you walk through all the possible causes, you will eventually find it being created from an OwnedFd. You then know you need to look into that OwnedFd's origins, and will find the logic error that way.
And it's well-understood that people are better at local reasoning than global reasoning - given that an error is in the code that's reporting a fault, or in inputs to that code, it's easier to find the bug than if the error is in unrelated code that you don't realise is running right now.
I agree with your general complaint, but for me the issue is that the From trait is something I'm accustomed to using without any fear of making a mistake. So for this weird case I think a dedicated method, with doc for this issue, would have been better. But it isn't a huge problem.
It allows approximating the "everything is a file" concept, and exposing functionality that can be applied to any file descriptor. As an example, you can (safely) dupStdout and convert the result to a File in order to write to stdout without Rust's locks and buffers.[1][2]
It'd be nicer if one could do that more directly, but even if the API was just take_fd which returned File instead of OwnedFd, it'd be doing the same dance behind the curtain. ↩︎
I agree on this one. the current design seems a bit off, at least the two-way conversion part.
to me, it feels wrong that OwnedFd can be converted toandfrom those standard library io objects, e.g, we have both OwnedFd: From<TcpLisntener> and TcpListener: From<OwnedFd>, same is true for other strongly typed io objects, such as File, TcpStream, UnixDatagram, PipeReader, etc.
to me, when I have two types given T: From<U> and U: From<T>, I would expect they are isomorphic and are equivalent, the fact they both exist is probably for historical and compatibility reasons. but the case for OwnedFd is apparently different.
in the documentation of the From trait, there's a (counter-)example, where the conversion between i8 and u8 can be lossless (in a roundtrip) using as cast, but they should NOT implement From because the "lossless" doesn't mean they have the same conceptual values, in the sense that, -1i8 and 255u8 are not the same number, despite having the same bit pattern representation.
I think an analogue can be made for OwnedFd, e.g. PipeReader { fd: 3 } and UnixDatagram { fd: 3 } represnt completely different semantic values, despite they have the same descriptor value as OwnedFd { fd: 3 }.
Does it help to think of From<OwnedFd> as a downcast? If you have OwnedFd(3), you know that it's a valid file descriptor. Assuming you have other information that tells you this particular fd is a Unix datagram socket, you can sensibly convert it to UnixDatagram { fd: 3 } and then do datagram-socket-y things with it.
That conversion is considered safe because even if your information is wrong the worst thing that can possibly happen is you try to do something datagram-socket-y and it fails with an ENOTSOCK error return.
Would it maybe be nice for OwnedFd to implement Any with a custom downcast method that asked the kernel whether your impression that this fd was a datagram socket was in fact correct? ... Yeah, actually, that could make a lot of sense, now I type it out like that.
yes, it is in this case. the operation is the From/Into conversion
should a type implement said operation?
this is the question I'm concerning.
personally, I think OwnedFd: From<TcpListener> is ok, analogue to an "upcast"
but TcpListener: From<OwnedFd> is not, analogue to a "downcast"
in theory, a downcast may cause a runtime failure. and platform specific apis exist to determine the type of a descriptor, e.g. fstat() on linux.[1]
yeah, that fits the downcasting analog well.
well, maybe not Any, but I would like TryFrom instead of just From.
I only use linux, but I think it's posix standard? ↩︎
I'm not really into rust history, but I feel like OwnedFd is to share a common Drop implementation for different io handles of the standard library, so I would consider it an "inner" type, an implementation detail in some sense, sort of like the Unique wrapper (removed recently in #164116).
I do think it is good to make such common abstraction public, since it can be useful in many ways. however, I'm not convinced the two-way conversion using From/Into is a good design choice.
sure, it is safe to do, but whether I implement a trait for a type should be decided based on the api semantics, not just because it is safe.
IMO, a dedicated (safe) trait is better than From, e.g. something like FromOwnedFd, in parallel with FromRawFd. it may have checked and unchecked api, and may even have a blanket impl for all T: From<OwnedFd>:
trait FromOwnedFd {
type Error;
fn try_from_owned_fd(fd: OwnedFd) -> Result<Self, Self::Error>;
// default unchecked version calls `unwrap()`, implementors can override
fn from_owned_fd(fd: OwnedFd) -> Self { Self::try_from_owned_fd().unwrap() }
}
impl<T> FromOwnedFd for T where T: From<OwnedFd> {
type Error = Infallible;
//...
}