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