1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//! 拥有和借用的操作系统套接字。

#![stable(feature = "io_safety", since = "1.63.0")]

use super::raw::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::mem;
use crate::mem::forget;
use crate::sys;
#[cfg(not(target_vendor = "uwp"))]
use crate::sys::cvt;

/// 借来的套接字。
///
/// 它有一个生命周期参数,将它与拥有套接字的事物的生命周期联系起来。
///
/// 这使用 `repr(transparent)` 并具有主机套接字的表示形式,因此它可以在 FFI 中用于套接字作为参数传递的地方,它不会被捕获或消耗,并且它永远不会有值 `INVALID_SOCKET`。
///
///
/// 这种类型的 `.to_owned()` 实现返回另一个 `BorrowedSocket` 而不是 `OwnedSocket`。它只是简单地复制原始套接字,然后在相同的生命周期下借用。
///
///
///
///
///
#[derive(Copy, Clone)]
#[repr(transparent)]
#[rustc_layout_scalar_valid_range_start(0)]
// 这是 -2,二进制补码。-1 是 `INVALID_SOCKET`。
#[cfg_attr(target_pointer_width = "32", rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
#[cfg_attr(
    target_pointer_width = "64",
    rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FF_FF_FF_FF_FE)
)]
#[rustc_nonnull_optimization_guaranteed]
#[stable(feature = "io_safety", since = "1.63.0")]
pub struct BorrowedSocket<'socket> {
    socket: RawSocket,
    _phantom: PhantomData<&'socket OwnedSocket>,
}

/// 一个拥有所有权的套接字。
///
/// 这将丢弃时关闭套接字。
///
/// 这使用 `repr(transparent)` 并具有主机套接字的表示形式,因此它可以在 FFI 中将套接字作为消耗参数传递或作为拥有值返回的地方使用,并且它永远不会具有值 `INVALID_SOCKET`。
///
///
///
#[repr(transparent)]
#[rustc_layout_scalar_valid_range_start(0)]
// 这是 -2,二进制补码。-1 是 `INVALID_SOCKET`。
#[cfg_attr(target_pointer_width = "32", rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
#[cfg_attr(
    target_pointer_width = "64",
    rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FF_FF_FF_FF_FE)
)]
#[rustc_nonnull_optimization_guaranteed]
#[stable(feature = "io_safety", since = "1.63.0")]
pub struct OwnedSocket {
    socket: RawSocket,
}

impl BorrowedSocket<'_> {
    /// 返回一个包含给定原始套接字的 `BorrowedSocket`。
    ///
    /// # Safety
    ///
    /// `raw` 指向的资源在返回的 `BorrowedSocket` 期间必须保持打开状态,并且它不能具有值 `INVALID_SOCKET`。
    ///
    ///
    #[inline]
    #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
    #[stable(feature = "io_safety", since = "1.63.0")]
    pub const unsafe fn borrow_raw(socket: RawSocket) -> Self {
        assert!(socket != sys::c::INVALID_SOCKET as RawSocket);
        Self { socket, _phantom: PhantomData }
    }
}

impl OwnedSocket {
    /// 创建一个新的 `OwnedSocket` 实例,该实例与现有 `OwnedSocket` 实例共享相同的底层 object。
    ///
    #[stable(feature = "io_safety", since = "1.63.0")]
    pub fn try_clone(&self) -> io::Result<Self> {
        self.as_socket().try_clone_to_owned()
    }

    // FIXME(strict_provenance_magic): 我们将 RawSocket 定义为 u64 ;-;
    #[allow(fuzzy_provenance_casts)]
    #[cfg(not(target_vendor = "uwp"))]
    pub(crate) fn set_no_inherit(&self) -> io::Result<()> {
        cvt(unsafe {
            sys::c::SetHandleInformation(
                self.as_raw_socket() as sys::c::HANDLE,
                sys::c::HANDLE_FLAG_INHERIT,
                0,
            )
        })
        .map(drop)
    }

    #[cfg(target_vendor = "uwp")]
    pub(crate) fn set_no_inherit(&self) -> io::Result<()> {
        Err(io::const_io_error!(io::ErrorKind::Unsupported, "Unavailable on UWP"))
    }
}

impl BorrowedSocket<'_> {
    /// 创建一个新的 `OwnedSocket` 实例,该实例与现有 `BorrowedSocket` 实例共享相同的底层 object。
    ///
    #[stable(feature = "io_safety", since = "1.63.0")]
    pub fn try_clone_to_owned(&self) -> io::Result<OwnedSocket> {
        let mut info = unsafe { mem::zeroed::<sys::c::WSAPROTOCOL_INFOW>() };
        let result = unsafe {
            sys::c::WSADuplicateSocketW(
                self.as_raw_socket(),
                sys::c::GetCurrentProcessId(),
                &mut info,
            )
        };
        sys::net::cvt(result)?;
        let socket = unsafe {
            sys::c::WSASocketW(
                info.iAddressFamily,
                info.iSocketType,
                info.iProtocol,
                &mut info,
                0,
                sys::c::WSA_FLAG_OVERLAPPED | sys::c::WSA_FLAG_NO_HANDLE_INHERIT,
            )
        };

        if socket != sys::c::INVALID_SOCKET {
            unsafe { Ok(OwnedSocket::from_raw_socket(socket)) }
        } else {
            let error = unsafe { sys::c::WSAGetLastError() };

            if error != sys::c::WSAEPROTOTYPE && error != sys::c::WSAEINVAL {
                return Err(io::Error::from_raw_os_error(error));
            }

            let socket = unsafe {
                sys::c::WSASocketW(
                    info.iAddressFamily,
                    info.iSocketType,
                    info.iProtocol,
                    &mut info,
                    0,
                    sys::c::WSA_FLAG_OVERLAPPED,
                )
            };

            if socket == sys::c::INVALID_SOCKET {
                return Err(last_error());
            }

            unsafe {
                let socket = OwnedSocket::from_raw_socket(socket);
                socket.set_no_inherit()?;
                Ok(socket)
            }
        }
    }
}

