windows_namespace_request_sys/query.rs
1// Copyright (c) Mike Grier.
2
3//! The `GetFileInformationByHandleEx` entry.
4//!
5//! Entry 5 of the audited catalogue, and the most-called namespace operation
6//! across all three audited consumers.
7//!
8//! # Why it is here despite being trivial to marshal
9//!
10//! This entry needs almost no marshaling work: its inputs are a handle, a
11//! scalar class, and a buffer size, with no pointer into caller memory
12//! anywhere. That invites the conclusion that it does not belong in a catalogue
13//! at all. Membership is decided by whether a **blocking** namespace call needs
14//! performing off the caller's thread, not by whether it is awkward to marshal
15//! -- the latter test would select for our implementation convenience rather
16//! than for consumer need. On the former test this is the call whose lack of an
17//! overlapped form is why an unassociated handle had to become a first-class
18//! destination at all.
19//!
20//! # This returns bytes, and does not parse them
21//!
22//! The audited classes have two result shapes -- fixed-size out-parameters and
23//! variable-length batches -- and both collapse to one owned buffer here,
24//! because this crate returns bytes plus the unaltered outcome. Per-class
25//! parsing stays with the consumer that already owns it.
26//!
27//! Two constraints on that buffer are not negotiable:
28//!
29//! - It must be **8-byte aligned**. A `Vec<u8>` guarantees byte alignment and
30//! nothing more, and a misaligned batch is not a subtle problem: the very
31//! first query fails with `ERROR_NOACCESS`. [`AlignedBuffer`] states the
32//! alignment rather than arriving at it by luck.
33//! - The call **reports no written length**. A batch is walked by its own
34//! next-entry offsets, so the whole buffer comes back and the consumer bounds
35//! its own reads, rather than this entry inventing a byte count it cannot
36//! know.
37//!
38//! # Only two classes touch the enumeration cursor
39//!
40//! Measured on Windows 11 Enterprise 10.0.28000, `aarch64-pc-windows-msvc`,
41//! against a real directory with a deliberately small buffer:
42//!
43//! | Question | Measured |
44//! |---|---|
45//! | Does a duplicated handle share the enumeration cursor? | **Yes** -- a clean continuation |
46//! | Control: do two separate opens share it? | **No** -- the second restarts |
47//! | Does closing the duplicate disturb the source? | **No** |
48//! | Does an interleaved `FileBasicInfo`, `FileIdInfo`, or non-`Ex` query disturb it? | **No** |
49//!
50//! So the contract is narrower than "handle-taking entries are hazardous":
51//! **only the two directory-enumeration classes mutate the shared cursor**, and
52//! every other query is a pure read that composes freely with an enumeration in
53//! progress, on the same handle or on a duplicate. What follows is specific --
54//! a duplicate is *not* an independent enumeration, and an independent
55//! traversal needs a fresh open.
56//!
57//! # This is single-shot, and is not a streaming engine
58//!
59//! An entry covering the two directory classes otherwise looks like a second
60//! implementation of a shipped streaming enumerator. It is not. This entry is
61//! **single-shot**: one call, one batch, and the *client* sequences the next,
62//! which is the one-entry-per-Win32-call rule applied literally. A consumer
63//! wanting streaming enumeration -- with the cursor, refill loop, quanta, and
64//! backpressure owned for it -- wants
65//! [windows-file-enumeration-sys](https://docs.rs/windows-file-enumeration-sys)
66//! and should not rebuild that loop out of single-shot calls.
67//!
68//! All five audited classes stay reachable here regardless, because restricting
69//! them would narrow the entry for a no-consumer reason.
70//!
71//! # No ambient context is needed
72//!
73//! Access was checked at the open. That is exactly why the enumeration crate
74//! applies impersonation only around `CreateFileW`, and it makes this the
75//! clearest case that a request and a context are **paired at submission**
76//! rather than fused.
77
78use windows_sys::Win32::Storage::FileSystem::{
79 FILE_INFO_BY_HANDLE_CLASS, FileBasicInfo, FileCaseSensitiveInfo, FileIdExtdDirectoryInfo,
80 FileIdExtdDirectoryRestartInfo, FileIdInfo, GetFileInformationByHandleEx,
81};
82
83use crate::buffer::AlignedBuffer;
84use crate::handle::{CapturedHandle, HandleCaptureError};
85use crate::outcome::{Outcome, perform_bool};
86
87/// The alignment a directory-information batch requires.
88///
89/// A `FILE_ID_EXTD_DIR_INFO` contains `i64` fields and the API keeps every
90/// record in a batch on an 8-byte boundary -- but only if the batch itself
91/// starts on one. Changing this value is a breaking change.
92const BATCH_ALIGNMENT: usize = align_of::<u64>();
93
94/// Which information the query asks for.
95///
96/// A newtype over `FILE_INFO_BY_HANDLE_CLASS` rather than an enum, because
97/// Windows defines classes this crate has never heard of and refusing them
98/// would narrow the entry. The named constants are the five the audit found;
99/// any other class reaches Windows unaltered through [`from_raw`](Self::from_raw).
100///
101/// # Example
102///
103/// ```
104/// use windows_namespace_request_sys::query::FileInformationClass;
105/// use windows_sys::Win32::Storage::FileSystem::{FileBasicInfo, FileStandardInfo};
106///
107/// assert_eq!(FileInformationClass::BASIC.as_raw(), FileBasicInfo);
108///
109/// // A class with no named constant here is still expressible.
110/// let standard = FileInformationClass::from_raw(FileStandardInfo);
111/// assert_eq!(standard.as_raw(), FileStandardInfo);
112/// ```
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114pub struct FileInformationClass(FILE_INFO_BY_HANDLE_CLASS);
115
116impl FileInformationClass {
117 /// `FileBasicInfo`: timestamps and attributes. A pure read.
118 pub const BASIC: Self = Self(FileBasicInfo);
119 /// `FileIdInfo`: the volume serial and 128-bit file id. A pure read.
120 pub const ID: Self = Self(FileIdInfo);
121 /// `FileCaseSensitiveInfo`: whether the directory is case-sensitive. A pure
122 /// read.
123 pub const CASE_SENSITIVE: Self = Self(FileCaseSensitiveInfo);
124 /// `FileIdExtdDirectoryInfo`: the next batch of directory entries.
125 ///
126 /// **Advances the enumeration cursor**, which lives in the file object and
127 /// is therefore shared with every duplicate of the handle.
128 pub const ID_EXTD_DIRECTORY: Self = Self(FileIdExtdDirectoryInfo);
129 /// `FileIdExtdDirectoryRestartInfo`: the first batch, restarting the
130 /// enumeration.
131 ///
132 /// **Resets the enumeration cursor**, with the same sharing consequence.
133 pub const ID_EXTD_DIRECTORY_RESTART: Self = Self(FileIdExtdDirectoryRestartInfo);
134
135 /// Wraps a raw `FILE_INFO_BY_HANDLE_CLASS`.
136 #[must_use]
137 pub const fn from_raw(class: FILE_INFO_BY_HANDLE_CLASS) -> Self {
138 Self(class)
139 }
140
141 /// The raw class value.
142 #[must_use]
143 pub const fn as_raw(self) -> FILE_INFO_BY_HANDLE_CLASS {
144 self.0
145 }
146
147 /// Whether this class mutates the handle's shared enumeration cursor.
148 ///
149 /// True only for the two directory-enumeration classes. Every other class
150 /// is a pure read that composes freely with an enumeration in progress,
151 /// measured rather than assumed.
152 ///
153 /// An unrecognised class reports `false`, because this answers "is this one
154 /// of the two known cursor-moving classes", not "is this provably safe".
155 ///
156 /// # Example
157 ///
158 /// ```
159 /// use windows_namespace_request_sys::query::FileInformationClass;
160 ///
161 /// assert!(FileInformationClass::ID_EXTD_DIRECTORY.moves_enumeration_cursor());
162 /// assert!(FileInformationClass::ID_EXTD_DIRECTORY_RESTART.moves_enumeration_cursor());
163 ///
164 /// // Interleaving one of these with an enumeration is safe: measured, not
165 /// // reasoned from the object model.
166 /// assert!(!FileInformationClass::BASIC.moves_enumeration_cursor());
167 /// assert!(!FileInformationClass::ID.moves_enumeration_cursor());
168 /// ```
169 #[must_use]
170 pub const fn moves_enumeration_cursor(self) -> bool {
171 self.0 == FileIdExtdDirectoryInfo || self.0 == FileIdExtdDirectoryRestartInfo
172 }
173}
174
175/// An owned, marshalable parameter set for `GetFileInformationByHandleEx`.
176///
177/// # Example
178///
179/// ```
180/// use std::fs;
181/// use std::os::windows::io::AsHandle;
182///
183/// use windows_namespace_request_sys::query::{FileInformationClass, QueryFileInformation};
184/// use windows_namespace_request_sys::CapturedHandle;
185///
186/// let path = std::env::temp_dir().join(format!("wnrs-q-{}.tmp", std::process::id()));
187/// fs::write(&path, b"example")?;
188/// let file = fs::File::open(&path)?;
189///
190/// let request = QueryFileInformation::new(
191/// CapturedHandle::capture(file.as_handle())?,
192/// FileInformationClass::BASIC,
193/// )
194/// .with_capacity(256);
195///
196/// // The whole buffer comes back: the call reports no written length, so the
197/// // consumer bounds its own reads rather than trusting a count we invented.
198/// let bytes = request.perform()?;
199/// assert_eq!(bytes.len(), 256);
200/// assert_eq!(bytes.as_ptr() as usize % 8, 0);
201/// # drop(file);
202/// # fs::remove_file(&path)?;
203/// # Ok::<(), Box<dyn std::error::Error>>(())
204/// ```
205#[derive(Debug)]
206#[must_use = "an unperformed request queries nothing"]
207pub struct QueryFileInformation {
208 handle: CapturedHandle,
209 class: FileInformationClass,
210 capacity: usize,
211}
212
213impl QueryFileInformation {
214 /// The capacity a request starts with.
215 ///
216 /// Large enough for any of the fixed-size classes and for a useful batch of
217 /// directory entries. A caller enumerating a large directory will want more
218 /// and should say so; this is a starting point, not a recommendation.
219 pub const DEFAULT_CAPACITY: usize = 64 * 1024;
220
221 /// Begins a request against `handle` for `class`.
222 pub fn new(handle: CapturedHandle, class: FileInformationClass) -> Self {
223 Self {
224 handle,
225 class,
226 capacity: Self::DEFAULT_CAPACITY,
227 }
228 }
229
230 /// Sets the buffer size the query is given.
231 ///
232 /// For a fixed-size class this must be at least the size of that class's
233 /// structure, and Windows reports `ERROR_BAD_LENGTH` if it is not. For a
234 /// directory class it bounds how many entries one call can return, and a
235 /// buffer too small for even one entry fails with `ERROR_MORE_DATA` --
236 /// neither is pre-empted here.
237 pub fn with_capacity(mut self, capacity: usize) -> Self {
238 self.capacity = capacity;
239 self
240 }
241
242 /// The owned duplicate of the handle being queried.
243 pub fn handle(&self) -> &CapturedHandle {
244 &self.handle
245 }
246
247 /// The information class this request asks for.
248 #[must_use]
249 pub fn class(&self) -> FileInformationClass {
250 self.class
251 }
252
253 /// The buffer size the query will be given.
254 #[must_use]
255 pub fn capacity(&self) -> usize {
256 self.capacity
257 }
258
259 /// Copies the request, duplicating the handle.
260 ///
261 /// Not `Clone`, because duplicating a handle is fallible. Note that the
262 /// copy shares the original's enumeration cursor, per this module's
263 /// measurements -- it is a second reference, not a second enumeration.
264 ///
265 /// # Errors
266 ///
267 /// Returns the handle-capture failure when the handle cannot be duplicated.
268 pub fn try_clone(&self) -> Result<Self, HandleCaptureError> {
269 Ok(Self {
270 handle: self.handle.try_clone()?,
271 class: self.class,
272 capacity: self.capacity,
273 })
274 }
275
276 /// Performs the query on the calling thread.
277 ///
278 /// Returns the **whole** buffer, 8-byte aligned. The call reports no
279 /// written length -- a batch is walked by its own next-entry offsets -- so
280 /// nothing here invents a byte count it cannot know.
281 ///
282 /// # Errors
283 ///
284 /// Returns the raw Win32 code, unaltered. `ERROR_NO_MORE_FILES` ends a
285 /// directory enumeration and `ERROR_MORE_DATA` means the buffer held no
286 /// complete entry; both are the caller's to interpret.
287 pub fn perform(&self) -> Outcome<AlignedBuffer> {
288 let mut buffer = AlignedBuffer::zeroed(self.capacity, BATCH_ALIGNMENT);
289 let size = u32::try_from(self.capacity).unwrap_or(u32::MAX);
290
291 perform_bool(|| {
292 // SAFETY: the handle is a duplicate this request owns and keeps
293 // open across the call; the buffer is writable for `size` bytes and
294 // 8-byte aligned, which is what the directory classes require.
295 unsafe {
296 GetFileInformationByHandleEx(
297 self.handle.raw(),
298 self.class.as_raw(),
299 buffer.as_mut_ptr().cast(),
300 size,
301 )
302 }
303 })?;
304
305 Ok(buffer)
306 }
307}
308
309impl crate::request::Request for QueryFileInformation {
310 type Error = crate::Win32Error;
311 type Output = AlignedBuffer;
312
313 fn perform(&self) -> Outcome<AlignedBuffer> {
314 Self::perform(self)
315 }
316}
317
318#[cfg(test)]
319mod tests;