Skip to main content

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