]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/net.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[rust.git] / library / std / src / sys / windows / net.rs
1 #![unstable(issue = "none", feature = "windows_net")]
2
3 use crate::cmp;
4 use crate::io::{self, IoSlice, IoSliceMut, Read};
5 use crate::lazy::SyncOnceCell;
6 use crate::mem;
7 use crate::net::{Shutdown, SocketAddr};
8 use crate::os::windows::io::{
9     AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
10 };
11 use crate::ptr;
12 use crate::sys;
13 use crate::sys::c;
14 use crate::sys_common::net;
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
16 use crate::time::Duration;
17
18 use libc::{c_int, c_long, c_ulong, c_ushort};
19
20 pub type wrlen_t = i32;
21
22 pub mod netc {
23     pub use crate::sys::c::ADDRESS_FAMILY as sa_family_t;
24     pub use crate::sys::c::ADDRINFOA as addrinfo;
25     pub use crate::sys::c::SOCKADDR as sockaddr;
26     pub use crate::sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage;
27     pub use crate::sys::c::*;
28 }
29
30 pub struct Socket(OwnedSocket);
31
32 static WSA_CLEANUP: SyncOnceCell<unsafe extern "system" fn() -> i32> = SyncOnceCell::new();
33
34 /// Checks whether the Windows socket interface has been started already, and
35 /// if not, starts it.
36 pub fn init() {
37     let _ = WSA_CLEANUP.get_or_init(|| unsafe {
38         let mut data: c::WSADATA = mem::zeroed();
39         let ret = c::WSAStartup(
40             0x202, // version 2.2
41             &mut data,
42         );
43         assert_eq!(ret, 0);
44
45         // Only register `WSACleanup` if `WSAStartup` is actually ever called.
46         // Workaround to prevent linking to `WS2_32.dll` when no network functionality is used.
47         // See issue #85441.
48         c::WSACleanup
49     });
50 }
51
52 pub fn cleanup() {
53     // only perform cleanup if network functionality was actually initialized
54     if let Some(cleanup) = WSA_CLEANUP.get() {
55         unsafe {
56             cleanup();
57         }
58     }
59 }
60
61 /// Returns the last error from the Windows socket interface.
62 fn last_error() -> io::Error {
63     io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
64 }
65
66 #[doc(hidden)]
67 pub trait IsMinusOne {
68     fn is_minus_one(&self) -> bool;
69 }
70
71 macro_rules! impl_is_minus_one {
72     ($($t:ident)*) => ($(impl IsMinusOne for $t {
73         fn is_minus_one(&self) -> bool {
74             *self == -1
75         }
76     })*)
77 }
78
79 impl_is_minus_one! { i8 i16 i32 i64 isize }
80
81 /// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
82 /// and if so, returns the last error from the Windows socket interface. This
83 /// function must be called before another call to the socket API is made.
84 pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
85     if t.is_minus_one() { Err(last_error()) } else { Ok(t) }
86 }
87
88 /// A variant of `cvt` for `getaddrinfo` which return 0 for a success.
89 pub fn cvt_gai(err: c_int) -> io::Result<()> {
90     if err == 0 { Ok(()) } else { Err(last_error()) }
91 }
92
93 /// Just to provide the same interface as sys/unix/net.rs
94 pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
95 where
96     T: IsMinusOne,
97     F: FnMut() -> T,
98 {
99     cvt(f())
100 }
101
102 impl Socket {
103     pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
104         let family = match *addr {
105             SocketAddr::V4(..) => c::AF_INET,
106             SocketAddr::V6(..) => c::AF_INET6,
107         };
108         let socket = unsafe {
109             c::WSASocketW(
110                 family,
111                 ty,
112                 0,
113                 ptr::null_mut(),
114                 0,
115                 c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
116             )
117         };
118
119         if socket != c::INVALID_SOCKET {
120             unsafe { Ok(Self::from_raw_socket(socket)) }
121         } else {
122             let error = unsafe { c::WSAGetLastError() };
123
124             if error != c::WSAEPROTOTYPE && error != c::WSAEINVAL {
125                 return Err(io::Error::from_raw_os_error(error));
126             }
127
128             let socket =
129                 unsafe { c::WSASocketW(family, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) };
130
131             if socket == c::INVALID_SOCKET {
132                 return Err(last_error());
133             }
134
135             unsafe {
136                 let socket = Self::from_raw_socket(socket);
137                 socket.0.set_no_inherit()?;
138                 Ok(socket)
139             }
140         }
141     }
142
143     pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
144         self.set_nonblocking(true)?;
145         let result = {
146             let (addrp, len) = addr.into_inner();
147             let result = unsafe { c::connect(self.as_raw_socket(), addrp, len) };
148             cvt(result).map(drop)
149         };
150         self.set_nonblocking(false)?;
151
152         match result {
153             Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
154                 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
155                     return Err(io::const_io_error!(
156                         io::ErrorKind::InvalidInput,
157                         "cannot set a 0 duration timeout",
158                     ));
159                 }
160
161                 let mut timeout = c::timeval {
162                     tv_sec: timeout.as_secs() as c_long,
163                     tv_usec: (timeout.subsec_nanos() / 1000) as c_long,
164                 };
165
166                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
167                     timeout.tv_usec = 1;
168                 }
169
170                 let fds = {
171                     let mut fds = unsafe { mem::zeroed::<c::fd_set>() };
172                     fds.fd_count = 1;
173                     fds.fd_array[0] = self.as_raw_socket();
174                     fds
175                 };
176
177                 let mut writefds = fds;
178                 let mut errorfds = fds;
179
180                 let count = {
181                     let result = unsafe {
182                         c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout)
183                     };
184                     cvt(result)?
185                 };
186
187                 match count {
188                     0 => Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out")),
189                     _ => {
190                         if writefds.fd_count != 1 {
191                             if let Some(e) = self.take_error()? {
192                                 return Err(e);
193                             }
194                         }
195
196                         Ok(())
197                     }
198                 }
199             }
200             _ => result,
201         }
202     }
203
204     pub fn accept(&self, storage: *mut c::SOCKADDR, len: *mut c_int) -> io::Result<Socket> {
205         let socket = unsafe { c::accept(self.as_raw_socket(), storage, len) };
206
207         match socket {
208             c::INVALID_SOCKET => Err(last_error()),
209             _ => unsafe { Ok(Self::from_raw_socket(socket)) },
210         }
211     }
212
213     pub fn duplicate(&self) -> io::Result<Socket> {
214         Ok(Self(self.0.try_clone()?))
215     }
216
217     fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
218         // On unix when a socket is shut down all further reads return 0, so we
219         // do the same on windows to map a shut down socket to returning EOF.
220         let length = cmp::min(buf.len(), i32::MAX as usize) as i32;
221         let result =
222             unsafe { c::recv(self.as_raw_socket(), buf.as_mut_ptr() as *mut _, length, flags) };
223
224         match result {
225             c::SOCKET_ERROR => {
226                 let error = unsafe { c::WSAGetLastError() };
227
228                 if error == c::WSAESHUTDOWN {
229                     Ok(0)
230                 } else {
231                     Err(io::Error::from_raw_os_error(error))
232                 }
233             }
234             _ => Ok(result as usize),
235         }
236     }
237
238     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
239         self.recv_with_flags(buf, 0)
240     }
241
242     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
243         // On unix when a socket is shut down all further reads return 0, so we
244         // do the same on windows to map a shut down socket to returning EOF.
245         let length = cmp::min(bufs.len(), c::DWORD::MAX as usize) as c::DWORD;
246         let mut nread = 0;
247         let mut flags = 0;
248         let result = unsafe {
249             c::WSARecv(
250                 self.as_raw_socket(),
251                 bufs.as_mut_ptr() as *mut c::WSABUF,
252                 length,
253                 &mut nread,
254                 &mut flags,
255                 ptr::null_mut(),
256                 ptr::null_mut(),
257             )
258         };
259
260         match result {
261             0 => Ok(nread as usize),
262             _ => {
263                 let error = unsafe { c::WSAGetLastError() };
264
265                 if error == c::WSAESHUTDOWN {
266                     Ok(0)
267                 } else {
268                     Err(io::Error::from_raw_os_error(error))
269                 }
270             }
271         }
272     }
273
274     #[inline]
275     pub fn is_read_vectored(&self) -> bool {
276         true
277     }
278
279     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
280         self.recv_with_flags(buf, c::MSG_PEEK)
281     }
282
283     fn recv_from_with_flags(
284         &self,
285         buf: &mut [u8],
286         flags: c_int,
287     ) -> io::Result<(usize, SocketAddr)> {
288         let mut storage = unsafe { mem::zeroed::<c::SOCKADDR_STORAGE_LH>() };
289         let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
290         let length = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
291
292         // On unix when a socket is shut down all further reads return 0, so we
293         // do the same on windows to map a shut down socket to returning EOF.
294         let result = unsafe {
295             c::recvfrom(
296                 self.as_raw_socket(),
297                 buf.as_mut_ptr() as *mut _,
298                 length,
299                 flags,
300                 &mut storage as *mut _ as *mut _,
301                 &mut addrlen,
302             )
303         };
304
305         match result {
306             c::SOCKET_ERROR => {
307                 let error = unsafe { c::WSAGetLastError() };
308
309                 if error == c::WSAESHUTDOWN {
310                     Ok((0, net::sockaddr_to_addr(&storage, addrlen as usize)?))
311                 } else {
312                     Err(io::Error::from_raw_os_error(error))
313                 }
314             }
315             _ => Ok((result as usize, net::sockaddr_to_addr(&storage, addrlen as usize)?)),
316         }
317     }
318
319     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
320         self.recv_from_with_flags(buf, 0)
321     }
322
323     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
324         self.recv_from_with_flags(buf, c::MSG_PEEK)
325     }
326
327     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
328         let length = cmp::min(bufs.len(), c::DWORD::MAX as usize) as c::DWORD;
329         let mut nwritten = 0;
330         let result = unsafe {
331             c::WSASend(
332                 self.as_raw_socket(),
333                 bufs.as_ptr() as *const c::WSABUF as *mut _,
334                 length,
335                 &mut nwritten,
336                 0,
337                 ptr::null_mut(),
338                 ptr::null_mut(),
339             )
340         };
341         cvt(result).map(|_| nwritten as usize)
342     }
343
344     #[inline]
345     pub fn is_write_vectored(&self) -> bool {
346         true
347     }
348
349     pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> {
350         let timeout = match dur {
351             Some(dur) => {
352                 let timeout = sys::dur2timeout(dur);
353                 if timeout == 0 {
354                     return Err(io::const_io_error!(
355                         io::ErrorKind::InvalidInput,
356                         "cannot set a 0 duration timeout",
357                     ));
358                 }
359                 timeout
360             }
361             None => 0,
362         };
363         net::setsockopt(self, c::SOL_SOCKET, kind, timeout)
364     }
365
366     pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> {
367         let raw: c::DWORD = net::getsockopt(self, c::SOL_SOCKET, kind)?;
368         if raw == 0 {
369             Ok(None)
370         } else {
371             let secs = raw / 1000;
372             let nsec = (raw % 1000) * 1000000;
373             Ok(Some(Duration::new(secs as u64, nsec as u32)))
374         }
375     }
376
377     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
378         let how = match how {
379             Shutdown::Write => c::SD_SEND,
380             Shutdown::Read => c::SD_RECEIVE,
381             Shutdown::Both => c::SD_BOTH,
382         };
383         let result = unsafe { c::shutdown(self.as_raw_socket(), how) };
384         cvt(result).map(drop)
385     }
386
387     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
388         let mut nonblocking = nonblocking as c_ulong;
389         let result =
390             unsafe { c::ioctlsocket(self.as_raw_socket(), c::FIONBIO as c_int, &mut nonblocking) };
391         cvt(result).map(drop)
392     }
393
394     pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
395         let linger = c::linger {
396             l_onoff: linger.is_some() as c_ushort,
397             l_linger: linger.unwrap_or_default().as_secs() as c_ushort,
398         };
399
400         net::setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger)
401     }
402
403     pub fn linger(&self) -> io::Result<Option<Duration>> {
404         let val: c::linger = net::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?;
405
406         Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
407     }
408
409     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
410         net::setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BYTE)
411     }
412
413     pub fn nodelay(&self) -> io::Result<bool> {
414         let raw: c::BYTE = net::getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?;
415         Ok(raw != 0)
416     }
417
418     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
419         let raw: c_int = net::getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?;
420         if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
421     }
422
423     // This is used by sys_common code to abstract over Windows and Unix.
424     pub fn as_raw(&self) -> RawSocket {
425         self.as_inner().as_raw_socket()
426     }
427 }
428
429 #[unstable(reason = "not public", issue = "none", feature = "fd_read")]
430 impl<'a> Read for &'a Socket {
431     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
432         (**self).read(buf)
433     }
434 }
435
436 impl AsInner<OwnedSocket> for Socket {
437     fn as_inner(&self) -> &OwnedSocket {
438         &self.0
439     }
440 }
441
442 impl FromInner<OwnedSocket> for Socket {
443     fn from_inner(sock: OwnedSocket) -> Socket {
444         Socket(sock)
445     }
446 }
447
448 impl IntoInner<OwnedSocket> for Socket {
449     fn into_inner(self) -> OwnedSocket {
450         self.0
451     }
452 }
453
454 impl AsSocket for Socket {
455     fn as_socket(&self) -> BorrowedSocket<'_> {
456         self.0.as_socket()
457     }
458 }
459
460 impl AsRawSocket for Socket {
461     fn as_raw_socket(&self) -> RawSocket {
462         self.0.as_raw_socket()
463     }
464 }
465
466 impl IntoRawSocket for Socket {
467     fn into_raw_socket(self) -> RawSocket {
468         self.0.into_raw_socket()
469     }
470 }
471
472 impl FromRawSocket for Socket {
473     unsafe fn from_raw_socket(raw_socket: RawSocket) -> Self {
474         Self(FromRawSocket::from_raw_socket(raw_socket))
475     }
476 }