/// 从 Windows 套接字接口返回最后一个错误。
fn last_error() -> io::Error {
    io::Error::from_raw_os_error(unsafe { sys::c::WSAGetLastError() })
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsRawSocket for BorrowedSocket<'_> {
    #[inline]
    fn as_raw_socket(&self) -> RawSocket {
        self.socket
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsRawSocket for OwnedSocket {
    #[inline]
    fn as_raw_socket(&self) -> RawSocket {
        self.socket
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl IntoRawSocket for OwnedSocket {
    #[inline]
    fn into_raw_socket(self) -> RawSocket {
        let socket = self.socket;
        forget(self);
        socket
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl FromRawSocket for OwnedSocket {
    #[inline]
    unsafe fn from_raw_socket(socket: RawSocket) -> Self {
        debug_assert_ne!(socket, sys::c::INVALID_SOCKET as RawSocket);
        Self { socket }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl Drop for OwnedSocket {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            let _ = sys::c::closesocket(self.socket);
        }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl fmt::Debug for BorrowedSocket<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BorrowedSocket").field("socket", &self.socket).finish()
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl fmt::Debug for OwnedSocket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OwnedSocket").field("socket", &self.socket).finish()
    }
}

/// 从底层对象借用套接字的 trait。
#[stable(feature = "io_safety", since = "1.63.0")]
pub trait AsSocket {
    /// 借用套接字。
    #[stable(feature = "io_safety", since = "1.63.0")]
    fn as_socket(&self) -> BorrowedSocket<'_>;
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl<T: AsSocket> AsSocket for &T {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        T::as_socket(self)
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl<T: AsSocket> AsSocket for &mut T {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        T::as_socket(self)
    }
}

#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
/// 这个 impl 允许在 Arc 上实现需要 `AsSocket` 的 traits。
/// ```
/// # #[cfg(windows)] mod group_cfg {
/// # use std::os::windows::io::AsSocket;
/// use std::net::UdpSocket;
/// use std::sync::Arc;
///
/// trait MyTrait: AsSocket {}
/// impl MyTrait for Arc<UdpSocket> {}
/// impl MyTrait for Box<UdpSocket> {}
/// # }
/// ```
impl<T: AsSocket> AsSocket for crate::sync::Arc<T> {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        (**self).as_socket()
    }
}

#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
impl<T: AsSocket> AsSocket for crate::rc::Rc<T> {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        (**self).as_socket()
    }
}

#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
impl<T: AsSocket> AsSocket for Box<T> {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        (**self).as_socket()
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsSocket for BorrowedSocket<'_> {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        *self
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsSocket for OwnedSocket {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        // 安全性: `OwnedSocket` 和 `BorrowedSocket` 具有相同的有效性不,变体,`BorrowedSocket` 以 `&self` 的生命周期为界。
        //
        //
        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsSocket for crate::net::TcpStream {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<crate::net::TcpStream> for OwnedSocket {
    #[inline]
    fn from(tcp_stream: crate::net::TcpStream) -> OwnedSocket {
        unsafe { OwnedSocket::from_raw_socket(tcp_stream.into_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<OwnedSocket> for crate::net::TcpStream {
    #[inline]
    fn from(owned: OwnedSocket) -> Self {
        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsSocket for crate::net::TcpListener {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<crate::net::TcpListener> for OwnedSocket {
    #[inline]
    fn from(tcp_listener: crate::net::TcpListener) -> OwnedSocket {
        unsafe { OwnedSocket::from_raw_socket(tcp_listener.into_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<OwnedSocket> for crate::net::TcpListener {
    #[inline]
    fn from(owned: OwnedSocket) -> Self {
        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl AsSocket for crate::net::UdpSocket {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<crate::net::UdpSocket> for OwnedSocket {
    #[inline]
    fn from(udp_socket: crate::net::UdpSocket) -> OwnedSocket {
        unsafe { OwnedSocket::from_raw_socket(udp_socket.into_raw_socket()) }
    }
}

#[stable(feature = "io_safety", since = "1.63.0")]
impl From<OwnedSocket> for crate::net::UdpSocket {
    #[inline]
    fn from(owned: OwnedSocket) -> Self {
        unsafe { Self::from_raw_socket(owned.into_raw_socket()) }
    }
}