windows_file_watcher/directory.rs
1// Copyright (c) 2026 Mike Grier
2//! The owned directory handle a detailed watch reads from, and the
3//! classification of the ways opening one can fail.
4//!
5//! `ReadDirectoryChangesW` needs a handle opened three specific ways, and all
6//! three are load-bearing rather than stylistic:
7//!
8//! - `FILE_LIST_DIRECTORY` is the access right the read requires.
9//! - `FILE_FLAG_BACKUP_SEMANTICS` is mandatory: without it `CreateFileW` refuses
10//! to open a directory at all, whatever the access mask says.
11//! - `FILE_FLAG_OVERLAPPED` is what makes the handle usable with the thread
12//! pool's I/O completion seam, which is how every read is issued.
13//!
14//! The share mode is deliberately permissive (`READ | WRITE | DELETE`). A watcher
15//! is an observer: holding a directory open must not stop anyone else reading,
16//! writing, renaming, or deleting it. `FILE_SHARE_DELETE` in particular is what
17//! lets the watched directory be removed out from under the watch, which is a
18//! case the fault model must handle rather than prevent.
19//!
20//! Failures are classified rather than surfaced raw, because the retry policy is
21//! driven by the *class* of failure, not the code. See [`OpenFailure`].
22//!
23//! # Directory identity is by file, not by path string
24//!
25//! Two subscriptions can name the same directory through different path strings
26//! -- a trailing separator, a different case, a symlink hop -- and coalescing
27//! (D-6) has to recognise that as *one* directory, not compare spellings. So a
28//! [`DirectoryId`] is computed from the open handle itself
29//! (`GetFileInformationByHandle`'s volume serial number plus file index), which
30//! is stable for as long as the file exists regardless of how it was reached.
31
32use std::os::windows::ffi::OsStringExt;
33use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
34use std::path::{Path, PathBuf};
35
36use wtf_string::Wtf16String;
37
38use windows_sys::Win32::Foundation::{
39 ERROR_DIRECTORY, ERROR_FILE_NOT_FOUND, ERROR_INVALID_FUNCTION, ERROR_INVALID_NAME,
40 ERROR_NOT_SUPPORTED, ERROR_PATH_NOT_FOUND, HANDLE, INVALID_HANDLE_VALUE,
41};
42use windows_sys::Win32::Storage::FileSystem::{
43 BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_CASE_SENSITIVE_INFO,
44 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY, FILE_NAME_NORMALIZED,
45 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileCaseSensitiveInfo,
46 GetFileInformationByHandle, GetFileInformationByHandleEx, GetFinalPathNameByHandleW,
47 GetVolumeInformationByHandleW, OPEN_EXISTING, VOLUME_NAME_DOS,
48};
49
50/// What a failed open means for the retry policy.
51///
52/// The fault model (D-14/D-15) reduces every failure to one of three actions:
53/// retry the open, downgrade to coarse watching, or -- for the two variants
54/// marked permanent below -- neither.
55///
56/// The permanent pair is worth calling out, because D-14 says there is no
57/// terminal *fault* state. That holds: [`NotADirectory`](Self::NotADirectory) and
58/// [`InvalidPath`](Self::InvalidPath) are not faults in the environment, they are
59/// the caller naming something that cannot ever be a watched directory. Retrying
60/// them would spin forever against an input that will never become valid, so they
61/// are reported to the caller instead of entering the retry loop. Every failure
62/// that *is* environmental stays retryable.
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
64pub enum OpenFailure {
65 /// Nothing exists at the path. Retryable: a watch may legitimately be set on
66 /// a path that does not exist yet, or whose directory was just deleted, and
67 /// the monitor waits for it to appear.
68 NotFound,
69 /// Something exists at the path but is not a directory. Permanent for this
70 /// path -- see the note on the enum.
71 NotADirectory,
72 /// The volume or filesystem cannot support `ReadDirectoryChangesW` at all.
73 /// This is the downgrade-to-coarse edge (D-17), handled by the coarse
74 /// fallback rather than reaching here in practice.
75 Unsupported,
76 /// Anything else: sharing violations, exhausted handles, a network path that
77 /// is momentarily unreachable. Retryable with backoff. This is the default
78 /// classification, so an unrecognised error is retried rather than treated as
79 /// fatal, which is what D-14's "no terminal state" requires.
80 Retryable,
81 /// The path cannot be handed to Win32 at all, because it contains an interior
82 /// NUL. Permanent -- see the note on the enum.
83 InvalidPath,
84 /// The open itself succeeded (or was retryable), but the monitor could not
85 /// set up what a retryable subscription needs to keep going -- its retry
86 /// timer failed to be created, vanishingly rare thread-pool resource
87 /// exhaustion. Permanent for this attempt: nothing was registered, so
88 /// nothing would ever fire to retry it.
89 RetryUnavailable,
90}
91
92impl OpenFailure {
93 /// Whether retrying the open could ever succeed.
94 ///
95 /// False only for the caller-input failures and the setup failure; every
96 /// environmental failure is retryable, including unrecognised ones.
97 pub fn is_retryable(self) -> bool {
98 match self {
99 OpenFailure::NotFound | OpenFailure::Unsupported | OpenFailure::Retryable => true,
100 OpenFailure::NotADirectory
101 | OpenFailure::InvalidPath
102 | OpenFailure::RetryUnavailable => false,
103 }
104 }
105}
106
107/// A failed open: the classification that drives policy, plus the underlying OS
108/// error, kept so a diagnostic never loses the original code.
109#[derive(Debug)]
110pub struct OpenError {
111 failure: OpenFailure,
112 source: std::io::Error,
113}
114
115impl OpenError {
116 pub(crate) fn new(failure: OpenFailure, source: std::io::Error) -> Self {
117 Self { failure, source }
118 }
119
120 /// Build an error for a condition detected before or independently of the
121 /// syscall, giving it the OS error code that describes it.
122 pub(crate) fn synthetic(failure: OpenFailure, code: u32) -> Self {
123 Self::new(
124 failure,
125 std::io::Error::from_raw_os_error(
126 i32::try_from(code).expect("a WIN32_ERROR always fits an i32"),
127 ),
128 )
129 }
130
131 /// How this failure should be treated by the retry policy.
132 pub fn failure(&self) -> OpenFailure {
133 self.failure
134 }
135
136 /// The raw code behind this failure (D-79), for a client that wants more
137 /// than the classification.
138 pub fn code(&self) -> FailureCode {
139 win32_code(&self.source)
140 }
141
142 /// This failure's classification and raw code together (D-79).
143 pub(crate) fn detail(&self) -> FaultDetail {
144 FaultDetail {
145 failure: self.failure,
146 code: self.code(),
147 }
148 }
149}
150
151impl std::fmt::Display for OpenError {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 write!(f, "{:?}: {}", self.failure, self.source)
154 }
155}
156
157impl std::error::Error for OpenError {
158 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
159 Some(&self.source)
160 }
161}
162
163/// A Win32 error code or an HRESULT, kept in the currency it actually arrived in
164/// (D-79).
165///
166/// Every failure source in this crate today (`CreateFileW`,
167/// `ReadDirectoryChangesW`, `FindFirstChangeNotificationW`,
168/// `GetVolumeInformationByHandleW`, `ReOpenFile`) is a classic last-error API, so
169/// only [`Win32`](Self::Win32) is produced today -- but a code is kept in
170/// whichever currency it actually arrived in rather than forced through
171/// `HRESULT_FROM_WIN32`/`HRESULT_CODE` into a single shape, either direction of
172/// which is lossy.
173#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
174#[non_exhaustive]
175pub enum FailureCode {
176 /// A `WIN32_ERROR` from a classic last-error API.
177 Win32(u32),
178 /// An `HRESULT` from a COM-style API. Nothing in this crate produces one
179 /// today; the variant exists so a future source does not need a breaking
180 /// change to be represented.
181 HResult(i32),
182}
183
184/// [`OpenFailure`]'s classification plus the raw code behind it (D-79), carried
185/// by every fault report and permanent failure so a client can act on more than
186/// which kind of thing failed.
187#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
188pub struct FaultDetail {
189 /// How this failure should be treated by the retry policy.
190 pub failure: OpenFailure,
191 /// The raw code behind it.
192 pub code: FailureCode,
193}
194
195impl FaultDetail {
196 /// Build a detail for a condition detected before or independently of the
197 /// syscall, giving it the OS error code that describes it.
198 pub(crate) fn synthetic(failure: OpenFailure, code: u32) -> Self {
199 Self {
200 failure,
201 code: FailureCode::Win32(code),
202 }
203 }
204
205 /// Build a detail for [`OpenFailure::RetryUnavailable`] from the error that
206 /// actually caused it (a failure to create this crate's own retry timer),
207 /// rather than reporting the fixed classification with no code at all.
208 pub(crate) fn retry_unavailable(error: &std::io::Error) -> Self {
209 Self {
210 failure: OpenFailure::RetryUnavailable,
211 code: win32_code(error),
212 }
213 }
214}
215
216/// The raw Win32 code behind an OS error, or `0` if it did not carry one (a
217/// last-error API always sets one; this covers only a caller-fabricated
218/// `io::Error` with no OS error backing it).
219pub(crate) fn win32_code(error: &std::io::Error) -> FailureCode {
220 let code = error.raw_os_error().unwrap_or(0);
221 FailureCode::Win32(u32::try_from(code).unwrap_or(0))
222}
223
224/// Classify an OS error from an open attempt into its full [`FaultDetail`]
225/// (D-79): the [`OpenFailure`] classification plus the raw code behind it.
226pub(crate) fn classify_detail(error: &std::io::Error) -> FaultDetail {
227 FaultDetail {
228 failure: classify(error),
229 code: win32_code(error),
230 }
231}
232
233/// Classify an OS error from an open attempt.
234///
235/// Anything unrecognised is [`OpenFailure::Retryable`] by design: a watcher that
236/// gives up on an error it does not know is a watcher that silently stops
237/// watching. Also reused to classify an *arm* failure's unsupported-class edge
238/// (D-17, M6.3): `ERROR_INVALID_FUNCTION`/`ERROR_NOT_SUPPORTED` mean the same
239/// thing -- "this filesystem does not support the detailed API" -- whether they
240/// arise from opening the directory or from arming a read on it.
241pub(crate) fn classify(error: &std::io::Error) -> OpenFailure {
242 let Some(code) = error.raw_os_error() else {
243 return OpenFailure::Retryable;
244 };
245 let Ok(code) = u32::try_from(code) else {
246 return OpenFailure::Retryable;
247 };
248 match code {
249 ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => OpenFailure::NotFound,
250 ERROR_DIRECTORY => OpenFailure::NotADirectory,
251 ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED => OpenFailure::Unsupported,
252 ERROR_INVALID_NAME => OpenFailure::InvalidPath,
253 _ => OpenFailure::Retryable,
254 }
255}
256
257/// Encode a path as a NUL-terminated wide string.
258///
259/// Otherwise **verbatim**: the caller's units reach Win32 unchanged, and in
260/// particular this never prepends `\\?\` (D-85). That prefix is a different path
261/// *parsing mode*, not a longer-path switch -- it would stop forward slashes,
262/// `.`, `..`, and relative paths from resolving, all of which work today -- and
263/// whether a path past `MAX_PATH` opens without it depends on the machine's
264/// `LongPathsEnabled` policy together with the consuming *application's*
265/// `longPathAware` manifest, neither of which is a library's to decide. A caller
266/// who wants `\\?\` semantics passes a `\\?\` path, and it arrives intact.
267///
268/// An interior NUL is rejected rather than passed on: Win32 would stop at it and
269/// silently open a *different, shorter* path than the caller named, which is a
270/// correctness hole rather than a mere inconvenience. `Wtf16String` keeps content
271/// and terminator distinct and reports the condition itself, so this is the
272/// crate's own documented predicate rather than a hand-rolled scan. Reused by
273/// the coarse handle (M6.1), which needs the identical NUL-terminated encoding
274/// for `FindFirstChangeNotificationW`.
275pub(crate) fn wide_path(path: &Path) -> Result<Wtf16String, OpenError> {
276 let wide = Wtf16String::from_os_str(path.as_os_str());
277 if wide.has_interior_nul() {
278 return Err(OpenError::synthetic(
279 OpenFailure::InvalidPath,
280 ERROR_INVALID_NAME,
281 ));
282 }
283 Ok(wide)
284}
285
286/// A directory's stable identity, independent of the path string used to open
287/// it.
288///
289/// Two opens of the same directory -- through different spellings, a symlink, or
290/// a trailing separator -- yield the same id, which is what makes coalescing by
291/// directory (D-6) correct rather than an accident of string comparison.
292#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
293pub(crate) struct DirectoryId {
294 volume_serial: u32,
295 file_index: u64,
296}
297
298/// Read a directory's identity from a live handle, rejecting one that turns out
299/// not to be a directory.
300///
301/// `FILE_LIST_DIRECTORY` and `FILE_READ_DATA` are the same bit, so a plain file
302/// opens perfectly happily with this crate's `CreateFileW` arguments. Without
303/// this check the mistake would not surface until `ReadDirectoryChangesW` failed
304/// later, where it would be misread as a transient I/O fault and retried
305/// forever.
306fn identify(handle: HANDLE) -> Result<DirectoryId, OpenError> {
307 // SAFETY: an all-integer POD struct, so an all-zero value is valid; it is
308 // fully written by the call below before it is read.
309 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
310 // SAFETY: `handle` is live for the duration of this call, and `info` is a
311 // valid writable destination of the required type.
312 let ok = unsafe { GetFileInformationByHandle(handle, &mut info) };
313 if ok == 0 {
314 let source = std::io::Error::last_os_error();
315 return Err(OpenError::new(classify(&source), source));
316 }
317 if info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
318 return Err(OpenError::synthetic(
319 OpenFailure::NotADirectory,
320 ERROR_DIRECTORY,
321 ));
322 }
323 Ok(DirectoryId {
324 volume_serial: info.dwVolumeSerialNumber,
325 file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
326 })
327}
328
329/// The `FILE_CASE_SENSITIVE_INFO::Flags` bit meaning "this directory is
330/// case-sensitive" (`FILE_CS_FLAG_CASE_SENSITIVE_DIR`). Not exported by
331/// `windows-sys`, so named here per the repo's no-bare-manifest-numeric rule.
332const FILE_CS_FLAG_CASE_SENSITIVE_DIR: u32 = 0x0000_0001;
333
334/// Query whether `handle` (a live, open directory handle) is a case-sensitive
335/// directory, via `GetFileInformationByHandleEx`'s `FileCaseSensitiveInfo`
336/// class. `false` (case-insensitive, the overwhelmingly common case and this
337/// crate's behavior before this query existed) on any failure -- an older OS
338/// that predates the class (pre-Windows 10 1803), or a filesystem that does
339/// not implement it -- rather than propagating an error for a query that is
340/// advisory, not load-bearing for opening the directory at all.
341fn is_case_sensitive_dir(handle: HANDLE) -> bool {
342 let mut info = FILE_CASE_SENSITIVE_INFO { Flags: 0 };
343 // SAFETY: `handle` is live for the duration of this call; `info` is a
344 // valid, correctly-sized writable destination for `FileCaseSensitiveInfo`.
345 let ok = unsafe {
346 GetFileInformationByHandleEx(
347 handle,
348 FileCaseSensitiveInfo,
349 std::ptr::from_mut(&mut info).cast(),
350 u32::try_from(size_of::<FILE_CASE_SENSITIVE_INFO>())
351 .expect("this fixed, small struct's size always fits a u32"),
352 )
353 };
354 ok != 0 && info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0
355}
356
357/// A directory opened for change notification, owned for the life of the watch.
358///
359/// Closing is the `OwnedHandle`'s job, so a `DirectoryHandle` cannot outlive its
360/// handle or leak it.
361pub struct DirectoryHandle {
362 handle: OwnedHandle,
363 identity: DirectoryId,
364 case_sensitive: bool,
365}
366
367impl DirectoryHandle {
368 /// Open `path` for change notification.
369 ///
370 /// `path` is passed to `CreateFileW` verbatim -- see [`wide_path`] and D-85
371 /// for why no `\\?\` prefix is added, and what that means for paths longer
372 /// than `MAX_PATH`.
373 ///
374 /// # Errors
375 ///
376 /// Returns a classified [`OpenError`]; see [`OpenFailure`] for what each
377 /// class means for the retry policy.
378 pub fn open(path: &Path) -> Result<Self, OpenError> {
379 let wide = wide_path(path)?;
380 // SAFETY: `wide`'s terminated pointer is NUL-terminated and outlives the
381 // call, and the interior-NUL case was rejected above so the callee sees
382 // the whole path; the security attributes and template handle are null by
383 // design, and the remaining arguments are constants.
384 let raw = unsafe {
385 CreateFileW(
386 wide.as_terminated_ptr(),
387 FILE_LIST_DIRECTORY,
388 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
389 std::ptr::null(),
390 OPEN_EXISTING,
391 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
392 std::ptr::null_mut(),
393 )
394 };
395 if raw == INVALID_HANDLE_VALUE {
396 let source = std::io::Error::last_os_error();
397 return Err(OpenError::new(classify(&source), source));
398 }
399 // SAFETY: `CreateFileW` returned a live handle that this call exclusively
400 // owns, so transferring it to an `OwnedHandle` is sound.
401 let handle = unsafe { OwnedHandle::from_raw_handle(raw) };
402 // Computed on the owned handle, so an early return here closes it rather
403 // than leaking.
404 let identity = identify(handle.as_raw_handle())?;
405 let case_sensitive = is_case_sensitive_dir(handle.as_raw_handle());
406 Ok(Self {
407 handle,
408 identity,
409 case_sensitive,
410 })
411 }
412
413 /// This directory's stable identity (D-6).
414 pub(crate) fn identity(&self) -> DirectoryId {
415 self.identity
416 }
417
418 /// Whether this directory enforces case-sensitive name matching, queried
419 /// once at open time via `GetFileInformationByHandleEx`'s
420 /// `FileCaseSensitiveInfo` class (PR #20 review response).
421 ///
422 /// Case-sensitive directories are a per-directory opt-in NTFS feature
423 /// (`fsutil file setCaseSensitiveInfo`), off by default; almost every
424 /// directory is the ordinary case-insensitive-but-case-preserving kind
425 /// this crate has always assumed. Route matching (`route.rs`) must not
426 /// fold case on the rare directory that *is* case-sensitive: on such a
427 /// directory `A.txt` and `a.txt` genuinely name different files, and
428 /// folding them together would route one file's changes to a route
429 /// subscribed to the other.
430 ///
431 /// The class is only supported from Windows 10 version 1803 onward; a
432 /// failure (older OS, or a filesystem that does not implement it) is
433 /// treated as case-insensitive, matching this crate's behavior before
434 /// this method existed and every filesystem's overwhelmingly common
435 /// case.
436 pub(crate) fn is_case_sensitive(&self) -> bool {
437 self.case_sensitive
438 }
439
440 /// This directory's volume-level identity (D-78): the filesystem name and
441 /// volume label, for detecting removable media swapped for different
442 /// media mounted at the same path.
443 ///
444 /// # Errors
445 ///
446 /// Returns a classified [`OpenError`] if `GetVolumeInformationByHandleW`
447 /// fails.
448 pub(crate) fn volume_identity(&self) -> Result<VolumeIdentity, OpenError> {
449 volume_identity(self.as_raw())
450 }
451
452 /// This directory's current path, as the filesystem sees it right now,
453 /// queried fresh via `GetFinalPathNameByHandleW` rather than cached from
454 /// whatever string originally opened it (M11.2/D-78).
455 ///
456 /// The distinction is the point: the string a client passed may be
457 /// relative, unnormalised, or routed through a junction or mapped drive
458 /// that no longer leads where it did. This reports where the handle
459 /// actually is, which is what a diagnostic about a *changed* resolution has
460 /// to say to be worth printing.
461 ///
462 /// # Errors
463 ///
464 /// Returns a classified [`OpenError`] if `GetFinalPathNameByHandleW`
465 /// fails.
466 pub(crate) fn canonical_path(&self) -> Result<PathBuf, OpenError> {
467 canonical_path(self.as_raw())
468 }
469
470 /// Consume the wrapper and surrender the handle.
471 ///
472 /// Used to hand the directory to the thread pool's I/O object, which takes
473 /// ownership of the endpoint it binds.
474 pub(crate) fn into_handle(self) -> OwnedHandle {
475 self.handle
476 }
477
478 /// The raw handle, for the Win32 calls that take one.
479 pub(crate) fn as_raw(&self) -> HANDLE {
480 self.handle.as_raw_handle()
481 }
482}
483
484impl std::fmt::Debug for DirectoryHandle {
485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486 f.debug_struct("DirectoryHandle")
487 .field("handle", &self.as_raw())
488 .finish()
489 }
490}
491
492/// A directory's volume-level identity (D-78): the volume serial number,
493/// plus the filesystem name and volume label kept only as descriptive data
494/// for [`crate::Notification::VolumeChanged`]. Compared only when a
495/// path-based reopen fallback succeeds (M11.3) -- a `ReOpenFile` success is
496/// structurally guaranteed to still be on the same volume -- to notice
497/// removable media swapped for different media mounted at the same path.
498///
499/// Equality (and therefore change detection) is on `volume_serial` alone
500/// (PR #20 review response): the filesystem name and volume label are both
501/// mutable (a volume can be relabeled without becoming different media, and
502/// two different volumes can share a label and filesystem type), so neither
503/// is a sound identity signal -- comparing them would miss a genuine media
504/// swap that happens to share the old label, and would falsely report a
505/// change on a mere rename. `DirectoryId`'s own volume serial is not reused
506/// here because it is read from a *directory* handle rather than this
507/// volume-level query, and keeping the two independent avoids coupling this
508/// type's meaning to `DirectoryId`'s.
509#[derive(Clone, Debug)]
510pub struct VolumeIdentity {
511 volume_serial: u32,
512 filesystem_name: Wtf16String,
513 volume_label: Wtf16String,
514}
515
516impl PartialEq for VolumeIdentity {
517 fn eq(&self, other: &Self) -> bool {
518 self.volume_serial == other.volume_serial
519 }
520}
521
522impl Eq for VolumeIdentity {}
523
524impl VolumeIdentity {
525 /// The volume's filesystem name (e.g. `"NTFS"`, `"FAT32"`, `"ReFS"`),
526 /// lossily -- for display and logging, not for round-tripping.
527 #[must_use]
528 pub fn filesystem_name(&self) -> String {
529 self.filesystem_name.to_string_lossy()
530 }
531
532 /// The volume's label, lossily -- for display and logging, not for
533 /// round-tripping.
534 #[must_use]
535 pub fn volume_label(&self) -> String {
536 self.volume_label.to_string_lossy()
537 }
538
539 /// Build a synthetic identity (M12.6's test seam: rigging a mismatch a real
540 /// removable-media swap is not otherwise reproducible in an automated
541 /// test). `volume_serial` is the only field that matters for the
542 /// mismatch this seam exists to rig; the descriptive fields are for
543 /// display only. Available to the crate's own tests and, via the public
544 /// [`for_test`](Self::for_test) wrapper, under the `test-util` feature.
545 ///
546 /// **No uniqueness is promised.** Every `u32` is an accepted serial and
547 /// equality compares by serial alone, so a caller may pick a value that
548 /// collides with a real volume's. That is harmless for the seam's purpose
549 /// -- it rigs a comparison between two values the caller supplies -- but it
550 /// means a synthetic identity must not be treated as distinguishable from a
551 /// read one.
552 #[cfg(any(test, feature = "test-util"))]
553 pub(crate) fn synthetic(volume_serial: u32, filesystem_name: &str, volume_label: &str) -> Self {
554 Self {
555 volume_serial,
556 filesystem_name: Wtf16String::from_os_str(std::ffi::OsStr::new(filesystem_name)),
557 volume_label: Wtf16String::from_os_str(std::ffi::OsStr::new(volume_label)),
558 }
559 }
560
561 /// Consumer test-surface constructor (D-82), available only under the
562 /// off-by-default `test-util` feature. Builds a `VolumeIdentity` for a
563 /// downstream consumer synthesizing a
564 /// [`VolumeChanged`](crate::Notification::VolumeChanged) notification to
565 /// feed its own handler; in production a `VolumeIdentity` only ever comes
566 /// from reading a real volume. Volume identity compares by serial alone, so
567 /// `volume_serial` is what decides whether two identities match; the
568 /// filesystem name and label are for display (D-83: valid by construction).
569 #[cfg(feature = "test-util")]
570 #[must_use]
571 pub fn for_test(volume_serial: u32, filesystem_name: &str, volume_label: &str) -> Self {
572 Self::synthetic(volume_serial, filesystem_name, volume_label)
573 }
574}
575
576/// Read a handle's volume-level identity via `GetVolumeInformationByHandleW`.
577fn volume_identity(handle: HANDLE) -> Result<VolumeIdentity, OpenError> {
578 /// `MAX_PATH + 1`, ample for either output buffer: a volume label is
579 /// capped at 32 UTF-16 units by every filesystem this crate targets, and a
580 /// filesystem name ("NTFS", "FAT32", "ReFS", ...) is far shorter still.
581 const BUFFER_UNITS: usize = 261;
582 let mut volume_label = [0u16; BUFFER_UNITS];
583 let mut filesystem_name = [0u16; BUFFER_UNITS];
584 let mut volume_serial = 0u32;
585 // SAFETY: both buffers are valid, correctly sized, writable destinations;
586 // `volume_serial` is a valid writable `u32` destination; `handle` is live
587 // for the duration of this call. The max-component-length out-param is
588 // not needed here, so it alone is null.
589 let ok = unsafe {
590 GetVolumeInformationByHandleW(
591 handle,
592 volume_label.as_mut_ptr(),
593 u32::try_from(volume_label.len()).expect("a fixed small buffer size fits a u32"),
594 &mut volume_serial,
595 std::ptr::null_mut(),
596 std::ptr::null_mut(),
597 filesystem_name.as_mut_ptr(),
598 u32::try_from(filesystem_name.len()).expect("a fixed small buffer size fits a u32"),
599 )
600 };
601 if ok == 0 {
602 let source = std::io::Error::last_os_error();
603 return Err(OpenError::new(classify(&source), source));
604 }
605 Ok(VolumeIdentity {
606 volume_serial,
607 filesystem_name: Wtf16String::from_units(trim_nul(&filesystem_name)),
608 volume_label: Wtf16String::from_units(trim_nul(&volume_label)),
609 })
610}
611
612/// The units up to (excluding) the first NUL, or the whole slice if there is
613/// none -- what a fixed-size Win32 output buffer needs trimmed off before it
614/// is a real string.
615fn trim_nul(units: &[u16]) -> &[u16] {
616 units
617 .iter()
618 .position(|&unit| unit == 0)
619 .map_or(units, |end| &units[..end])
620}
621
622/// Read a handle's current path via `GetFinalPathNameByHandleW`, growing the
623/// buffer and retrying if the path is longer than the first guess -- the
624/// documented two-call convention for this API.
625fn canonical_path(handle: HANDLE) -> Result<PathBuf, OpenError> {
626 let mut buffer = vec![0u16; 512];
627 loop {
628 // SAFETY: `buffer` is a valid, writable destination of the length
629 // passed; `handle` is live for the duration of this call.
630 let written = unsafe {
631 GetFinalPathNameByHandleW(
632 handle,
633 buffer.as_mut_ptr(),
634 u32::try_from(buffer.len()).unwrap_or(u32::MAX),
635 VOLUME_NAME_DOS | FILE_NAME_NORMALIZED,
636 )
637 };
638 if written == 0 {
639 let source = std::io::Error::last_os_error();
640 return Err(OpenError::new(classify(&source), source));
641 }
642 let written = written as usize;
643 // Win32's two-call convention makes `written == buffer.len()` unreachable,
644 // which is why this is `<` and why a `<=` here would be equivalent rather
645 // than wrong: on success the call returns the length *excluding* the NUL
646 // and needs room for it, so `written < buffer.len()`; when the buffer is
647 // too small it returns the length *including* the NUL, which by
648 // definition exceeds `buffer.len()`. Confirmed empirically -- an
649 // `assert_ne!` here never fired across the suite, including a walk of
650 // every path length from 508 to 516 units.
651 if written < buffer.len() {
652 buffer.truncate(written);
653 return Ok(PathBuf::from(std::ffi::OsString::from_wide(&buffer)));
654 }
655 // `written` is the required length, including the NUL this call
656 // would otherwise have appended; the path did not fit, so retry once
657 // sized to hold it.
658 buffer.resize(written, 0);
659 }
660}
661
662#[cfg(test)]
663mod tests;