std/os/windows/io/
socket.rs

1//! Owned and borrowed OS sockets.
2
3#![stable(feature = "io_safety", since = "1.63.0")]
4
5use super::raw::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
6use crate::marker::PhantomData;
7use crate::mem::{self, ManuallyDrop};
8#[cfg(not(target_vendor = "uwp"))]
9use crate::sys::cvt;
10use crate::{fmt, io, sys};
11
12// The max here is -2, in two's complement. -1 is `INVALID_SOCKET`.
13type ValidRawSocket = core::num::niche_types::NotAllOnes<RawSocket>;
14
15/// A borrowed socket.
16///
17/// This has a lifetime parameter to tie it to the lifetime of something that
18/// owns the socket.
19///
20/// This uses `repr(transparent)` and has the representation of a host socket,
21/// so it can be used in FFI in places where a socket is passed as an argument,
22/// it is not captured or consumed, and it never has the value
23/// `INVALID_SOCKET`.
24///
25/// This type's `.to_owned()` implementation returns another `BorrowedSocket`
26/// rather than an `OwnedSocket`. It just makes a trivial copy of the raw
27/// socket, which is then borrowed under the same lifetime.
28#[derive(Copy, Clone)]
29#[repr(transparent)]
30#[rustc_nonnull_optimization_guaranteed]
31#[stable(feature = "io_safety", since = "1.63.0")]
32pub struct BorrowedSocket<'socket> {
33    socket: ValidRawSocket,
34    _phantom: PhantomData<&'socket OwnedSocket>,
35}
36
37/// An owned socket.
38///
39/// This closes the socket on drop.
40///
41/// This uses `repr(transparent)` and has the representation of a host socket,
42/// so it can be used in FFI in places where a socket is passed as a consumed
43/// argument or returned as an owned value, and it never has the value
44/// `INVALID_SOCKET`.
45#[repr(transparent)]
46#[rustc_nonnull_optimization_guaranteed]
47#[stable(feature = "io_safety", since = "1.63.0")]
48pub struct OwnedSocket {
49    socket: ValidRawSocket,
50}
51
52impl BorrowedSocket<'_> {
53    /// Returns a `BorrowedSocket` holding the given raw socket.
54    ///
55    /// # Safety
56    ///
57    /// The resource pointed to by `raw` must remain open for the duration of
58    /// the returned `BorrowedSocket`, and it must not have the value
59    /// `INVALID_SOCKET`.
60    #[inline]
61    #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
62    #[stable(feature = "io_safety", since = "1.63.0")]
63    pub const unsafe fn borrow_raw(socket: RawSocket) -> Self {
64        assert!(socket != sys::c::INVALID_SOCKET as RawSocket);
65        let socket = unsafe { ValidRawSocket::new_unchecked(socket) };
66        Self { socket, _phantom: PhantomData }
67    }
68}
69
70impl OwnedSocket {
71    /// Creates a new `OwnedSocket` instance that shares the same underlying
72    /// object as the existing `OwnedSocket` instance.
73    #[stable(feature = "io_safety", since = "1.63.0")]
74    pub fn try_clone(&self) -> io::Result<Self> {
75        self.as_socket().try_clone_to_owned()
76    }
77
78    // FIXME(strict_provenance_magic): we defined RawSocket to be a u64 ;-;
79    #[allow(fuzzy_provenance_casts)]
80    #[cfg(not(target_vendor = "uwp"))]
81    pub(crate) fn set_no_inherit(&self) -> io::Result<()> {
82        cvt(unsafe {
83            sys::c::SetHandleInformation(
84                self.as_raw_socket() as sys::c::HANDLE,
85                sys::c::HANDLE_FLAG_INHERIT,
86                0,
87            )
88        })
89        .map(drop)
90    }
91
92    #[cfg(target_vendor = "uwp")]
93    pub(crate) fn set_no_inherit(&self) -> io::Result<()> {
94        Err(io::const_error!(io::ErrorKind::Unsupported, "Unavailable on UWP"))
95    }
96}
97
98impl BorrowedSocket<'_> {
99    /// Creates a new `OwnedSocket` instance that shares the same underlying
100    /// object as the existing `BorrowedSocket` instance.
101    #[stable(feature = "io_safety", since = "1.63.0")]
102    pub fn try_clone_to_owned(&self) -> io::Result<OwnedSocket> {
103        let mut info = unsafe { mem::zeroed::<sys::c::WSAPROTOCOL_INFOW>() };
104        let result = unsafe {
105            sys::c::WSADuplicateSocketW(
106                self.as_raw_socket() as sys::c::SOCKET,
107                sys::c::GetCurrentProcessId(),
108                &mut info,
109            )
110        };
111        sys::net::cvt(result)?;
112        let socket = unsafe {
113            sys::c::WSASocketW(
114                info.iAddressFamily,
115                info.iSocketType,
116                info.iProtocol,
117                &info,
118                0,
119                sys::c::WSA_FLAG_OVERLAPPED | sys::c::WSA_FLAG_NO_HANDLE_INHERIT,
120            )
121        };
122
123        if socket != sys::c::INVALID_SOCKET {
124            unsafe { Ok(OwnedSocket::from_raw_socket(socket as RawSocket)) }
125        } else {
126            let error = unsafe { sys::c::WSAGetLastError() };
127
128            if error != sys::c::WSAEPROTOTYPE && error != sys::c::WSAEINVAL {
129                return Err(io::Error::from_raw_os_error(error));
130            }
131
132            let socket = unsafe {
133                sys::c::WSASocketW(
134                    info.iAddressFamily,
135                    info.iSocketType,
136                    info.iProtocol,
137                    &info,
138                    0,
139                    sys::c::WSA_FLAG_OVERLAPPED,
140                )
141            };
142
143            if socket == sys::c::INVALID_SOCKET {
144                return Err(last_error());
145            }
146
147            unsafe {
148                let socket = OwnedSocket::from_raw_socket(socket as RawSocket);
149                socket.set_no_inherit()?;
150                Ok(socket)
151            }
152        }
153    }
154}
155
156/// Returns the last error from the Windows socket interface.
157fn last_error() -> io::Error {
158    io::Error::from_raw_os_error(unsafe { sys::c::WSAGetLastError() })
159}
160
161#[stable(feature = "io_safety", since = "1.63.0")]
162impl AsRawSocket for BorrowedSocket<'_> {
163    #[inline]
164    fn as_raw_socket(&self) -> RawSocket {
165        self.socket.as_inner()
166    }
167}
168
169#[stable(feature = "io_safety", since = "1.63.0")]
170impl AsRawSocket for OwnedSocket {
171    #[inline]
172    fn as_raw_socket(&self) -> RawSocket {
173        self.socket.as_inner()
174    }
175}
176
177#[stable(feature = "io_safety", since = "1.63.0")]
178impl IntoRawSocket for OwnedSocket {
179    #[inline]
180    fn into_raw_socket(self) -> RawSocket {
181        ManuallyDrop::new(self).socket.as_inner()
182    }
183}
184
185#[stable(feature = "io_safety", since = "1.63.0")]
186impl FromRawSocket for OwnedSocket {
187    #[inline]
188    unsafe fn from_raw_socket(socket: RawSocket) -> Self {
189        debug_assert_ne!(socket, sys::c::INVALID_SOCKET as RawSocket);
190        let socket = unsafe { ValidRawSocket::new_unchecked(socket) };
191        Self { socket }
192    }
193}
194
195#[stable(feature = "io_safety", since = "1.63.0")]
196impl Drop for OwnedSocket {
197    #[inline]
198    fn drop(&mut self) {
199        unsafe {
200            let _ = sys::c::closesocket(self.socket.as_inner() as sys::c::SOCKET);
201        }
202    }
203}
204
205#[stable(feature = "io_safety", since = "1.63.0")]
206impl fmt::Debug for BorrowedSocket<'_> {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.debug_struct("BorrowedSocket").field("socket", &self.socket).finish()
209    }
210}
211
212#[stable(feature = "io_safety", since = "1.63.0")]
213impl fmt::Debug for OwnedSocket {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        f.debug_struct("OwnedSocket").field("socket", &self.socket).finish()
216    }
217}
218
219/// A trait to borrow the socket from an underlying object.
220#[stable(feature = "io_safety", since = "1.63.0")]
221pub trait AsSocket {
222    /// Borrows the socket.
223    #[stable(feature = "io_safety", since = "1.63.0")]
224    fn as_socket(&self) -> BorrowedSocket<'_>;
225}
226
227#[stable(feature = "io_safety", since = "1.63.0")]
228impl<T: AsSocket> AsSocket for &T {
229    #[inline]
230    fn as_socket(&self) -> BorrowedSocket<'_> {
231        T::as_socket(self)
232    }
233}
234
235#[stable(feature = "io_safety", since = "1.63.0")]
236impl<T: AsSocket> AsSocket for &mut T {
237    #[inline]
238    fn as_socket(&self) -> BorrowedSocket<'_> {
239        T::as_socket(self)
240    }
241}
242
243#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
244/// This impl allows implementing traits that require `AsSocket` on Arc.
245/// ```
246/// # #[cfg(windows)] mod group_cfg {
247/// # use std::os::windows::io::AsSocket;
248/// use std::net::UdpSocket;
249/// use std::sync::Arc;
250///
251/// trait MyTrait: AsSocket {}
252/// impl MyTrait for Arc<UdpSocket> {}
253/// impl MyTrait for Box<UdpSocket> {}
254/// # }
255/// ```
256impl<T: AsSocket> AsSocket for crate::sync::Arc<T> {
257    #[inline]
258    fn as_socket(&self) -> BorrowedSocket<'_> {
259        (**self).as_socket()
260    }
261}
262
263#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
264impl<T: AsSocket> AsSocket for crate::rc::Rc<T> {
265    #[inline]
266    fn as_socket(&self) -> BorrowedSocket<'_> {
267        (**self).as_socket()
268    }
269}
270
271#[unstable(feature = "unique_rc_arc", issue = "112566")]
272impl<T: AsSocket + ?Sized> AsSocket for crate::rc::UniqueRc<T> {
273    #[inline]
274    fn as_socket(&self) -> BorrowedSocket<'_> {
275        (**self).as_socket()
276    }
277}
278
279#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
280impl<T: AsSocket> AsSocket for Box<T> {
281    #[inline]
282    fn as_socket(&self) -> BorrowedSocket<'_> {
283        (**self).as_socket()
284    }
285}
286
287#[stable(feature = "io_safety", since = "1.63.0")]
288impl AsSocket for BorrowedSocket<'_> {
289    #[inline]
290    fn as_socket(&self) -> BorrowedSocket<'_> {
291        *self
292    }
293}
294
295#[stable(feature = "io_safety", since = "1.63.0")]
296impl AsSocket for OwnedSocket {
297    #[inline]
298    fn as_socket(&self) -> BorrowedSocket<'_> {
299        // Safety: `OwnedSocket` and `BorrowedSocket` have the same validity
300        // invariants, and the `BorrowedSocket` is bounded by the lifetime
301        // of `&self`.
302        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
303    }
304}
305
306#[stable(feature = "io_safety", since = "1.63.0")]
307impl AsSocket for crate::net::TcpStream {
308    #[inline]
309    fn as_socket(&self) -> BorrowedSocket<'_> {
310        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
311    }
312}
313
314#[stable(feature = "io_safety", since = "1.63.0")]
315impl From<crate::net::TcpStream> for OwnedSocket {
316    /// Takes ownership of a [`TcpStream`](crate::net::TcpStream)'s socket.
317    #[inline]
318    fn from(tcp_stream: crate::net::TcpStream) -> OwnedSocket {
319        unsafe { OwnedSocket::from_raw_socket(tcp_stream.into_raw_socket()) }
320    }
321}
322
323#[stable(feature = "io_safety", since = "1.63.0")]
324impl From<OwnedSocket> for crate::net::TcpStream {
325    #[inline]
326    fn from(owned: OwnedSocket) -> Self {
327        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
328    }
329}
330
331#[stable(feature = "io_safety", since = "1.63.0")]
332impl AsSocket for crate::net::TcpListener {
333    #[inline]
334    fn as_socket(&self) -> BorrowedSocket<'_> {
335        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
336    }
337}
338
339#[stable(feature = "io_safety", since = "1.63.0")]
340impl From<crate::net::TcpListener> for OwnedSocket {
341    /// Takes ownership of a [`TcpListener`](crate::net::TcpListener)'s socket.
342    #[inline]
343    fn from(tcp_listener: crate::net::TcpListener) -> OwnedSocket {
344        unsafe { OwnedSocket::from_raw_socket(tcp_listener.into_raw_socket()) }
345    }
346}
347
348#[stable(feature = "io_safety", since = "1.63.0")]
349impl From<OwnedSocket> for crate::net::TcpListener {
350    #[inline]
351    fn from(owned: OwnedSocket) -> Self {
352        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
353    }
354}
355
356#[stable(feature = "io_safety", since = "1.63.0")]
357impl AsSocket for crate::net::UdpSocket {
358    #[inline]
359    fn as_socket(&self) -> BorrowedSocket<'_> {
360        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
361    }
362}
363
364#[stable(feature = "io_safety", since = "1.63.0")]
365impl From<crate::net::UdpSocket> for OwnedSocket {
366    /// Takes ownership of a [`UdpSocket`](crate::net::UdpSocket)'s underlying socket.
367    #[inline]
368    fn from(udp_socket: crate::net::UdpSocket) -> OwnedSocket {
369        unsafe { OwnedSocket::from_raw_socket(udp_socket.into_raw_socket()) }
370    }
371}
372
373#[stable(feature = "io_safety", since = "1.63.0")]
374impl From<OwnedSocket> for crate::net::UdpSocket {
375    #[inline]
376    fn from(owned: OwnedSocket) -> Self {
377        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
378    }
379}