Debian Codegraph @

src/iocp/afd.rs

raw symbols SCIP
1 //! Safe wrapper around \Device\Afd
2
3 use super::port::{Completion, CompletionHandle};
4
5 use std::cell::UnsafeCell;
6 use std::fmt;
7 use std::io;
8 use std::marker::{PhantomData, PhantomPinned};
9 use std::mem::{self, size_of, transmute, MaybeUninit};
10 use std::ops;
11 use std::os::windows::prelude::{AsRawHandle, RawHandle, RawSocket};
12 use std::pin::Pin;
13 use std::ptr;
14 use std::sync::atomic::{AtomicBool, Ordering};
15 use std::sync::OnceLock;
16
17 use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
18 use windows_sys::Wdk::Storage::FileSystem::FILE_OPEN;
19 use windows_sys::Win32::Foundation::{
20 CloseHandle, HANDLE, HMODULE, NTSTATUS, STATUS_NOT_FOUND, STATUS_PENDING, STATUS_SUCCESS,
21 UNICODE_STRING,
22 };
23 use windows_sys::Win32::Networking::WinSock::{
24 WSAIoctl, SIO_BASE_HANDLE, SIO_BSP_HANDLE_POLL, SOCKET_ERROR,
25 };
26 use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE, SYNCHRONIZE};
27 use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
28 use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
29
30 #[derive(Default)]
31 #[repr(C)]
32 pub(super) struct AfdPollInfo {
33 /// The timeout for this poll.
34 timeout: i64,
35
36 /// The number of handles being polled.
37 handle_count: u32,
38
39 /// Whether or not this poll is exclusive for this handle.
40 exclusive: u32,
41
42 /// The handles to poll.
43 handles: [AfdPollHandleInfo; 1],
44 }
45
46 #[repr(C)]
47 struct AfdPollHandleInfo {
48 /// The handle to poll.
49 handle: HANDLE,
50
51 /// The events to poll for.
52 events: AfdPollMask,
53
54 /// The status of the poll.
55 status: NTSTATUS,
56 }
57
58 impl Default for AfdPollHandleInfo {
59 fn default() -> Self {
60 Self {
61 handle: ptr::null_mut(),
62 events: Default::default(),
63 status: Default::default(),
64 }
65 }
66 }
67
68 impl AfdPollInfo {
69 pub(super) fn handle_count(&self) -> u32 {
70 self.handle_count
71 }
72
73 pub(super) fn events(&self) -> AfdPollMask {
74 self.handles[0].events
75 }
76 }
77
78 #[derive(Default, Copy, Clone, PartialEq, Eq)]
79 #[repr(transparent)]
80 pub(super) struct AfdPollMask(u32);
81
82 impl AfdPollMask {
83 pub(crate) const RECEIVE: AfdPollMask = AfdPollMask(0x001);
84 pub(crate) const RECEIVE_EXPEDITED: AfdPollMask = AfdPollMask(0x002);
85 pub(crate) const SEND: AfdPollMask = AfdPollMask(0x004);
86 pub(crate) const DISCONNECT: AfdPollMask = AfdPollMask(0x008);
87 pub(crate) const ABORT: AfdPollMask = AfdPollMask(0x010);
88 pub(crate) const LOCAL_CLOSE: AfdPollMask = AfdPollMask(0x020);
89 pub(crate) const ACCEPT: AfdPollMask = AfdPollMask(0x080);
90 pub(crate) const CONNECT_FAIL: AfdPollMask = AfdPollMask(0x100);
91
92 /// Creates an empty mask.
93 pub(crate) const fn empty() -> AfdPollMask {
94 AfdPollMask(0)
95 }
96
97 /// Checks if this mask contains the other mask.
98 pub(crate) fn intersects(self, other: AfdPollMask) -> bool {
99 (self.0 & other.0) != 0
100 }
101
102 /// Sets a flag.
103 pub(crate) fn set(&mut self, other: AfdPollMask, value: bool) {
104 if value {
105 *self |= other;
106 } else {
107 self.0 &= !other.0;
108 }
109 }
110 }
111
112 impl fmt::Debug for AfdPollMask {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 const FLAGS: &[(&str, AfdPollMask)] = &[
115 ("RECEIVE", AfdPollMask::RECEIVE),
116 ("RECEIVE_EXPEDITED", AfdPollMask::RECEIVE_EXPEDITED),
117 ("SEND", AfdPollMask::SEND),
118 ("DISCONNECT", AfdPollMask::DISCONNECT),
119 ("ABORT", AfdPollMask::ABORT),
120 ("LOCAL_CLOSE", AfdPollMask::LOCAL_CLOSE),
121 ("ACCEPT", AfdPollMask::ACCEPT),
122 ("CONNECT_FAIL", AfdPollMask::CONNECT_FAIL),
123 ];
124
125 let mut first = true;
126 for (name, value) in FLAGS {
127 if self.intersects(*value) {
128 if !first {
129 write!(f, " | ")?;
130 }
131
132 first = false;
133 write!(f, "{name}")?;
134 }
135 }
136
137 Ok(())
138 }
139 }
140
141 impl ops::BitOr for AfdPollMask {
142 type Output = Self;
143
144 fn bitor(self, rhs: Self) -> Self {
145 AfdPollMask(self.0 | rhs.0)
146 }
147 }
148
149 impl ops::BitOrAssign for AfdPollMask {
150 fn bitor_assign(&mut self, rhs: Self) {
151 self.0 |= rhs.0;
152 }
153 }
154
155 impl ops::BitAnd for AfdPollMask {
156 type Output = Self;
157
158 fn bitand(self, rhs: Self) -> Self {
159 AfdPollMask(self.0 & rhs.0)
160 }
161 }
162
163 impl ops::BitAndAssign for AfdPollMask {
164 fn bitand_assign(&mut self, rhs: Self) {
165 self.0 &= rhs.0;
166 }
167 }
168
169 pub(super) trait HasAfdInfo {
170 fn afd_info(self: Pin<&Self>) -> Pin<&UnsafeCell<AfdPollInfo>>;
171 }
172
173 macro_rules! define_ntdll_import {
174 (
175 $(
176 $(#[$attr:meta])*
177 fn $name:ident($($arg:ident: $arg_ty:ty),*) -> $ret:ty;
178 )*
179 ) => {
180 /// Imported functions from ntdll.dll.
181 #[allow(non_snake_case)]
182 pub(super) struct NtdllImports {
183 $(
184 $(#[$attr])*
185 $name: unsafe extern "system" fn($($arg_ty),*) -> $ret,
186 )*
187 }
188
189 #[allow(non_snake_case)]
190 impl NtdllImports {
191 unsafe fn load(ntdll: HMODULE) -> io::Result<Self> {
192 $(
193 #[allow(clippy::missing_transmute_annotations)]
194 let $name = {
195 const NAME: &str = concat!(stringify!($name), "\0");
196 let addr = GetProcAddress(ntdll, NAME.as_ptr() as *const _);
197
198 let addr = match addr {
199 Some(addr) => addr,
200 None => {
201 #[cfg(feature = "tracing")]
202 tracing::error!("Failed to load ntdll function {}", NAME);
203 return Err(io::Error::last_os_error());
204 },
205 };
206
207 transmute::<_, unsafe extern "system" fn($($arg_ty),*) -> $ret>(addr)
208 };
209 )*
210
211 Ok(Self {
212 $(
213 $name,
214 )*
215 })
216 }
217
218 $(
219 $(#[$attr])*
220 unsafe fn $name(&self, $($arg: $arg_ty),*) -> $ret {
221 (self.$name)($($arg),*)
222 }
223 )*
224 }
225 };
226 }
227
228 define_ntdll_import! {
229 /// Cancels an ongoing I/O operation.
230 fn NtCancelIoFileEx(
231 FileHandle: HANDLE,
232 IoRequestToCancel: *mut IO_STATUS_BLOCK,
233 IoStatusBlock: *mut IO_STATUS_BLOCK
234 ) -> NTSTATUS;
235
236 /// Opens or creates a file handle.
237 #[allow(clippy::too_many_arguments)]
238 fn NtCreateFile(
239 FileHandle: *mut HANDLE,
240 DesiredAccess: u32,
241 ObjectAttributes: *mut OBJECT_ATTRIBUTES,
242 IoStatusBlock: *mut IO_STATUS_BLOCK,
243 AllocationSize: *mut i64,
244 FileAttributes: u32,
245 ShareAccess: u32,
246 CreateDisposition: u32,
247 CreateOptions: u32,
248 EaBuffer: *mut (),
249 EaLength: u32
250 ) -> NTSTATUS;
251
252 /// Runs an I/O control on a file handle.
253 ///
254 /// Practically equivalent to `ioctl`.
255 #[allow(clippy::too_many_arguments)]
256 fn NtDeviceIoControlFile(
257 FileHandle: HANDLE,
258 Event: HANDLE,
259 ApcRoutine: *mut (),
260 ApcContext: *mut (),
261 IoStatusBlock: *mut IO_STATUS_BLOCK,
262 IoControlCode: u32,
263 InputBuffer: *mut (),
264 InputBufferLength: u32,
265 OutputBuffer: *mut (),
266 OutputBufferLength: u32
267 ) -> NTSTATUS;
268
269 /// Converts `NTSTATUS` to a DOS error code.
270 fn RtlNtStatusToDosError(
271 Status: NTSTATUS
272 ) -> u32;
273 }
274
275 impl NtdllImports {
276 fn get() -> io::Result<&'static Self> {
277 macro_rules! s {
278 ($e:expr) => {{
279 $e as u16
280 }};
281 }
282
283 // ntdll.dll
284 static NTDLL_NAME: &[u16] = &[
285 s!('n'),
286 s!('t'),
287 s!('d'),
288 s!('l'),
289 s!('l'),
290 s!('.'),
291 s!('d'),
292 s!('l'),
293 s!('l'),
294 s!('\0'),
295 ];
296 static NTDLL_IMPORTS: OnceLock<io::Result<NtdllImports>> = OnceLock::new();
297
298 NTDLL_IMPORTS
299 .get_or_init(|| unsafe {
300 let ntdll = GetModuleHandleW(NTDLL_NAME.as_ptr() as *const _);
301
302 if ntdll.is_null() {
303 #[cfg(feature = "tracing")]
304 tracing::error!("Failed to load ntdll.dll");
305 return Err(io::Error::last_os_error());
306 }
307
308 NtdllImports::load(ntdll)
309 })
310 .as_ref()
311 .map_err(|e| io::Error::from(e.kind()))
312 }
313
314 pub(super) fn force_load() -> io::Result<()> {
315 Self::get()?;
316 Ok(())
317 }
318 }
319
320 /// The handle to the AFD device.
321 pub(super) struct Afd<T> {
322 /// The handle to the AFD device.
323 handle: HANDLE,
324
325 /// We own `T`.
326 _marker: PhantomData<T>,
327 }
328
329 impl<T> fmt::Debug for Afd<T> {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 struct WriteAsHex(HANDLE);
332
333 impl fmt::Debug for WriteAsHex {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 write!(f, "{:010x}", self.0 as usize)
336 }
337 }
338
339 f.debug_struct("Afd")
340 .field("handle", &WriteAsHex(self.handle))
341 .finish()
342 }
343 }
344
345 impl<T> Drop for Afd<T> {
346 fn drop(&mut self) {
347 unsafe {
348 CloseHandle(self.handle);
349 }
350 }
351 }
352
353 impl<T> AsRawHandle for Afd<T> {
354 fn as_raw_handle(&self) -> RawHandle {
355 self.handle as _
356 }
357 }
358
359 impl<T: CompletionHandle> Afd<T>
360 where
361 T::Completion: AsIoStatusBlock + HasAfdInfo,
362 {
363 /// Create a new AFD device.
364 pub(super) fn new() -> io::Result<Self> {
365 macro_rules! s {
366 ($e:expr) => {
367 ($e) as u16
368 };
369 }
370
371 /// \Device\Afd\Smol
372 const AFD_NAME: &[u16] = &[
373 s!('\\'),
374 s!('D'),
375 s!('e'),
376 s!('v'),
377 s!('i'),
378 s!('c'),
379 s!('e'),
380 s!('\\'),
381 s!('A'),
382 s!('f'),
383 s!('d'),
384 s!('\\'),
385 s!('S'),
386 s!('m'),
387 s!('o'),
388 s!('l'),
389 s!('\0'),
390 ];
391
392 // Set up device attributes.
393 let mut device_name = UNICODE_STRING {
394 Length: mem::size_of_val(AFD_NAME) as u16,
395 MaximumLength: mem::size_of_val(AFD_NAME) as u16,
396 Buffer: AFD_NAME.as_ptr() as *mut _,
397 };
398 let mut device_attributes = OBJECT_ATTRIBUTES {
399 Length: size_of::<OBJECT_ATTRIBUTES>() as u32,
400 RootDirectory: ptr::null_mut(),
401 ObjectName: &mut device_name,
402 Attributes: 0,
403 SecurityDescriptor: ptr::null_mut(),
404 SecurityQualityOfService: ptr::null_mut(),
405 };
406
407 let mut handle = MaybeUninit::<HANDLE>::uninit();
408 let mut iosb = MaybeUninit::<IO_STATUS_BLOCK>::zeroed();
409 let ntdll = NtdllImports::get()?;
410
411 let result = unsafe {
412 ntdll.NtCreateFile(
413 handle.as_mut_ptr(),
414 SYNCHRONIZE,
415 &mut device_attributes,
416 iosb.as_mut_ptr(),
417 ptr::null_mut(),
418 0,
419 FILE_SHARE_READ | FILE_SHARE_WRITE,
420 FILE_OPEN,
421 0,
422 ptr::null_mut(),
423 0,
424 )
425 };
426
427 if result != STATUS_SUCCESS {
428 let real_code = unsafe { ntdll.RtlNtStatusToDosError(result) };
429
430 return Err(io::Error::from_raw_os_error(real_code as i32));
431 }
432
433 let handle = unsafe { handle.assume_init() };
434
435 Ok(Self {
436 handle,
437 _marker: PhantomData,
438 })
439 }
440
441 /// Begin polling with the provided handle.
442 pub(super) fn poll(
443 &self,
444 packet: T,
445 base_socket: RawSocket,
446 afd_events: AfdPollMask,
447 ) -> io::Result<()> {
448 const IOCTL_AFD_POLL: u32 = 0x00012024;
449
450 // Lock the packet.
451 if !packet.get().try_lock() {
452 return Err(io::Error::new(
453 io::ErrorKind::WouldBlock,
454 "packet is already in use",
455 ));
456 }
457
458 // Set up the AFD poll info.
459 let poll_info = unsafe {
460 let poll_info = Pin::into_inner_unchecked(packet.get().afd_info()).get();
461
462 // Initialize the AFD poll info.
463 (*poll_info).exclusive = false.into();
464 (*poll_info).handle_count = 1;
465 (*poll_info).timeout = i64::MAX;
466 (*poll_info).handles[0].handle = base_socket as HANDLE;
467 (*poll_info).handles[0].status = 0;
468 (*poll_info).handles[0].events = afd_events;
469
470 poll_info
471 };
472
473 let iosb = T::into_ptr(packet).cast::<IO_STATUS_BLOCK>();
474 // Set Status to pending
475 unsafe {
476 (*iosb).Anonymous.Status = STATUS_PENDING;
477 }
478
479 let ntdll = NtdllImports::get()?;
480 let result = unsafe {
481 ntdll.NtDeviceIoControlFile(
482 self.handle,
483 ptr::null_mut(),
484 ptr::null_mut(),
485 iosb.cast(),
486 iosb.cast(),
487 IOCTL_AFD_POLL,
488 poll_info.cast(),
489 size_of::<AfdPollInfo>() as u32,
490 poll_info.cast(),
491 size_of::<AfdPollInfo>() as u32,
492 )
493 };
494
495 match result {
496 STATUS_SUCCESS => Ok(()),
497 STATUS_PENDING => Err(io::ErrorKind::WouldBlock.into()),
498 status => {
499 let real_code = unsafe { ntdll.RtlNtStatusToDosError(status) };
500
501 Err(io::Error::from_raw_os_error(real_code as i32))
502 }
503 }
504 }
505
506 /// Cancel an ongoing poll operation.
507 ///
508 /// # Safety
509 ///
510 /// The poll operation must currently be in progress for this AFD.
511 pub(super) unsafe fn cancel(&self, packet: &T) -> io::Result<()> {
512 let ntdll = NtdllImports::get()?;
513
514 let result = {
515 // First, check if the packet is still in use.
516 let iosb = packet.as_ptr().cast::<IO_STATUS_BLOCK>();
517
518 if (*iosb).Anonymous.Status != STATUS_PENDING {
519 return Ok(());
520 }
521
522 // Cancel the packet.
523 let mut cancel_iosb = MaybeUninit::<IO_STATUS_BLOCK>::zeroed();
524
525 ntdll.NtCancelIoFileEx(self.handle, iosb, cancel_iosb.as_mut_ptr())
526 };
527
528 if result == STATUS_SUCCESS || result == STATUS_NOT_FOUND {
529 Ok(())
530 } else {
531 let real_code = ntdll.RtlNtStatusToDosError(result);
532
533 Err(io::Error::from_raw_os_error(real_code as i32))
534 }
535 }
536 }
537
538 pin_project_lite::pin_project! {
539 /// An I/O status block paired with some auxiliary data.
540 #[repr(C)]
541 pub(super) struct IoStatusBlock<T> {
542 // The I/O status block.
543 iosb: UnsafeCell<IO_STATUS_BLOCK>,
544
545 // Whether or not the block is in use.
546 in_use: AtomicBool,
547
548 // The auxiliary data.
549 #[pin]
550 data: T,
551
552 // This block is not allowed to move.
553 #[pin]
554 _marker: PhantomPinned,
555 }
556 }
557
558 impl<T: fmt::Debug> fmt::Debug for IoStatusBlock<T> {
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560 f.debug_struct("IoStatusBlock")
561 .field("iosb", &"..")
562 .field("in_use", &self.in_use)
563 .field("data", &self.data)
564 .finish()
565 }
566 }
567
568 unsafe impl<T: Send> Send for IoStatusBlock<T> {}
569 unsafe impl<T: Sync> Sync for IoStatusBlock<T> {}
570
571 impl<T> From<T> for IoStatusBlock<T> {
572 fn from(data: T) -> Self {
573 Self {
574 iosb: UnsafeCell::new(unsafe { std::mem::zeroed() }),
575 in_use: AtomicBool::new(false),
576 data,
577 _marker: PhantomPinned,
578 }
579 }
580 }
581
582 impl<T> IoStatusBlock<T> {
583 pub(super) fn iosb(self: Pin<&Self>) -> &UnsafeCell<IO_STATUS_BLOCK> {
584 self.project_ref().iosb
585 }
586
587 pub(super) fn data(self: Pin<&Self>) -> Pin<&T> {
588 self.project_ref().data
589 }
590 }
591
592 impl<T: HasAfdInfo> HasAfdInfo for IoStatusBlock<T> {
593 fn afd_info(self: Pin<&Self>) -> Pin<&UnsafeCell<AfdPollInfo>> {
594 self.project_ref().data.afd_info()
595 }
596 }
597
598 /// Can be transmuted to an I/O status block.
599 ///
600 /// # Safety
601 ///
602 /// A pointer to `T` must be able to be converted to a pointer to `IO_STATUS_BLOCK`
603 /// without any issues.
604 pub(super) unsafe trait AsIoStatusBlock {}
605
606 unsafe impl<T> AsIoStatusBlock for IoStatusBlock<T> {}
607 unsafe impl<T> Completion for IoStatusBlock<T> {
608 fn try_lock(self: Pin<&Self>) -> bool {
609 !self.in_use.swap(true, Ordering::SeqCst)
610 }
611
612 unsafe fn unlock(self: Pin<&Self>) {
613 self.in_use.store(false, Ordering::SeqCst);
614 }
615 }
616
617 /// Get the base socket associated with a socket.
618 pub(super) fn base_socket(sock: RawSocket) -> io::Result<RawSocket> {
619 // First, try the SIO_BASE_HANDLE ioctl.
620 let result = unsafe { try_socket_ioctl(sock, SIO_BASE_HANDLE) };
621
622 match result {
623 Ok(sock) => return Ok(sock),
624 Err(e) if e.kind() == io::ErrorKind::InvalidInput => return Err(e),
625 Err(_) => {}
626 }
627
628 // Some poorly coded LSPs may not handle SIO_BASE_HANDLE properly, but in some cases may
629 // handle SIO_BSP_HANDLE_POLL better. Try that.
630 let result = unsafe { try_socket_ioctl(sock, SIO_BSP_HANDLE_POLL)? };
631 if result == sock {
632 return Err(io::Error::from(io::ErrorKind::InvalidInput));
633 }
634
635 // Try `SIO_BASE_HANDLE` again, in case the LSP fixed itself.
636 unsafe { try_socket_ioctl(result, SIO_BASE_HANDLE) }
637 }
638
639 /// Run an IOCTL on a socket and return a socket.
640 ///
641 /// # Safety
642 ///
643 /// The `ioctl` parameter must be a valid I/O control that returns a valid socket.
644 unsafe fn try_socket_ioctl(sock: RawSocket, ioctl: u32) -> io::Result<RawSocket> {
645 let mut out = MaybeUninit::<RawSocket>::uninit();
646 let mut bytes = 0u32;
647
648 let result = WSAIoctl(
649 sock as _,
650 ioctl,
651 ptr::null_mut(),
652 0,
653 out.as_mut_ptr().cast(),
654 size_of::<RawSocket>() as u32,
655 &mut bytes,
656 ptr::null_mut(),
657 None,
658 );
659
660 if result == SOCKET_ERROR {
661 return Err(io::Error::last_os_error());
662 }
663
664 Ok(out.assume_init())
665 }