1use std::fmt;
2use std::marker::PhantomData;
3use std::mem::ManuallyDrop;
4use std::ops::Deref;
5#[cfg(unix)]
6use std::os::unix::io::{AsRawFd, FromRawFd};
7#[cfg(windows)]
8use std::os::windows::io::{AsRawSocket, FromRawSocket};
9
10use crate::Socket;
11
12/// A reference to a [`Socket`] that can be used to configure socket types other
13/// than the `Socket` type itself.
14///
15/// This allows for example a [`TcpStream`], found in the standard library, to
16/// be configured using all the additional methods found in the [`Socket`] API.
17///
18/// `SockRef` can be created from any socket type that implements [`AsRawFd`]
19/// (Unix) or [`AsRawSocket`] (Windows) using the [`From`] implementation, but
20/// the caller must ensure the file descriptor/socket is a valid.
21///
22/// [`TcpStream`]: std::net::TcpStream
23// Don't use intra-doc links because they won't build on every platform.
24/// [`AsRawFd`]: https://doc.rust-lang.org/stable/std/os/unix/io/trait.AsRawFd.html
25/// [`AsRawSocket`]: https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsRawSocket.html
26///
27/// # Examples
28///
29/// Below is an example of converting a [`TcpStream`] into a [`SockRef`].
30///
31/// ```
32/// use std::net::{TcpStream, SocketAddr};
33///
34/// use socket2::SockRef;
35///
36/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
37/// // Create `TcpStream` from the standard library.
38/// let address: SocketAddr = "127.0.0.1:1234".parse()?;
39/// # let b1 = std::sync::Arc::new(std::sync::Barrier::new(2));
40/// # let b2 = b1.clone();
41/// # let handle = std::thread::spawn(move || {
42/// # let listener = std::net::TcpListener::bind(address).unwrap();
43/// # b2.wait();
44/// # let (stream, _) = listener.accept().unwrap();
45/// # std::thread::sleep(std::time::Duration::from_millis(10));
46/// # drop(stream);
47/// # });
48/// # b1.wait();
49/// let stream = TcpStream::connect(address)?;
50///
51/// // Create a `SockRef`erence to the stream.
52/// let socket_ref = SockRef::from(&stream);
53/// // Use `Socket::set_nodelay` on the stream.
54/// socket_ref.set_nodelay(true)?;
55/// drop(socket_ref);
56///
57/// assert_eq!(stream.nodelay()?, true);
58/// # handle.join().unwrap();
59/// # Ok(())
60/// # }
61/// ```
62///
63/// Below is an example of **incorrect usage** of `SockRef::from`, which is
64/// currently possible (but not intended and will be fixed in future versions).
65///
66/// ```compile_fail
67/// use socket2::SockRef;
68///
69/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
70/// /// THIS USAGE IS NOT VALID!
71/// let socket_ref = SockRef::from(&123);
72/// // The above line is overseen possibility when using `SockRef::from`, it
73/// // uses the `RawFd` (on Unix), which is a type alias for `c_int`/`i32`,
74/// // which implements `AsRawFd`. However it may be clear that this usage is
75/// // invalid as it doesn't guarantee that `123` is a valid file descriptor.
76///
77/// // Using `Socket::set_nodelay` now will call it on a file descriptor we
78/// // don't own! We don't even not if the file descriptor is valid or a socket.
79/// socket_ref.set_nodelay(true)?;
80/// drop(socket_ref);
81/// # Ok(())
82/// # }
83/// # DO_NOT_COMPILE
84/// ```
85pub struct SockRef<'s> {
86 /// Because this is a reference we don't own the `Socket`, however `Socket`
87 /// closes itself when dropped, so we use `ManuallyDrop` to prevent it from
88 /// closing itself.
89 socket: ManuallyDrop<Socket>,
90 /// Because we don't own the socket we need to ensure the socket remains
91 /// open while we have a "reference" to it, the lifetime `'s` ensures this.
92 _lifetime: PhantomData<&'s Socket>,
93}
94
95impl<'s> Deref for SockRef<'s> {
96 type Target = Socket;
97
98 fn deref(&self) -> &Self::Target {
99 &self.socket
100 }
101}
102
103/// On Windows, a corresponding `From<&impl AsRawSocket>` implementation exists.
104#[cfg(unix)]
105#[cfg_attr(docsrs, doc(cfg(unix)))]
106impl<'s, S> From<&'s S> for SockRef<'s>
107where
108 S: AsRawFd,
109{
110 /// The caller must ensure `S` is actually a socket.
111 fn from(socket: &'s S) -> Self {
112 let fd: i32 = socket.as_raw_fd();
113 assert!(fd >= 0);
114 SockRef {
115 socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(fd) }),
116 _lifetime: PhantomData,
117 }
118 }
119}
120
121/// On Unix, a corresponding `From<&impl AsRawFd>` implementation exists.
122#[cfg(windows)]
123#[cfg_attr(docsrs, doc(cfg(windows)))]
124impl<'s, S> From<&'s S> for SockRef<'s>
125where
126 S: AsRawSocket,
127{
128 /// See the `From<&impl AsRawFd>` implementation.
129 fn from(socket: &'s S) -> Self {
130 let socket = socket.as_raw_socket();
131 assert!(socket != winapi::um::winsock2::INVALID_SOCKET as _);
132 SockRef {
133 socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket) }),
134 _lifetime: PhantomData,
135 }
136 }
137}
138
139impl fmt::Debug for SockRef<'_> {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f&mut DebugStruct<'_, '_>.debug_struct("SockRef")
142 .field("raw", &self.socket.as_raw())
143 .field("local_addr", &self.socket.local_addr().ok())
144 .field(name:"peer_addr", &self.socket.peer_addr().ok())
145 .finish()
146 }
147}
148