std\sys\net\connection\socket/
windows.rs

1#![unstable(issue = "none", feature = "windows_net")]
2
3use core::ffi::{c_int, c_long, c_ulong, c_ushort};
4
5use super::{getsockopt, setsockopt, socket_addr_from_c, socket_addr_to_c};
6use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut, Read};
7use crate::net::{Shutdown, SocketAddr};
8use crate::os::windows::io::{
9    AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
10};
11use crate::sync::OnceLock;
12use crate::sys::c;
13use crate::sys_common::{AsInner, FromInner, IntoInner};
14use crate::time::Duration;
15use crate::{cmp, mem, ptr, sys};
16
17#[allow(non_camel_case_types)]
18pub type wrlen_t = i32;
19
20pub(super) mod netc {
21    //! BSD socket compatibility shim
22    //!
23    //! Some Windows API types are not quite what's expected by our cross-platform
24    //! net code. E.g. naming differences or different pointer types.
25
26    use core::ffi::{c_char, c_int, c_uint, c_ulong, c_ushort, c_void};
27
28    use crate::sys::c::{self, ADDRESS_FAMILY, ADDRINFOA, SOCKADDR, SOCKET};
29    // re-exports from Windows API bindings.
30    pub use crate::sys::c::{
31        ADDRESS_FAMILY as sa_family_t, ADDRINFOA as addrinfo, IP_ADD_MEMBERSHIP,
32        IP_DROP_MEMBERSHIP, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, IPPROTO_IP, IPPROTO_IPV6,
33        IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_MULTICAST_LOOP, IPV6_V6ONLY, SO_BROADCAST,
34        SO_RCVTIMEO, SO_SNDTIMEO, SOCK_DGRAM, SOCK_STREAM, SOCKADDR as sockaddr,
35        SOCKADDR_STORAGE as sockaddr_storage, SOL_SOCKET, bind, connect, freeaddrinfo, getpeername,
36        getsockname, getsockopt, listen, setsockopt,
37    };
38
39    #[allow(non_camel_case_types)]
40    pub type socklen_t = c_int;
41
42    pub const AF_INET: i32 = c::AF_INET as i32;
43    pub const AF_INET6: i32 = c::AF_INET6 as i32;
44
45    // The following two structs use a union in the generated bindings but
46    // our cross-platform code expects a normal field so it's redefined here.
47    // As a consequence, we also need to redefine other structs that use this struct.
48    #[repr(C)]
49    #[derive(Copy, Clone)]
50    pub struct in_addr {
51        pub s_addr: u32,
52    }
53
54    #[repr(C)]
55    #[derive(Copy, Clone)]
56    pub struct in6_addr {
57        pub s6_addr: [u8; 16],
58    }
59
60    #[repr(C)]
61    pub struct ip_mreq {
62        pub imr_multiaddr: in_addr,
63        pub imr_interface: in_addr,
64    }
65
66    #[repr(C)]
67    pub struct ipv6_mreq {
68        pub ipv6mr_multiaddr: in6_addr,
69        pub ipv6mr_interface: c_uint,
70    }
71
72    #[repr(C)]
73    #[derive(Copy, Clone)]
74    pub struct sockaddr_in {
75        pub sin_family: ADDRESS_FAMILY,
76        pub sin_port: c_ushort,
77        pub sin_addr: in_addr,
78        pub sin_zero: [c_char; 8],
79    }
80
81    #[repr(C)]
82    #[derive(Copy, Clone)]
83    pub struct sockaddr_in6 {
84        pub sin6_family: ADDRESS_FAMILY,
85        pub sin6_port: c_ushort,
86        pub sin6_flowinfo: c_ulong,
87        pub sin6_addr: in6_addr,
88        pub sin6_scope_id: c_ulong,
89    }
90
91    pub unsafe fn send(socket: SOCKET, buf: *const c_void, len: c_int, flags: c_int) -> c_int {
92        unsafe { c::send(socket, buf.cast::<u8>(), len, flags) }
93    }
94    pub unsafe fn sendto(
95        socket: SOCKET,
96        buf: *const c_void,
97        len: c_int,
98        flags: c_int,
99        addr: *const SOCKADDR,
100        addrlen: c_int,
101    ) -> c_int {
102        unsafe { c::sendto(socket, buf.cast::<u8>(), len, flags, addr, addrlen) }
103    }
104    pub unsafe fn getaddrinfo(
105        node: *const c_char,
106        service: *const c_char,
107        hints: *const ADDRINFOA,
108        res: *mut *mut ADDRINFOA,
109    ) -> c_int {
110        unsafe { c::getaddrinfo(node.cast::<u8>(), service.cast::<u8>(), hints, res) }
111    }
112}
113
114#[expect(missing_debug_implementations)]
115pub struct Socket(OwnedSocket);
116
117static WSA_CLEANUP: OnceLock<unsafe extern "system" fn() -> i32> = OnceLock::new();
118
119/// Checks whether the Windows socket interface has been started already, and
120/// if not, starts it.
121pub fn init() {
122    let _ = WSA_CLEANUP.get_or_init(|| unsafe {
123        let mut data: c::WSADATA = mem::zeroed();
124        let ret = c::WSAStartup(
125            0x202, // version 2.2
126            &mut data,
127        );
128        assert_eq!(ret, 0);
129
130        // Only register `WSACleanup` if `WSAStartup` is actually ever called.
131        // Workaround to prevent linking to `WS2_32.dll` when no network functionality is used.
132        // See issue #85441.
133        c::WSACleanup
134    });
135}
136
137pub fn cleanup() {
138    // only perform cleanup if network functionality was actually initialized
139    if let Some(cleanup) = WSA_CLEANUP.get() {
140        unsafe {
141            cleanup();
142        }
143    }
144}
145
146/// Returns the last error from the Windows socket interface.
147fn last_error() -> io::Error {
148    io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
149}
150
151#[doc(hidden)]
152pub trait IsMinusOne {
153    fn is_minus_one(&self) -> bool;
154}
155
156macro_rules! impl_is_minus_one {
157    ($($t:ident)*) => ($(impl IsMinusOne for $t {
158        fn is_minus_one(&self) -> bool {
159            *self == -1
160        }
161    })*)
162}
163
164impl_is_minus_one! { i8 i16 i32 i64 isize }
165
166/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
167/// and if so, returns the last error from the Windows socket interface. This
168/// function must be called before another call to the socket API is made.
169pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
170    if t.is_minus_one() { Err(last_error()) } else { Ok(t) }
171}
172
173/// A variant of `cvt` for `getaddrinfo` which return 0 for a success.
174pub fn cvt_gai(err: c_int) -> io::Result<()> {
175    if err == 0 { Ok(()) } else { Err(last_error()) }
176}
177
178/// Just to provide the same interface as sys/pal/unix/net.rs
179pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
180where
181    T: IsMinusOne,
182    F: FnMut() -> T,
183{
184    cvt(f())
185}
186
187impl Socket {
188    pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
189        let family = match *addr {
190            SocketAddr::V4(..) => netc::AF_INET,
191            SocketAddr::V6(..) => netc::AF_INET6,
192        };
193        let socket = unsafe {
194            c::WSASocketW(
195                family,
196                ty,
197                0,
198                ptr::null_mut(),
199                0,
200                c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
201            )
202        };
203
204        if socket != c::INVALID_SOCKET {
205            unsafe { Ok(Self::from_raw(socket)) }
206        } else {
207            let error = unsafe { c::WSAGetLastError() };
208
209            if error != c::WSAEPROTOTYPE && error != c::WSAEINVAL {
210                return Err(io::Error::from_raw_os_error(error));
211            }
212
213            let socket =
214                unsafe { c::WSASocketW(family, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) };
215
216            if socket == c::INVALID_SOCKET {
217                return Err(last_error());
218            }
219
220            unsafe {
221                let socket = Self::from_raw(socket);
222                socket.0.set_no_inherit()?;
223                Ok(socket)
224            }
225        }
226    }
227
228    pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
229        let (addr, len) = socket_addr_to_c(addr);
230        let result = unsafe { c::connect(self.as_raw(), addr.as_ptr(), len) };
231        cvt(result).map(drop)
232    }
233
234    pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
235        self.set_nonblocking(true)?;
236        let result = self.connect(addr);
237        self.set_nonblocking(false)?;
238
239        match result {
240            Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
241                if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
242                    return Err(io::Error::ZERO_TIMEOUT);
243                }
244
245                let mut timeout = c::TIMEVAL {
246                    tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long,
247                    tv_usec: timeout.subsec_micros() as c_long,
248                };
249
250                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
251                    timeout.tv_usec = 1;
252                }
253
254                let fds = {
255                    let mut fds = unsafe { mem::zeroed::<c::FD_SET>() };
256                    fds.fd_count = 1;
257                    fds.fd_array[0] = self.as_raw();
258                    fds
259                };
260
261                let mut writefds = fds;
262                let mut errorfds = fds;
263
264                let count = {
265                    let result = unsafe {
266                        c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout)
267                    };
268                    cvt(result)?
269                };
270
271                match count {
272                    0 => Err(io::const_error!(io::ErrorKind::TimedOut, "connection timed out")),
273                    _ => {
274                        if writefds.fd_count != 1 {
275                            if let Some(e) = self.take_error()? {
276                                return Err(e);
277                            }
278                        }
279
280                        Ok(())
281                    }
282                }
283            }
284            _ => result,
285        }
286    }
287
288    pub fn accept(&self, storage: *mut c::SOCKADDR, len: *mut c_int) -> io::Result<Socket> {
289        let socket = unsafe { c::accept(self.as_raw(), storage, len) };
290
291        match socket {
292            c::INVALID_SOCKET => Err(last_error()),
293            _ => unsafe { Ok(Self::from_raw(socket)) },
294        }
295    }
296
297    pub fn duplicate(&self) -> io::Result<Socket> {
298        Ok(Self(self.0.try_clone()?))
299    }
300
301    fn recv_with_flags(&self, mut buf: BorrowedCursor<'_>, flags: c_int) -> io::Result<()> {
302        // On unix when a socket is shut down all further reads return 0, so we
303        // do the same on windows to map a shut down socket to returning EOF.
304        let length = cmp::min(buf.capacity(), i32::MAX as usize) as i32;
305        let result =
306            unsafe { c::recv(self.as_raw(), buf.as_mut().as_mut_ptr() as *mut _, length, flags) };
307
308        match result {
309            c::SOCKET_ERROR => {
310                let error = unsafe { c::WSAGetLastError() };
311
312                if error == c::WSAESHUTDOWN {
313                    Ok(())
314                } else {
315                    Err(io::Error::from_raw_os_error(error))
316                }
317            }
318            _ => {
319                unsafe { buf.advance_unchecked(result as usize) };
320                Ok(())
321            }
322        }
323    }
324
325    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
326        let mut buf = BorrowedBuf::from(buf);
327        self.recv_with_flags(buf.unfilled(), 0)?;
328        Ok(buf.len())
329    }
330
331    pub fn read_buf(&self, buf: BorrowedCursor<'_>) -> io::Result<()> {
332        self.recv_with_flags(buf, 0)
333    }
334
335    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
336        // On unix when a socket is shut down all further reads return 0, so we
337        // do the same on windows to map a shut down socket to returning EOF.
338        let length = cmp::min(bufs.len(), u32::MAX as usize) as u32;
339        let mut nread = 0;
340        let mut flags = 0;
341        let result = unsafe {
342            c::WSARecv(
343                self.as_raw(),
344                bufs.as_mut_ptr() as *mut c::WSABUF,
345                length,
346                &mut nread,
347                &mut flags,
348                ptr::null_mut(),
349                None,
350            )
351        };
352
353        match result {
354            0 => Ok(nread as usize),
355            _ => {
356                let error = unsafe { c::WSAGetLastError() };
357
358                if error == c::WSAESHUTDOWN {
359                    Ok(0)
360                } else {
361                    Err(io::Error::from_raw_os_error(error))
362                }
363            }
364        }
365    }
366
367    #[inline]
368    pub fn is_read_vectored(&self) -> bool {
369        true
370    }
371
372    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
373        let mut buf = BorrowedBuf::from(buf);
374        self.recv_with_flags(buf.unfilled(), c::MSG_PEEK)?;
375        Ok(buf.len())
376    }
377
378    fn recv_from_with_flags(
379        &self,
380        buf: &mut [u8],
381        flags: c_int,
382    ) -> io::Result<(usize, SocketAddr)> {
383        let mut storage = unsafe { mem::zeroed::<c::SOCKADDR_STORAGE>() };
384        let mut addrlen = size_of_val(&storage) as netc::socklen_t;
385        let length = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
386
387        // On unix when a socket is shut down all further reads return 0, so we
388        // do the same on windows to map a shut down socket to returning EOF.
389        let result = unsafe {
390            c::recvfrom(
391                self.as_raw(),
392                buf.as_mut_ptr() as *mut _,
393                length,
394                flags,
395                (&raw mut storage) as *mut _,
396                &mut addrlen,
397            )
398        };
399
400        match result {
401            c::SOCKET_ERROR => {
402                let error = unsafe { c::WSAGetLastError() };
403
404                if error == c::WSAESHUTDOWN {
405                    Ok((0, unsafe { socket_addr_from_c(&storage, addrlen as usize)? }))
406                } else {
407                    Err(io::Error::from_raw_os_error(error))
408                }
409            }
410            _ => Ok((result as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })),
411        }
412    }
413
414    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
415        self.recv_from_with_flags(buf, 0)
416    }
417
418    pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
419        self.recv_from_with_flags(buf, c::MSG_PEEK)
420    }
421
422    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
423        let length = cmp::min(bufs.len(), u32::MAX as usize) as u32;
424        let mut nwritten = 0;
425        let result = unsafe {
426            c::WSASend(
427                self.as_raw(),
428                bufs.as_ptr() as *const c::WSABUF as *mut _,
429                length,
430                &mut nwritten,
431                0,
432                ptr::null_mut(),
433                None,
434            )
435        };
436        cvt(result).map(|_| nwritten as usize)
437    }
438
439    #[inline]
440    pub fn is_write_vectored(&self) -> bool {
441        true
442    }
443
444    pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> {
445        let timeout = match dur {
446            Some(dur) => {
447                let timeout = sys::dur2timeout(dur);
448                if timeout == 0 {
449                    return Err(io::Error::ZERO_TIMEOUT);
450                }
451                timeout
452            }
453            None => 0,
454        };
455        setsockopt(self, c::SOL_SOCKET, kind, timeout)
456    }
457
458    pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> {
459        let raw: u32 = getsockopt(self, c::SOL_SOCKET, kind)?;
460        if raw == 0 {
461            Ok(None)
462        } else {
463            let secs = raw / 1000;
464            let nsec = (raw % 1000) * 1000000;
465            Ok(Some(Duration::new(secs as u64, nsec as u32)))
466        }
467    }
468
469    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
470        let how = match how {
471            Shutdown::Write => c::SD_SEND,
472            Shutdown::Read => c::SD_RECEIVE,
473            Shutdown::Both => c::SD_BOTH,
474        };
475        let result = unsafe { c::shutdown(self.as_raw(), how) };
476        cvt(result).map(drop)
477    }
478
479    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
480        let mut nonblocking = nonblocking as c_ulong;
481        let result =
482            unsafe { c::ioctlsocket(self.as_raw(), c::FIONBIO as c_int, &mut nonblocking) };
483        cvt(result).map(drop)
484    }
485
486    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
487        let linger = c::LINGER {
488            l_onoff: linger.is_some() as c_ushort,
489            l_linger: linger.unwrap_or_default().as_secs() as c_ushort,
490        };
491
492        setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger)
493    }
494
495    pub fn linger(&self) -> io::Result<Option<Duration>> {
496        let val: c::LINGER = getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?;
497
498        Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
499    }
500
501    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
502        setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BOOL)
503    }
504
505    pub fn nodelay(&self) -> io::Result<bool> {
506        let raw: c::BOOL = getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?;
507        Ok(raw != 0)
508    }
509
510    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
511        let raw: c_int = getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?;
512        if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
513    }
514
515    // This is used by sys_common code to abstract over Windows and Unix.
516    pub fn as_raw(&self) -> c::SOCKET {
517        debug_assert_eq!(size_of::<c::SOCKET>(), size_of::<RawSocket>());
518        debug_assert_eq!(align_of::<c::SOCKET>(), align_of::<RawSocket>());
519        self.as_inner().as_raw_socket() as c::SOCKET
520    }
521    pub unsafe fn from_raw(raw: c::SOCKET) -> Self {
522        debug_assert_eq!(size_of::<c::SOCKET>(), size_of::<RawSocket>());
523        debug_assert_eq!(align_of::<c::SOCKET>(), align_of::<RawSocket>());
524        unsafe { Self::from_raw_socket(raw as RawSocket) }
525    }
526}
527
528#[unstable(reason = "not public", issue = "none", feature = "fd_read")]
529impl<'a> Read for &'a Socket {
530    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
531        (**self).read(buf)
532    }
533}
534
535impl AsInner<OwnedSocket> for Socket {
536    #[inline]
537    fn as_inner(&self) -> &OwnedSocket {
538        &self.0
539    }
540}
541
542impl FromInner<OwnedSocket> for Socket {
543    fn from_inner(sock: OwnedSocket) -> Socket {
544        Socket(sock)
545    }
546}
547
548impl IntoInner<OwnedSocket> for Socket {
549    fn into_inner(self) -> OwnedSocket {
550        self.0
551    }
552}
553
554impl AsSocket for Socket {
555    fn as_socket(&self) -> BorrowedSocket<'_> {
556        self.0.as_socket()
557    }
558}
559
560impl AsRawSocket for Socket {
561    fn as_raw_socket(&self) -> RawSocket {
562        self.0.as_raw_socket()
563    }
564}
565
566impl IntoRawSocket for Socket {
567    fn into_raw_socket(self) -> RawSocket {
568        self.0.into_raw_socket()
569    }
570}
571
572impl FromRawSocket for Socket {
573    unsafe fn from_raw_socket(raw_socket: RawSocket) -> Self {
574        unsafe { Self(FromRawSocket::from_raw_socket(raw_socket)) }
575    }
576}