1 // Copyright 2015 The Rust Project Developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 use std::cmp::min;
10 use std::io::{self, IoSlice};
11 use std::marker::PhantomData;
12 use std::mem::{self, size_of, MaybeUninit};
13 use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown};
14 use std::os::windows::prelude::*;
15 use std::sync::Once;
16 use std::time::{Duration, Instant};
17 use std::{ptr, slice};
18
19 use winapi::ctypes::c_long;
20 use winapi::shared::in6addr::*;
21 use winapi::shared::inaddr::*;
22 use winapi::shared::minwindef::DWORD;
23 use winapi::shared::minwindef::ULONG;
24 use winapi::shared::mstcpip::{tcp_keepalive, SIO_KEEPALIVE_VALS};
25 use winapi::shared::ntdef::HANDLE;
26 use winapi::shared::ws2def;
27 use winapi::shared::ws2def::WSABUF;
28 use winapi::um::handleapi::SetHandleInformation;
29 use winapi::um::processthreadsapi::GetCurrentProcessId;
30 use winapi::um::winbase::{self, INFINITE};
31 use winapi::um::winsock2::{
32 self as sock, u_long, POLLERR, POLLHUP, POLLRDNORM, POLLWRNORM, SD_BOTH, SD_RECEIVE, SD_SEND,
33 WSAPOLLFD,
34 };
35
36 use crate::{RecvFlags, SockAddr, TcpKeepalive, Type};
37
38 pub(crate) use winapi::ctypes::c_int;
39
40 /// Fake MSG_TRUNC flag for the [`RecvFlags`] struct.
41 ///
42 /// The flag is enabled when a `WSARecv[From]` call returns `WSAEMSGSIZE`. The
43 /// value of the flag is defined by us.
44 pub(crate) const MSG_TRUNC: c_int = 0x01;
45
46 // Used in `Domain`.
47 pub(crate) use winapi::shared::ws2def::{AF_INET, AF_INET6};
48 // Used in `Type`.
49 pub(crate) use winapi::shared::ws2def::{SOCK_DGRAM, SOCK_STREAM};
50 #[cfg(feature = "all")]
51 pub(crate) use winapi::shared::ws2def::{SOCK_RAW, SOCK_SEQPACKET};
52 // Used in `Protocol`.
53 pub(crate) const IPPROTO_ICMP: c_int = winapi::shared::ws2def::IPPROTO_ICMP as c_int;
54 pub(crate) const IPPROTO_ICMPV6: c_int = winapi::shared::ws2def::IPPROTO_ICMPV6 as c_int;
55 pub(crate) const IPPROTO_TCP: c_int = winapi::shared::ws2def::IPPROTO_TCP as c_int;
56 pub(crate) const IPPROTO_UDP: c_int = winapi::shared::ws2def::IPPROTO_UDP as c_int;
57 // Used in `SockAddr`.
58 pub(crate) use winapi::shared::ws2def::{
59 ADDRESS_FAMILY as sa_family_t, SOCKADDR as sockaddr, SOCKADDR_IN as sockaddr_in,
60 SOCKADDR_STORAGE as sockaddr_storage,
61 };
62 pub(crate) use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH as sockaddr_in6;
63 pub(crate) use winapi::um::ws2tcpip::socklen_t;
64 // Used in `Socket`.
65 pub(crate) use winapi::shared::ws2def::{
66 IPPROTO_IP, SOL_SOCKET, SO_BROADCAST, SO_ERROR, SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE,
67 SO_RCVBUF, SO_RCVTIMEO, SO_REUSEADDR, SO_SNDBUF, SO_SNDTIMEO, SO_TYPE, TCP_NODELAY,
68 };
69 #[cfg(feature = "all")]
70 pub(crate) use winapi::shared::ws2ipdef::IP_HDRINCL;
71 pub(crate) use winapi::shared::ws2ipdef::{
72 IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_MREQ as Ipv6Mreq, IPV6_MULTICAST_HOPS,
73 IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY, IP_ADD_MEMBERSHIP,
74 IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP, IP_MREQ as IpMreq,
75 IP_MREQ_SOURCE as IpMreqSource, IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TOS,
76 IP_TTL,
77 };
78 pub(crate) use winapi::um::winsock2::{linger, MSG_OOB, MSG_PEEK};
79 pub(crate) const IPPROTO_IPV6: c_int = winapi::shared::ws2def::IPPROTO_IPV6 as c_int;
80
81 /// Type used in set/getsockopt to retrieve the `TCP_NODELAY` option.
82 ///
83 /// NOTE: <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-getsockopt>
84 /// documents that options such as `TCP_NODELAY` and `SO_KEEPALIVE` expect a
85 /// `BOOL` (alias for `c_int`, 4 bytes), however in practice this turns out to
86 /// be false (or misleading) as a `BOOLEAN` (`c_uchar`, 1 byte) is returned by
87 /// `getsockopt`.
88 pub(crate) type Bool = winapi::shared::ntdef::BOOLEAN;
89
90 /// Maximum size of a buffer passed to system call like `recv` and `send`.
91 const MAX_BUF_LEN: usize = <c_int>::max_value() as usize;
92
93 /// Helper macro to execute a system call that returns an `io::Result`.
94 macro_rules! syscall {
95 ($fn: ident ( $($arg: expr),* $(,)* ), $err_test: path, $err_value: expr) => {{
96 #[allow(unused_unsafe)]
97 let res = unsafe { sock::$fn($($arg, )*) };
98 if $err_test(&res, &$err_value) {
99 Err(io::Error::last_os_error())
100 } else {
101 Ok(res)
102 }
103 }};
104 }
105
106 impl_debug!(
107 crate::Domain,
108 ws2def::AF_INET,
109 ws2def::AF_INET6,
110 ws2def::AF_UNIX,
111 ws2def::AF_UNSPEC, // = 0.
112 );
113
114 /// Windows only API.
115 impl Type {
116 /// Our custom flag to set `WSA_FLAG_NO_HANDLE_INHERIT` on socket creation.
117 /// Trying to mimic `Type::cloexec` on windows.
118 const NO_INHERIT: c_int = 1 << ((size_of::<c_int>() * 8) - 1); // Last bit.
119
120 /// Set `WSA_FLAG_NO_HANDLE_INHERIT` on the socket.
121 #[cfg(feature = "all")]
122 #[cfg_attr(docsrs, doc(cfg(all(windows, feature = "all"))))]
no_inherit(self) -> Type123 pub const fn no_inherit(self) -> Type {
124 self._no_inherit()
125 }
126
_no_inherit(self) -> Type127 pub(crate) const fn _no_inherit(self) -> Type {
128 Type(self.0 | Type::NO_INHERIT)
129 }
130 }
131
132 impl_debug!(
133 crate::Type,
134 ws2def::SOCK_STREAM,
135 ws2def::SOCK_DGRAM,
136 ws2def::SOCK_RAW,
137 ws2def::SOCK_RDM,
138 ws2def::SOCK_SEQPACKET,
139 );
140
141 impl_debug!(
142 crate::Protocol,
143 self::IPPROTO_ICMP,
144 self::IPPROTO_ICMPV6,
145 self::IPPROTO_TCP,
146 self::IPPROTO_UDP,
147 );
148
149 impl std::fmt::Debug for RecvFlags {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 f.debug_struct("RecvFlags")
152 .field("is_truncated", &self.is_truncated())
153 .finish()
154 }
155 }
156
157 #[repr(transparent)]
158 pub struct MaybeUninitSlice<'a> {
159 vec: WSABUF,
160 _lifetime: PhantomData<&'a mut [MaybeUninit<u8>]>,
161 }
162
163 unsafe impl<'a> Send for MaybeUninitSlice<'a> {}
164
165 unsafe impl<'a> Sync for MaybeUninitSlice<'a> {}
166
167 impl<'a> MaybeUninitSlice<'a> {
new(buf: &'a mut [MaybeUninit<u8>]) -> MaybeUninitSlice<'a>168 pub fn new(buf: &'a mut [MaybeUninit<u8>]) -> MaybeUninitSlice<'a> {
169 assert!(buf.len() <= ULONG::MAX as usize);
170 MaybeUninitSlice {
171 vec: WSABUF {
172 len: buf.len() as ULONG,
173 buf: buf.as_mut_ptr().cast(),
174 },
175 _lifetime: PhantomData,
176 }
177 }
178
as_slice(&self) -> &[MaybeUninit<u8>]179 pub fn as_slice(&self) -> &[MaybeUninit<u8>] {
180 unsafe { slice::from_raw_parts(self.vec.buf.cast(), self.vec.len as usize) }
181 }
182
as_mut_slice(&mut self) -> &mut [MaybeUninit<u8>]183 pub fn as_mut_slice(&mut self) -> &mut [MaybeUninit<u8>] {
184 unsafe { slice::from_raw_parts_mut(self.vec.buf.cast(), self.vec.len as usize) }
185 }
186 }
187
init()188 fn init() {
189 static INIT: Once = Once::new();
190
191 INIT.call_once(|| {
192 // Initialize winsock through the standard library by just creating a
193 // dummy socket. Whether this is successful or not we drop the result as
194 // libstd will be sure to have initialized winsock.
195 let _ = net::UdpSocket::bind("127.0.0.1:34254");
196 });
197 }
198
199 pub(crate) type Socket = sock::SOCKET;
200
socket_from_raw(socket: Socket) -> crate::socket::Inner201 pub(crate) unsafe fn socket_from_raw(socket: Socket) -> crate::socket::Inner {
202 crate::socket::Inner::from_raw_socket(socket as RawSocket)
203 }
204
socket_as_raw(socket: &crate::socket::Inner) -> Socket205 pub(crate) fn socket_as_raw(socket: &crate::socket::Inner) -> Socket {
206 socket.as_raw_socket() as Socket
207 }
208
socket_into_raw(socket: crate::socket::Inner) -> Socket209 pub(crate) fn socket_into_raw(socket: crate::socket::Inner) -> Socket {
210 socket.into_raw_socket() as Socket
211 }
212
socket(family: c_int, mut ty: c_int, protocol: c_int) -> io::Result<Socket>213 pub(crate) fn socket(family: c_int, mut ty: c_int, protocol: c_int) -> io::Result<Socket> {
214 init();
215
216 // Check if we set our custom flag.
217 let flags = if ty & Type::NO_INHERIT != 0 {
218 ty = ty & !Type::NO_INHERIT;
219 sock::WSA_FLAG_NO_HANDLE_INHERIT
220 } else {
221 0
222 };
223
224 syscall!(
225 WSASocketW(
226 family,
227 ty,
228 protocol,
229 ptr::null_mut(),
230 0,
231 sock::WSA_FLAG_OVERLAPPED | flags,
232 ),
233 PartialEq::eq,
234 sock::INVALID_SOCKET
235 )
236 }
237
bind(socket: Socket, addr: &SockAddr) -> io::Result<()>238 pub(crate) fn bind(socket: Socket, addr: &SockAddr) -> io::Result<()> {
239 syscall!(bind(socket, addr.as_ptr(), addr.len()), PartialEq::ne, 0).map(|_| ())
240 }
241
connect(socket: Socket, addr: &SockAddr) -> io::Result<()>242 pub(crate) fn connect(socket: Socket, addr: &SockAddr) -> io::Result<()> {
243 syscall!(connect(socket, addr.as_ptr(), addr.len()), PartialEq::ne, 0).map(|_| ())
244 }
245
poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()>246 pub(crate) fn poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()> {
247 let start = Instant::now();
248
249 let mut fd_array = WSAPOLLFD {
250 fd: socket.as_raw(),
251 events: POLLRDNORM | POLLWRNORM,
252 revents: 0,
253 };
254
255 loop {
256 let elapsed = start.elapsed();
257 if elapsed >= timeout {
258 return Err(io::ErrorKind::TimedOut.into());
259 }
260
261 let timeout = (timeout - elapsed).as_millis();
262 let timeout = clamp(timeout, 1, c_int::max_value() as u128) as c_int;
263
264 match syscall!(
265 WSAPoll(&mut fd_array, 1, timeout),
266 PartialEq::eq,
267 sock::SOCKET_ERROR
268 ) {
269 Ok(0) => return Err(io::ErrorKind::TimedOut.into()),
270 Ok(_) => {
271 // Error or hang up indicates an error (or failure to connect).
272 if (fd_array.revents & POLLERR) != 0 || (fd_array.revents & POLLHUP) != 0 {
273 match socket.take_error() {
274 Ok(Some(err)) => return Err(err),
275 Ok(None) => {
276 return Err(io::Error::new(
277 io::ErrorKind::Other,
278 "no error set after POLLHUP",
279 ))
280 }
281 Err(err) => return Err(err),
282 }
283 }
284 return Ok(());
285 }
286 // Got interrupted, try again.
287 Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue,
288 Err(err) => return Err(err),
289 }
290 }
291 }
292
293 // TODO: use clamp from std lib, stable since 1.50.
clamp<T>(value: T, min: T, max: T) -> T where T: Ord,294 fn clamp<T>(value: T, min: T, max: T) -> T
295 where
296 T: Ord,
297 {
298 if value <= min {
299 min
300 } else if value >= max {
301 max
302 } else {
303 value
304 }
305 }
306
listen(socket: Socket, backlog: c_int) -> io::Result<()>307 pub(crate) fn listen(socket: Socket, backlog: c_int) -> io::Result<()> {
308 syscall!(listen(socket, backlog), PartialEq::ne, 0).map(|_| ())
309 }
310
accept(socket: Socket) -> io::Result<(Socket, SockAddr)>311 pub(crate) fn accept(socket: Socket) -> io::Result<(Socket, SockAddr)> {
312 // Safety: `accept` initialises the `SockAddr` for us.
313 unsafe {
314 SockAddr::init(|storage, len| {
315 syscall!(
316 accept(socket, storage.cast(), len),
317 PartialEq::eq,
318 sock::INVALID_SOCKET
319 )
320 })
321 }
322 }
323
getsockname(socket: Socket) -> io::Result<SockAddr>324 pub(crate) fn getsockname(socket: Socket) -> io::Result<SockAddr> {
325 // Safety: `getsockname` initialises the `SockAddr` for us.
326 unsafe {
327 SockAddr::init(|storage, len| {
328 syscall!(
329 getsockname(socket, storage.cast(), len),
330 PartialEq::eq,
331 sock::SOCKET_ERROR
332 )
333 })
334 }
335 .map(|(_, addr)| addr)
336 }
337
getpeername(socket: Socket) -> io::Result<SockAddr>338 pub(crate) fn getpeername(socket: Socket) -> io::Result<SockAddr> {
339 // Safety: `getpeername` initialises the `SockAddr` for us.
340 unsafe {
341 SockAddr::init(|storage, len| {
342 syscall!(
343 getpeername(socket, storage.cast(), len),
344 PartialEq::eq,
345 sock::SOCKET_ERROR
346 )
347 })
348 }
349 .map(|(_, addr)| addr)
350 }
351
try_clone(socket: Socket) -> io::Result<Socket>352 pub(crate) fn try_clone(socket: Socket) -> io::Result<Socket> {
353 let mut info: MaybeUninit<sock::WSAPROTOCOL_INFOW> = MaybeUninit::uninit();
354 syscall!(
355 WSADuplicateSocketW(socket, GetCurrentProcessId(), info.as_mut_ptr()),
356 PartialEq::eq,
357 sock::SOCKET_ERROR
358 )?;
359 // Safety: `WSADuplicateSocketW` intialised `info` for us.
360 let mut info = unsafe { info.assume_init() };
361
362 syscall!(
363 WSASocketW(
364 info.iAddressFamily,
365 info.iSocketType,
366 info.iProtocol,
367 &mut info,
368 0,
369 sock::WSA_FLAG_OVERLAPPED | sock::WSA_FLAG_NO_HANDLE_INHERIT,
370 ),
371 PartialEq::eq,
372 sock::INVALID_SOCKET
373 )
374 }
375
set_nonblocking(socket: Socket, nonblocking: bool) -> io::Result<()>376 pub(crate) fn set_nonblocking(socket: Socket, nonblocking: bool) -> io::Result<()> {
377 let mut nonblocking = nonblocking as u_long;
378 ioctlsocket(socket, sock::FIONBIO, &mut nonblocking)
379 }
380
shutdown(socket: Socket, how: Shutdown) -> io::Result<()>381 pub(crate) fn shutdown(socket: Socket, how: Shutdown) -> io::Result<()> {
382 let how = match how {
383 Shutdown::Write => SD_SEND,
384 Shutdown::Read => SD_RECEIVE,
385 Shutdown::Both => SD_BOTH,
386 };
387 syscall!(shutdown(socket, how), PartialEq::eq, sock::SOCKET_ERROR).map(|_| ())
388 }
389
recv(socket: Socket, buf: &mut [MaybeUninit<u8>], flags: c_int) -> io::Result<usize>390 pub(crate) fn recv(socket: Socket, buf: &mut [MaybeUninit<u8>], flags: c_int) -> io::Result<usize> {
391 let res = syscall!(
392 recv(
393 socket,
394 buf.as_mut_ptr().cast(),
395 min(buf.len(), MAX_BUF_LEN) as c_int,
396 flags,
397 ),
398 PartialEq::eq,
399 sock::SOCKET_ERROR
400 );
401 match res {
402 Ok(n) => Ok(n as usize),
403 Err(ref err) if err.raw_os_error() == Some(sock::WSAESHUTDOWN as i32) => Ok(0),
404 Err(err) => Err(err),
405 }
406 }
407
recv_vectored( socket: Socket, bufs: &mut [crate::MaybeUninitSlice<'_>], flags: c_int, ) -> io::Result<(usize, RecvFlags)>408 pub(crate) fn recv_vectored(
409 socket: Socket,
410 bufs: &mut [crate::MaybeUninitSlice<'_>],
411 flags: c_int,
412 ) -> io::Result<(usize, RecvFlags)> {
413 let mut nread = 0;
414 let mut flags = flags as DWORD;
415 let res = syscall!(
416 WSARecv(
417 socket,
418 bufs.as_mut_ptr().cast(),
419 min(bufs.len(), DWORD::max_value() as usize) as DWORD,
420 &mut nread,
421 &mut flags,
422 ptr::null_mut(),
423 None,
424 ),
425 PartialEq::eq,
426 sock::SOCKET_ERROR
427 );
428 match res {
429 Ok(_) => Ok((nread as usize, RecvFlags(0))),
430 Err(ref err) if err.raw_os_error() == Some(sock::WSAESHUTDOWN as i32) => {
431 Ok((0, RecvFlags(0)))
432 }
433 Err(ref err) if err.raw_os_error() == Some(sock::WSAEMSGSIZE as i32) => {
434 Ok((nread as usize, RecvFlags(MSG_TRUNC)))
435 }
436 Err(err) => Err(err),
437 }
438 }
439
recv_from( socket: Socket, buf: &mut [MaybeUninit<u8>], flags: c_int, ) -> io::Result<(usize, SockAddr)>440 pub(crate) fn recv_from(
441 socket: Socket,
442 buf: &mut [MaybeUninit<u8>],
443 flags: c_int,
444 ) -> io::Result<(usize, SockAddr)> {
445 // Safety: `recvfrom` initialises the `SockAddr` for us.
446 unsafe {
447 SockAddr::init(|storage, addrlen| {
448 let res = syscall!(
449 recvfrom(
450 socket,
451 buf.as_mut_ptr().cast(),
452 min(buf.len(), MAX_BUF_LEN) as c_int,
453 flags,
454 storage.cast(),
455 addrlen,
456 ),
457 PartialEq::eq,
458 sock::SOCKET_ERROR
459 );
460 match res {
461 Ok(n) => Ok(n as usize),
462 Err(ref err) if err.raw_os_error() == Some(sock::WSAESHUTDOWN as i32) => Ok(0),
463 Err(err) => Err(err),
464 }
465 })
466 }
467 }
468
recv_from_vectored( socket: Socket, bufs: &mut [crate::MaybeUninitSlice<'_>], flags: c_int, ) -> io::Result<(usize, RecvFlags, SockAddr)>469 pub(crate) fn recv_from_vectored(
470 socket: Socket,
471 bufs: &mut [crate::MaybeUninitSlice<'_>],
472 flags: c_int,
473 ) -> io::Result<(usize, RecvFlags, SockAddr)> {
474 // Safety: `recvfrom` initialises the `SockAddr` for us.
475 unsafe {
476 SockAddr::init(|storage, addrlen| {
477 let mut nread = 0;
478 let mut flags = flags as DWORD;
479 let res = syscall!(
480 WSARecvFrom(
481 socket,
482 bufs.as_mut_ptr().cast(),
483 min(bufs.len(), DWORD::max_value() as usize) as DWORD,
484 &mut nread,
485 &mut flags,
486 storage.cast(),
487 addrlen,
488 ptr::null_mut(),
489 None,
490 ),
491 PartialEq::eq,
492 sock::SOCKET_ERROR
493 );
494 match res {
495 Ok(_) => Ok((nread as usize, RecvFlags(0))),
496 Err(ref err) if err.raw_os_error() == Some(sock::WSAESHUTDOWN as i32) => {
497 Ok((nread as usize, RecvFlags(0)))
498 }
499 Err(ref err) if err.raw_os_error() == Some(sock::WSAEMSGSIZE as i32) => {
500 Ok((nread as usize, RecvFlags(MSG_TRUNC)))
501 }
502 Err(err) => Err(err),
503 }
504 })
505 }
506 .map(|((n, recv_flags), addr)| (n, recv_flags, addr))
507 }
508
send(socket: Socket, buf: &[u8], flags: c_int) -> io::Result<usize>509 pub(crate) fn send(socket: Socket, buf: &[u8], flags: c_int) -> io::Result<usize> {
510 syscall!(
511 send(
512 socket,
513 buf.as_ptr().cast(),
514 min(buf.len(), MAX_BUF_LEN) as c_int,
515 flags,
516 ),
517 PartialEq::eq,
518 sock::SOCKET_ERROR
519 )
520 .map(|n| n as usize)
521 }
522
send_vectored( socket: Socket, bufs: &[IoSlice<'_>], flags: c_int, ) -> io::Result<usize>523 pub(crate) fn send_vectored(
524 socket: Socket,
525 bufs: &[IoSlice<'_>],
526 flags: c_int,
527 ) -> io::Result<usize> {
528 let mut nsent = 0;
529 syscall!(
530 WSASend(
531 socket,
532 // FIXME: From the `WSASend` docs [1]:
533 // > For a Winsock application, once the WSASend function is called,
534 // > the system owns these buffers and the application may not
535 // > access them.
536 //
537 // So what we're doing is actually UB as `bufs` needs to be `&mut
538 // [IoSlice<'_>]`.
539 //
540 // Tracking issue: https://github.com/rust-lang/socket2-rs/issues/129.
541 //
542 // NOTE: `send_to_vectored` has the same problem.
543 //
544 // [1] https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasend
545 bufs.as_ptr() as *mut _,
546 min(bufs.len(), DWORD::max_value() as usize) as DWORD,
547 &mut nsent,
548 flags as DWORD,
549 std::ptr::null_mut(),
550 None,
551 ),
552 PartialEq::eq,
553 sock::SOCKET_ERROR
554 )
555 .map(|_| nsent as usize)
556 }
557
send_to( socket: Socket, buf: &[u8], addr: &SockAddr, flags: c_int, ) -> io::Result<usize>558 pub(crate) fn send_to(
559 socket: Socket,
560 buf: &[u8],
561 addr: &SockAddr,
562 flags: c_int,
563 ) -> io::Result<usize> {
564 syscall!(
565 sendto(
566 socket,
567 buf.as_ptr().cast(),
568 min(buf.len(), MAX_BUF_LEN) as c_int,
569 flags,
570 addr.as_ptr(),
571 addr.len(),
572 ),
573 PartialEq::eq,
574 sock::SOCKET_ERROR
575 )
576 .map(|n| n as usize)
577 }
578
send_to_vectored( socket: Socket, bufs: &[IoSlice<'_>], addr: &SockAddr, flags: c_int, ) -> io::Result<usize>579 pub(crate) fn send_to_vectored(
580 socket: Socket,
581 bufs: &[IoSlice<'_>],
582 addr: &SockAddr,
583 flags: c_int,
584 ) -> io::Result<usize> {
585 let mut nsent = 0;
586 syscall!(
587 WSASendTo(
588 socket,
589 // FIXME: Same problem as in `send_vectored`.
590 bufs.as_ptr() as *mut _,
591 bufs.len().min(DWORD::MAX as usize) as DWORD,
592 &mut nsent,
593 flags as DWORD,
594 addr.as_ptr(),
595 addr.len(),
596 ptr::null_mut(),
597 None,
598 ),
599 PartialEq::eq,
600 sock::SOCKET_ERROR
601 )
602 .map(|_| nsent as usize)
603 }
604
605 /// Wrapper around `getsockopt` to deal with platform specific timeouts.
timeout_opt(fd: Socket, lvl: c_int, name: c_int) -> io::Result<Option<Duration>>606 pub(crate) fn timeout_opt(fd: Socket, lvl: c_int, name: c_int) -> io::Result<Option<Duration>> {
607 unsafe { getsockopt(fd, lvl, name).map(from_ms) }
608 }
609
from_ms(duration: DWORD) -> Option<Duration>610 fn from_ms(duration: DWORD) -> Option<Duration> {
611 if duration == 0 {
612 None
613 } else {
614 let secs = duration / 1000;
615 let nsec = (duration % 1000) * 1000000;
616 Some(Duration::new(secs as u64, nsec as u32))
617 }
618 }
619
620 /// Wrapper around `setsockopt` to deal with platform specific timeouts.
set_timeout_opt( fd: Socket, level: c_int, optname: c_int, duration: Option<Duration>, ) -> io::Result<()>621 pub(crate) fn set_timeout_opt(
622 fd: Socket,
623 level: c_int,
624 optname: c_int,
625 duration: Option<Duration>,
626 ) -> io::Result<()> {
627 let duration = into_ms(duration);
628 unsafe { setsockopt(fd, level, optname, duration) }
629 }
630
into_ms(duration: Option<Duration>) -> DWORD631 fn into_ms(duration: Option<Duration>) -> DWORD {
632 // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
633 // timeouts in windows APIs are typically u32 milliseconds. To translate, we
634 // have two pieces to take care of:
635 //
636 // * Nanosecond precision is rounded up
637 // * Greater than u32::MAX milliseconds (50 days) is rounded up to
638 // INFINITE (never time out).
639 duration
640 .map(|duration| min(duration.as_millis(), INFINITE as u128) as DWORD)
641 .unwrap_or(0)
642 }
643
set_tcp_keepalive(socket: Socket, keepalive: &TcpKeepalive) -> io::Result<()>644 pub(crate) fn set_tcp_keepalive(socket: Socket, keepalive: &TcpKeepalive) -> io::Result<()> {
645 let mut keepalive = tcp_keepalive {
646 onoff: 1,
647 keepalivetime: into_ms(keepalive.time),
648 keepaliveinterval: into_ms(keepalive.interval),
649 };
650 let mut out = 0;
651 syscall!(
652 WSAIoctl(
653 socket,
654 SIO_KEEPALIVE_VALS,
655 &mut keepalive as *mut _ as *mut _,
656 size_of::<tcp_keepalive>() as _,
657 ptr::null_mut(),
658 0,
659 &mut out,
660 ptr::null_mut(),
661 None,
662 ),
663 PartialEq::eq,
664 sock::SOCKET_ERROR
665 )
666 .map(|_| ())
667 }
668
669 /// Caller must ensure `T` is the correct type for `level` and `optname`.
getsockopt<T>(socket: Socket, level: c_int, optname: c_int) -> io::Result<T>670 pub(crate) unsafe fn getsockopt<T>(socket: Socket, level: c_int, optname: c_int) -> io::Result<T> {
671 let mut optval: MaybeUninit<T> = MaybeUninit::uninit();
672 let mut optlen = mem::size_of::<T>() as c_int;
673 syscall!(
674 getsockopt(
675 socket,
676 level,
677 optname,
678 optval.as_mut_ptr().cast(),
679 &mut optlen,
680 ),
681 PartialEq::eq,
682 sock::SOCKET_ERROR
683 )
684 .map(|_| {
685 debug_assert_eq!(optlen as usize, mem::size_of::<T>());
686 // Safety: `getsockopt` initialised `optval` for us.
687 optval.assume_init()
688 })
689 }
690
691 /// Caller must ensure `T` is the correct type for `level` and `optname`.
setsockopt<T>( socket: Socket, level: c_int, optname: c_int, optval: T, ) -> io::Result<()>692 pub(crate) unsafe fn setsockopt<T>(
693 socket: Socket,
694 level: c_int,
695 optname: c_int,
696 optval: T,
697 ) -> io::Result<()> {
698 syscall!(
699 setsockopt(
700 socket,
701 level,
702 optname,
703 (&optval as *const T).cast(),
704 mem::size_of::<T>() as c_int,
705 ),
706 PartialEq::eq,
707 sock::SOCKET_ERROR
708 )
709 .map(|_| ())
710 }
711
ioctlsocket(socket: Socket, cmd: c_long, payload: &mut u_long) -> io::Result<()>712 fn ioctlsocket(socket: Socket, cmd: c_long, payload: &mut u_long) -> io::Result<()> {
713 syscall!(
714 ioctlsocket(socket, cmd, payload),
715 PartialEq::eq,
716 sock::SOCKET_ERROR
717 )
718 .map(|_| ())
719 }
720
to_in_addr(addr: &Ipv4Addr) -> IN_ADDR721 pub(crate) fn to_in_addr(addr: &Ipv4Addr) -> IN_ADDR {
722 let mut s_un: in_addr_S_un = unsafe { mem::zeroed() };
723 // `S_un` is stored as BE on all machines, and the array is in BE order. So
724 // the native endian conversion method is used so that it's never swapped.
725 unsafe { *(s_un.S_addr_mut()) = u32::from_ne_bytes(addr.octets()) };
726 IN_ADDR { S_un: s_un }
727 }
728
from_in_addr(in_addr: IN_ADDR) -> Ipv4Addr729 pub(crate) fn from_in_addr(in_addr: IN_ADDR) -> Ipv4Addr {
730 Ipv4Addr::from(unsafe { *in_addr.S_un.S_addr() }.to_ne_bytes())
731 }
732
to_in6_addr(addr: &Ipv6Addr) -> in6_addr733 pub(crate) fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr {
734 let mut ret_addr: in6_addr_u = unsafe { mem::zeroed() };
735 unsafe { *(ret_addr.Byte_mut()) = addr.octets() };
736 let mut ret: in6_addr = unsafe { mem::zeroed() };
737 ret.u = ret_addr;
738 ret
739 }
740
from_in6_addr(addr: in6_addr) -> Ipv6Addr741 pub(crate) fn from_in6_addr(addr: in6_addr) -> Ipv6Addr {
742 Ipv6Addr::from(*unsafe { addr.u.Byte() })
743 }
744
to_mreqn( multiaddr: &Ipv4Addr, interface: &crate::socket::InterfaceIndexOrAddress, ) -> IpMreq745 pub(crate) fn to_mreqn(
746 multiaddr: &Ipv4Addr,
747 interface: &crate::socket::InterfaceIndexOrAddress,
748 ) -> IpMreq {
749 IpMreq {
750 imr_multiaddr: to_in_addr(multiaddr),
751 // Per https://docs.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-ip_mreq#members:
752 //
753 // imr_interface
754 //
755 // The local IPv4 address of the interface or the interface index on
756 // which the multicast group should be joined or dropped. This value is
757 // in network byte order. If this member specifies an IPv4 address of
758 // 0.0.0.0, the default IPv4 multicast interface is used.
759 //
760 // To use an interface index of 1 would be the same as an IP address of
761 // 0.0.0.1.
762 imr_interface: match interface {
763 crate::socket::InterfaceIndexOrAddress::Index(interface) => {
764 to_in_addr(&(*interface).into())
765 }
766 crate::socket::InterfaceIndexOrAddress::Address(interface) => to_in_addr(interface),
767 },
768 }
769 }
770
771 /// Windows only API.
772 impl crate::Socket {
773 /// Sets `HANDLE_FLAG_INHERIT` using `SetHandleInformation`.
774 #[cfg(feature = "all")]
775 #[cfg_attr(docsrs, doc(cfg(all(windows, feature = "all"))))]
set_no_inherit(&self, no_inherit: bool) -> io::Result<()>776 pub fn set_no_inherit(&self, no_inherit: bool) -> io::Result<()> {
777 self._set_no_inherit(no_inherit)
778 }
779
_set_no_inherit(&self, no_inherit: bool) -> io::Result<()>780 pub(crate) fn _set_no_inherit(&self, no_inherit: bool) -> io::Result<()> {
781 // NOTE: can't use `syscall!` because it expects the function in the
782 // `sock::` path.
783 let res = unsafe {
784 SetHandleInformation(
785 self.as_raw() as HANDLE,
786 winbase::HANDLE_FLAG_INHERIT,
787 !no_inherit as _,
788 )
789 };
790 if res == 0 {
791 // Zero means error.
792 Err(io::Error::last_os_error())
793 } else {
794 Ok(())
795 }
796 }
797 }
798
799 impl AsRawSocket for crate::Socket {
as_raw_socket(&self) -> RawSocket800 fn as_raw_socket(&self) -> RawSocket {
801 self.as_raw() as RawSocket
802 }
803 }
804
805 impl IntoRawSocket for crate::Socket {
into_raw_socket(self) -> RawSocket806 fn into_raw_socket(self) -> RawSocket {
807 self.into_raw() as RawSocket
808 }
809 }
810
811 impl FromRawSocket for crate::Socket {
from_raw_socket(socket: RawSocket) -> crate::Socket812 unsafe fn from_raw_socket(socket: RawSocket) -> crate::Socket {
813 crate::Socket::from_raw(socket as Socket)
814 }
815 }
816
817 #[test]
in_addr_convertion()818 fn in_addr_convertion() {
819 let ip = Ipv4Addr::new(127, 0, 0, 1);
820 let raw = to_in_addr(&ip);
821 assert_eq!(unsafe { *raw.S_un.S_addr() }, 127 << 0 | 1 << 24);
822 assert_eq!(from_in_addr(raw), ip);
823
824 let ip = Ipv4Addr::new(127, 34, 4, 12);
825 let raw = to_in_addr(&ip);
826 assert_eq!(
827 unsafe { *raw.S_un.S_addr() },
828 127 << 0 | 34 << 8 | 4 << 16 | 12 << 24
829 );
830 assert_eq!(from_in_addr(raw), ip);
831 }
832
833 #[test]
in6_addr_convertion()834 fn in6_addr_convertion() {
835 let ip = Ipv6Addr::new(0x2000, 1, 2, 3, 4, 5, 6, 7);
836 let raw = to_in6_addr(&ip);
837 let want = [
838 0x2000u16.to_be(),
839 1u16.to_be(),
840 2u16.to_be(),
841 3u16.to_be(),
842 4u16.to_be(),
843 5u16.to_be(),
844 6u16.to_be(),
845 7u16.to_be(),
846 ];
847 assert_eq!(unsafe { *raw.u.Word() }, want);
848 assert_eq!(from_in6_addr(raw), ip);
849 }
850