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::sys::c;
12use crate::sys::pal::winsock::last_error;
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 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 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 #[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
114pub use crate::sys::pal::winsock::{cvt, cvt_gai, cvt_r, startup as init};
115
116#[expect(missing_debug_implementations)]
117pub struct Socket(OwnedSocket);
118
119impl Socket {
120 pub fn new(family: c_int, ty: c_int) -> io::Result<Socket> {
121 let socket = unsafe {
122 c::WSASocketW(
123 family,
124 ty,
125 0,
126 ptr::null_mut(),
127 0,
128 c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
129 )
130 };
131
132 if socket != c::INVALID_SOCKET {
133 unsafe { Ok(Self::from_raw(socket)) }
134 } else {
135 let error = unsafe { c::WSAGetLastError() };
136
137 if error != c::WSAEPROTOTYPE && error != c::WSAEINVAL {
138 return Err(io::Error::from_raw_os_error(error));
139 }
140
141 let socket =
142 unsafe { c::WSASocketW(family, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) };
143
144 if socket == c::INVALID_SOCKET {
145 return Err(last_error());
146 }
147
148 unsafe {
149 let socket = Self::from_raw(socket);
150 socket.0.set_no_inherit()?;
151 Ok(socket)
152 }
153 }
154 }
155
156 pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
157 let (addr, len) = socket_addr_to_c(addr);
158 let result = unsafe { c::connect(self.as_raw(), addr.as_ptr(), len) };
159 cvt(result).map(drop)
160 }
161
162 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
163 self.set_nonblocking(true)?;
164 let result = self.connect(addr);
165 self.set_nonblocking(false)?;
166
167 match result {
168 Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
169 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
170 return Err(io::Error::ZERO_TIMEOUT);
171 }
172
173 let mut timeout = c::TIMEVAL {
174 tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long,
175 tv_usec: timeout.subsec_micros() as c_long,
176 };
177
178 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
179 timeout.tv_usec = 1;
180 }
181
182 let fds = {
183 let mut fds = unsafe { mem::zeroed::<c::FD_SET>() };
184 fds.fd_count = 1;
185 fds.fd_array[0] = self.as_raw();
186 fds
187 };
188
189 let mut writefds = fds;
190 let mut errorfds = fds;
191
192 let count = {
193 let result = unsafe {
194 c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout)
195 };
196 cvt(result)?
197 };
198
199 match count {
200 0 => Err(io::const_error!(io::ErrorKind::TimedOut, "connection timed out")),
201 _ => {
202 if writefds.fd_count != 1 {
203 if let Some(e) = self.take_error()? {
204 return Err(e);
205 }
206 }
207
208 Ok(())
209 }
210 }
211 }
212 _ => result,
213 }
214 }
215
216 pub fn accept(&self, storage: *mut c::SOCKADDR, len: *mut c_int) -> io::Result<Socket> {
217 let socket = unsafe { c::accept(self.as_raw(), storage, len) };
218
219 match socket {
220 c::INVALID_SOCKET => Err(last_error()),
221 _ => unsafe { Ok(Self::from_raw(socket)) },
222 }
223 }
224
225 pub fn duplicate(&self) -> io::Result<Socket> {
226 Ok(Self(self.0.try_clone()?))
227 }
228
229 fn recv_with_flags(&self, mut buf: BorrowedCursor<'_>, flags: c_int) -> io::Result<()> {
230 let length = cmp::min(buf.capacity(), i32::MAX as usize) as i32;
233 let result =
234 unsafe { c::recv(self.as_raw(), buf.as_mut().as_mut_ptr() as *mut _, length, flags) };
235
236 match result {
237 c::SOCKET_ERROR => {
238 let error = unsafe { c::WSAGetLastError() };
239
240 if error == c::WSAESHUTDOWN {
241 Ok(())
242 } else {
243 Err(io::Error::from_raw_os_error(error))
244 }
245 }
246 _ => {
247 unsafe { buf.advance_unchecked(result as usize) };
248 Ok(())
249 }
250 }
251 }
252
253 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
254 let mut buf = BorrowedBuf::from(buf);
255 self.recv_with_flags(buf.unfilled(), 0)?;
256 Ok(buf.len())
257 }
258
259 pub fn read_buf(&self, buf: BorrowedCursor<'_>) -> io::Result<()> {
260 self.recv_with_flags(buf, 0)
261 }
262
263 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
264 let length = cmp::min(bufs.len(), u32::MAX as usize) as u32;
267 let mut nread = 0;
268 let mut flags = 0;
269 let result = unsafe {
270 c::WSARecv(
271 self.as_raw(),
272 bufs.as_mut_ptr() as *mut c::WSABUF,
273 length,
274 &mut nread,
275 &mut flags,
276 ptr::null_mut(),
277 None,
278 )
279 };
280
281 match result {
282 0 => Ok(nread as usize),
283 _ => {
284 let error = unsafe { c::WSAGetLastError() };
285
286 if error == c::WSAESHUTDOWN {
287 Ok(0)
288 } else {
289 Err(io::Error::from_raw_os_error(error))
290 }
291 }
292 }
293 }
294
295 #[inline]
296 pub fn is_read_vectored(&self) -> bool {
297 true
298 }
299
300 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
301 let mut buf = BorrowedBuf::from(buf);
302 self.recv_with_flags(buf.unfilled(), c::MSG_PEEK)?;
303 Ok(buf.len())
304 }
305
306 fn recv_from_with_flags(
307 &self,
308 buf: &mut [u8],
309 flags: c_int,
310 ) -> io::Result<(usize, SocketAddr)> {
311 let mut storage = unsafe { mem::zeroed::<c::SOCKADDR_STORAGE>() };
312 let mut addrlen = size_of_val(&storage) as netc::socklen_t;
313 let length = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
314
315 let result = unsafe {
318 c::recvfrom(
319 self.as_raw(),
320 buf.as_mut_ptr() as *mut _,
321 length,
322 flags,
323 (&raw mut storage) as *mut _,
324 &mut addrlen,
325 )
326 };
327
328 match result {
329 c::SOCKET_ERROR => {
330 let error = unsafe { c::WSAGetLastError() };
331
332 if error == c::WSAESHUTDOWN {
333 Ok((0, unsafe { socket_addr_from_c(&storage, addrlen as usize)? }))
334 } else {
335 Err(io::Error::from_raw_os_error(error))
336 }
337 }
338 _ => Ok((result as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })),
339 }
340 }
341
342 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
343 self.recv_from_with_flags(buf, 0)
344 }
345
346 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
347 self.recv_from_with_flags(buf, c::MSG_PEEK)
348 }
349
350 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
351 let length = cmp::min(bufs.len(), u32::MAX as usize) as u32;
352 let mut nwritten = 0;
353 let result = unsafe {
354 c::WSASend(
355 self.as_raw(),
356 bufs.as_ptr() as *const c::WSABUF as *mut _,
357 length,
358 &mut nwritten,
359 0,
360 ptr::null_mut(),
361 None,
362 )
363 };
364 cvt(result).map(|_| nwritten as usize)
365 }
366
367 #[inline]
368 pub fn is_write_vectored(&self) -> bool {
369 true
370 }
371
372 pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> {
373 let timeout = match dur {
374 Some(dur) => {
375 let timeout = sys::dur2timeout(dur);
376 if timeout == 0 {
377 return Err(io::Error::ZERO_TIMEOUT);
378 }
379 timeout
380 }
381 None => 0,
382 };
383 unsafe { setsockopt(self, c::SOL_SOCKET, kind, timeout) }
384 }
385
386 pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> {
387 let raw: u32 = unsafe { getsockopt(self, c::SOL_SOCKET, kind)? };
388 if raw == 0 {
389 Ok(None)
390 } else {
391 let secs = raw / 1000;
392 let nsec = (raw % 1000) * 1000000;
393 Ok(Some(Duration::new(secs as u64, nsec as u32)))
394 }
395 }
396
397 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
398 let how = match how {
399 Shutdown::Write => c::SD_SEND,
400 Shutdown::Read => c::SD_RECEIVE,
401 Shutdown::Both => c::SD_BOTH,
402 };
403 let result = unsafe { c::shutdown(self.as_raw(), how) };
404 cvt(result).map(drop)
405 }
406
407 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
408 let mut nonblocking = nonblocking as c_ulong;
409 let result =
410 unsafe { c::ioctlsocket(self.as_raw(), c::FIONBIO as c_int, &mut nonblocking) };
411 cvt(result).map(drop)
412 }
413
414 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
415 let linger = c::LINGER {
416 l_onoff: linger.is_some() as c_ushort,
417 l_linger: linger.unwrap_or_default().as_secs() as c_ushort,
418 };
419
420 unsafe { setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger) }
421 }
422
423 pub fn linger(&self) -> io::Result<Option<Duration>> {
424 let val: c::LINGER = unsafe { getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)? };
425
426 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
427 }
428
429 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
430 unsafe { setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BOOL) }
431 }
432
433 pub fn nodelay(&self) -> io::Result<bool> {
434 let raw: c::BOOL = unsafe { getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)? };
435 Ok(raw != 0)
436 }
437
438 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
439 let raw: c_int = unsafe { getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)? };
440 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
441 }
442
443 pub fn as_raw(&self) -> c::SOCKET {
445 debug_assert_eq!(size_of::<c::SOCKET>(), size_of::<RawSocket>());
446 debug_assert_eq!(align_of::<c::SOCKET>(), align_of::<RawSocket>());
447 self.as_inner().as_raw_socket() as c::SOCKET
448 }
449 pub unsafe fn from_raw(raw: c::SOCKET) -> Self {
450 debug_assert_eq!(size_of::<c::SOCKET>(), size_of::<RawSocket>());
451 debug_assert_eq!(align_of::<c::SOCKET>(), align_of::<RawSocket>());
452 unsafe { Self::from_raw_socket(raw as RawSocket) }
453 }
454}
455
456#[unstable(reason = "not public", issue = "none", feature = "fd_read")]
457impl<'a> Read for &'a Socket {
458 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
459 (**self).read(buf)
460 }
461}
462
463impl AsInner<OwnedSocket> for Socket {
464 #[inline]
465 fn as_inner(&self) -> &OwnedSocket {
466 &self.0
467 }
468}
469
470impl FromInner<OwnedSocket> for Socket {
471 fn from_inner(sock: OwnedSocket) -> Socket {
472 Socket(sock)
473 }
474}
475
476impl IntoInner<OwnedSocket> for Socket {
477 fn into_inner(self) -> OwnedSocket {
478 self.0
479 }
480}
481
482impl AsSocket for Socket {
483 fn as_socket(&self) -> BorrowedSocket<'_> {
484 self.0.as_socket()
485 }
486}
487
488impl AsRawSocket for Socket {
489 fn as_raw_socket(&self) -> RawSocket {
490 self.0.as_raw_socket()
491 }
492}
493
494impl IntoRawSocket for Socket {
495 fn into_raw_socket(self) -> RawSocket {
496 self.0.into_raw_socket()
497 }
498}
499
500impl FromRawSocket for Socket {
501 unsafe fn from_raw_socket(raw_socket: RawSocket) -> Self {
502 unsafe { Self(FromRawSocket::from_raw_socket(raw_socket)) }
503 }
504}