1 #![unstable(issue = "none", feature = "windows_net")]
4 use crate::io::{self, IoSlice, IoSliceMut, Read};
5 use crate::lazy::SyncOnceCell;
7 use crate::net::{Shutdown, SocketAddr};
8 use crate::os::windows::io::{
9 AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
14 use crate::sys_common::net;
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
16 use crate::time::Duration;
18 use libc::{c_int, c_long, c_ulong, c_ushort};
20 pub type wrlen_t = i32;
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::*;
30 pub struct Socket(OwnedSocket);
32 static WSA_CLEANUP: SyncOnceCell<unsafe extern "system" fn() -> i32> = SyncOnceCell::new();
34 /// Checks whether the Windows socket interface has been started already, and
35 /// if not, starts it.
37 let _ = WSA_CLEANUP.get_or_init(|| unsafe {
38 let mut data: c::WSADATA = mem::zeroed();
39 let ret = c::WSAStartup(
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.
53 // only perform cleanup if network functionality was actually initialized
54 if let Some(cleanup) = WSA_CLEANUP.get() {
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() })
67 pub trait IsMinusOne {
68 fn is_minus_one(&self) -> bool;
71 macro_rules! impl_is_minus_one {
72 ($($t:ident)*) => ($(impl IsMinusOne for $t {
73 fn is_minus_one(&self) -> bool {
79 impl_is_minus_one! { i8 i16 i32 i64 isize }
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) }
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()) }
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>
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,
108 let socket = unsafe {
115 c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
119 if socket != c::INVALID_SOCKET {
120 unsafe { Ok(Self::from_raw_socket(socket)) }
122 let error = unsafe { c::WSAGetLastError() };
124 if error != c::WSAEPROTOTYPE && error != c::WSAEINVAL {
125 return Err(io::Error::from_raw_os_error(error));
129 unsafe { c::WSASocketW(family, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) };
131 if socket == c::INVALID_SOCKET {
132 return Err(last_error());
136 let socket = Self::from_raw_socket(socket);
137 socket.0.set_no_inherit()?;
143 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
144 self.set_nonblocking(true)?;
146 let (addrp, len) = addr.into_inner();
147 let result = unsafe { c::connect(self.as_raw_socket(), addrp, len) };
148 cvt(result).map(drop)
150 self.set_nonblocking(false)?;
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",
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,
166 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
171 let mut fds = unsafe { mem::zeroed::<c::fd_set>() };
173 fds.fd_array[0] = self.as_raw_socket();
177 let mut writefds = fds;
178 let mut errorfds = fds;
181 let result = unsafe {
182 c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout)
188 0 => Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out")),
190 if writefds.fd_count != 1 {
191 if let Some(e) = self.take_error()? {
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) };
208 c::INVALID_SOCKET => Err(last_error()),
209 _ => unsafe { Ok(Self::from_raw_socket(socket)) },
213 pub fn duplicate(&self) -> io::Result<Socket> {
214 Ok(Self(self.0.try_clone()?))
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;
222 unsafe { c::recv(self.as_raw_socket(), buf.as_mut_ptr() as *mut _, length, flags) };
226 let error = unsafe { c::WSAGetLastError() };
228 if error == c::WSAESHUTDOWN {
231 Err(io::Error::from_raw_os_error(error))
234 _ => Ok(result as usize),
238 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
239 self.recv_with_flags(buf, 0)
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;
248 let result = unsafe {
250 self.as_raw_socket(),
251 bufs.as_mut_ptr() as *mut c::WSABUF,
261 0 => Ok(nread as usize),
263 let error = unsafe { c::WSAGetLastError() };
265 if error == c::WSAESHUTDOWN {
268 Err(io::Error::from_raw_os_error(error))
275 pub fn is_read_vectored(&self) -> bool {
279 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
280 self.recv_with_flags(buf, c::MSG_PEEK)
283 fn recv_from_with_flags(
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;
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 {
296 self.as_raw_socket(),
297 buf.as_mut_ptr() as *mut _,
300 &mut storage as *mut _ as *mut _,
307 let error = unsafe { c::WSAGetLastError() };
309 if error == c::WSAESHUTDOWN {
310 Ok((0, net::sockaddr_to_addr(&storage, addrlen as usize)?))
312 Err(io::Error::from_raw_os_error(error))
315 _ => Ok((result as usize, net::sockaddr_to_addr(&storage, addrlen as usize)?)),
319 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
320 self.recv_from_with_flags(buf, 0)
323 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
324 self.recv_from_with_flags(buf, c::MSG_PEEK)
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 {
332 self.as_raw_socket(),
333 bufs.as_ptr() as *const c::WSABUF as *mut _,
341 cvt(result).map(|_| nwritten as usize)
345 pub fn is_write_vectored(&self) -> bool {
349 pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> {
350 let timeout = match dur {
352 let timeout = sys::dur2timeout(dur);
354 return Err(io::const_io_error!(
355 io::ErrorKind::InvalidInput,
356 "cannot set a 0 duration timeout",
363 net::setsockopt(self, c::SOL_SOCKET, kind, timeout)
366 pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> {
367 let raw: c::DWORD = net::getsockopt(self, c::SOL_SOCKET, kind)?;
371 let secs = raw / 1000;
372 let nsec = (raw % 1000) * 1000000;
373 Ok(Some(Duration::new(secs as u64, nsec as u32)))
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,
383 let result = unsafe { c::shutdown(self.as_raw_socket(), how) };
384 cvt(result).map(drop)
387 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
388 let mut nonblocking = nonblocking as c_ulong;
390 unsafe { c::ioctlsocket(self.as_raw_socket(), c::FIONBIO as c_int, &mut nonblocking) };
391 cvt(result).map(drop)
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,
400 net::setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger)
403 pub fn linger(&self) -> io::Result<Option<Duration>> {
404 let val: c::linger = net::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?;
406 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
409 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
410 net::setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BYTE)
413 pub fn nodelay(&self) -> io::Result<bool> {
414 let raw: c::BYTE = net::getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?;
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))) }
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()
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> {
436 impl AsInner<OwnedSocket> for Socket {
437 fn as_inner(&self) -> &OwnedSocket {
442 impl FromInner<OwnedSocket> for Socket {
443 fn from_inner(sock: OwnedSocket) -> Socket {
448 impl IntoInner<OwnedSocket> for Socket {
449 fn into_inner(self) -> OwnedSocket {
454 impl AsSocket for Socket {
455 fn as_socket(&self) -> BorrowedSocket<'_> {
460 impl AsRawSocket for Socket {
461 fn as_raw_socket(&self) -> RawSocket {
462 self.0.as_raw_socket()
466 impl IntoRawSocket for Socket {
467 fn into_raw_socket(self) -> RawSocket {
468 self.0.into_raw_socket()
472 impl FromRawSocket for Socket {
473 unsafe fn from_raw_socket(raw_socket: RawSocket) -> Self {
474 Self(FromRawSocket::from_raw_socket(raw_socket))