A full-featured download manager.
fix(finalize): allow exfat directory roots without file ids (#2330)
Dr_rOot64a0cecb65a2
diff --git a/.github/workflows/finalize-smb.yml b/.github/workflows/finalize-smb.ymlindex 4908a861..08996201 100644--- a/.github/workflows/finalize-smb.yml+++ b/.github/workflows/finalize-smb.yml@@ -64,3 +64,45 @@ jobs:if ($created) { Remove-SmbShare -Name $shareName -Force }Remove-Item -LiteralPath $shareRoot -Recurse -Force}++ windows-exfat:+ runs-on: windows-2025+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable+ with:+ toolchain: 1.94.1+ - name: Exercise an isolated exFAT virtual disk+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ if (Get-PSDrive -Name R -ErrorAction SilentlyContinue) { throw 'Test drive letter R is already in use' }+ $vhd = Join-Path $env:RUNNER_TEMP "motrix-exfat-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT.vhd"+ $script = Join-Path $env:RUNNER_TEMP "motrix-exfat-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT.txt"+ if (Test-Path -LiteralPath $vhd) { throw 'Test VHD already exists' }+ try {+ @(+ "create vdisk file=`"$vhd`" maximum=128 type=expandable",+ "select vdisk file=`"$vhd`"",+ 'attach vdisk',+ 'create partition primary',+ 'format fs=exfat quick label=MotrixTest',+ 'assign letter=R'+ ) | Set-Content -LiteralPath $script -Encoding ASCII+ diskpart /s $script+ if ($LASTEXITCODE -ne 0) { throw 'Creating exFAT test VHD failed' }+ $disk = Get-DiskImage -ImagePath $vhd | Get-Disk+ $volume = Get-Partition -DiskNumber $disk.Number | Get-Volume | Where-Object DriveLetter -eq R+ if (!$volume -or $volume.FileSystem -ne 'exFAT') { throw 'R is not the newly created exFAT test volume' }+ $env:MOTRIX_FINALIZE_EXFAT_ROOT = 'R:\'+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::windows::tests::exfat_volume_root_and_nested_directory_support_no_replace_rename+ if ($LASTEXITCODE -ne 0) { throw 'exFAT finalization contract failed' }+ } finally {+ Remove-Item Env:MOTRIX_FINALIZE_EXFAT_ROOT -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $vhd) {+ Dismount-DiskImage -ImagePath $vhd -ErrorAction Continue+ Remove-Item -LiteralPath $vhd -Force -ErrorAction Continue+ }+ Remove-Item -LiteralPath $script -Force -ErrorAction SilentlyContinue+ }diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.mdindex 8da29947..f97683a8 100644--- a/packages/finalize-fs/README.md+++ b/packages/finalize-fs/README.md@@ -238,3 +238,22 @@ does not bound time spent inside a blocking filesystem call.Directory case-sensitivity queries fall back only on recognized unsupportedinformation-class errors. Permission, sharing, transport, and I/O failures arepropagated instead of silently switching to case-insensitive lookup.++## Windows FAT-family directory roots++Directory traversal validates directory type and rejects reparse points without+requiring a file identity. Some volume roots, including exFAT roots, report a+zero legacy file index. Their held handles remain usable for relative opens and+directory flushes. Parent flush deduplication requires two matching, nonzero IDs;+when either ID is empty, both parents are flushed. Real query failures still+propagate. Artifact admission, snapshots and name-to-handle checks continue to+reject empty IDs; zero IDs are never treated as evidence that files are equal.++The Windows workflow creates a disposable exFAT VHD and tests both the volume+root and a nested directory, including target conflicts and successful removal+of the `.motrix` suffix. To run the same native test against a disposable exFAT+volume, set `MOTRIX_FINALIZE_EXFAT_ROOT` to its drive root and run:++```sh+cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::windows::tests::exfat_volume_root_and_nested_directory_support_no_replace_rename+```diff --git a/packages/finalize-fs/src/platform/windows/metadata.rs b/packages/finalize-fs/src/platform/windows/metadata.rsindex 721e990f..22384fb0 100644--- a/packages/finalize-fs/src/platform/windows/metadata.rs+++ b/packages/finalize-fs/src/platform/windows/metadata.rs@@ -11,10 +11,10 @@ use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_FILES, ERROR_PATH_NOT_FOUND,};use windows_sys::Win32::Storage::FileSystem::{- BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_FULL_DIR_INFO,- FILE_ID_INFO, FILE_STANDARD_INFO, FileBasicInfo, FileFullDirectoryInfo,- FileFullDirectoryRestartInfo, FileIdInfo, FileStandardInfo, GetFileInformationByHandle,- GetFileInformationByHandleEx,+ BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT,+ FILE_BASIC_INFO, FILE_FULL_DIR_INFO, FILE_ID_INFO, FILE_STANDARD_INFO, FileBasicInfo,+ FileFullDirectoryInfo, FileFullDirectoryRestartInfo, FileIdInfo, FileStandardInfo,+ GetFileInformationByHandle, GetFileInformationByHandleEx,};#[derive(Clone, Debug, Eq, PartialEq)]@@ -57,6 +57,48 @@ impl ArtifactSnapshot {}}+/// Held traversal directories need type/reparse validation, not an artifact ID.+/// In particular, FAT-family volume roots may report a zero legacy file index.+pub(super) fn ensure_directory(handle: &OwnedHandle) -> io::Result<()> {+ let basic: FILE_BASIC_INFO = query(handle, FileBasicInfo)?;+ validate_directory_attributes(basic.FileAttributes)+}++fn validate_directory_attributes(attributes: u32) -> io::Result<()> {+ if attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "Windows reparse points are forbidden",+ ));+ }+ if attributes & FILE_ATTRIBUTE_DIRECTORY == 0 {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "Windows path component is not a directory",+ ));+ }+ Ok(())+}++/// Identity equality is only a flush optimization, never a prerequisite to+/// using an already-held directory. Missing IDs require flushing both parents.+pub(super) fn same_parent_directory(left: &OwnedHandle, right: &OwnedHandle) -> io::Result<bool> {+ let left = query_raw_identity_with(left, query::<FILE_ID_INFO>(left, FileIdInfo))?;+ let right = query_raw_identity_with(right, query::<FILE_ID_INFO>(right, FileIdInfo))?;+ Ok(same_known_identity(&left, &right))+}++fn same_known_identity(left: &(u64, FileIdentity), right: &(u64, FileIdentity)) -> bool {+ !empty_identity(&left.1) && !empty_identity(&right.1) && left == right+}++fn empty_identity(id: &FileIdentity) -> bool {+ match id {+ FileIdentity::Extended(id) => *id == [0; 16],+ FileIdentity::Legacy(id) => *id == 0,+ }+}+pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {let basic: FILE_BASIC_INFO = query(handle, FileBasicInfo)?;let (volume, file_id) = query_identity(handle)?;@@ -84,16 +126,33 @@ pub(super) fn query_identity(handle: &OwnedHandle) -> io::Result<(u64, FileIdentfn query_identity_with(handle: &OwnedHandle,extended: io::Result<FILE_ID_INFO>,+) -> io::Result<(u64, FileIdentity)> {+ let identity = query_raw_identity_with(handle, extended)?;+ require_artifact_identity(identity)+}++fn require_artifact_identity(identity: (u64, FileIdentity)) -> io::Result<(u64, FileIdentity)> {+ if empty_identity(&identity.1) {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ match identity.1 {+ FileIdentity::Legacy(_) => "filesystem returned an empty legacy file identity",+ FileIdentity::Extended(_) => "filesystem returned an empty file identity",+ },+ ));+ }+ Ok(identity)+}++fn query_raw_identity_with(+ handle: &OwnedHandle,+ extended: io::Result<FILE_ID_INFO>,) -> io::Result<(u64, FileIdentity)> {match extended {- Ok(id) if id.FileId.Identifier != [0; 16] => Ok((+ Ok(id) => Ok((id.VolumeSerialNumber,FileIdentity::Extended(id.FileId.Identifier),)),- Ok(_) => Err(io::Error::new(- io::ErrorKind::Unsupported,- "filesystem returned an empty file identity",- )),Err(error) if unsupported_information(os_code(&error)) => {// SMB 2.x and older NAS implementations expose 64-bit file indices.// Keep the identity namespace distinct from the 128-bit query.@@ -106,12 +165,6 @@ fn query_identity_with());}let id = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow);- if id == 0 {- return Err(io::Error::new(- io::ErrorKind::Unsupported,- "filesystem returned an empty legacy file identity",- ));- }Ok((u64::from(info.dwVolumeSerialNumber),FileIdentity::Legacy(id),@@ -344,6 +397,34 @@ fn query<T: Default>(handle: &OwnedHandle, class: i32) -> io::Result<T> {mod tests {use super::*;+ #[test]+ fn traversal_accepts_directories_without_relaxing_artifact_identity() {+ validate_directory_attributes(FILE_ATTRIBUTE_DIRECTORY).unwrap();+ assert!(+ validate_directory_attributes(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)+ .is_err()+ );+ assert!(validate_directory_attributes(0).is_err());+ for id in [FileIdentity::Legacy(0), FileIdentity::Extended([0; 16])] {+ assert!(require_artifact_identity((42, id.clone())).is_err());+ assert!(!same_known_identity(&(42, id.clone()), &(42, id)));+ }+ }++ #[test]+ fn parent_deduplication_requires_matching_nonempty_ids_in_the_same_namespace() {+ let known = (42, FileIdentity::Legacy(7));+ assert!(same_known_identity(&known, &known));+ for other in [+ (42, FileIdentity::Legacy(0)),+ (43, FileIdentity::Legacy(7)),+ (42, FileIdentity::Legacy(8)),+ (42, FileIdentity::Extended([7; 16])),+ ] {+ assert!(!same_known_identity(&known, &other));+ }+ }+#[test]fn legacy_identity_fallback_is_stable_and_preserves_real_errors() {let file = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rsindex e34bc4a6..3647f60a 100644--- a/packages/finalize-fs/src/platform/windows/mod.rs+++ b/packages/finalize-fs/src/platform/windows/mod.rs@@ -42,13 +42,7 @@ pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {let requested = Path::new(path);let (anchor, components) = split_absolute_root(requested)?;let mut current = nt::open_anchor(&anchor, components.is_empty())?;- let anchor_stamp = query_stamp(¤t)?;- if !anchor_stamp.directory {- return Err(io::Error::new(- io::ErrorKind::InvalidInput,- "Windows root anchor is not a directory",- ));- }+ metadata::ensure_directory(¤t)?;let component_count = components.len();for (index, component) in components.into_iter().enumerate() {current = if index + 1 == component_count {@@ -56,12 +50,7 @@ pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {} else {nt::open_existing_directory(¤t, &component)?};- if !query_stamp(¤t)?.directory {- return Err(io::Error::new(- io::ErrorKind::InvalidInput,- "Windows root component is not a directory",- ));- }+ metadata::ensure_directory(¤t)?;}Ok(RootHandle { handle: current })}@@ -126,8 +115,7 @@ pub(crate) fn rename_opened_no_replace(ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;let parts = validate_relative(target_relative)?;let (target_parent, target_name) = open_parent(&target.handle, &parts)?;- let same_parent = metadata::query_identity(&artifact.parent)?- == metadata::query_identity(&target_parent)?;+ let same_parent = metadata::same_parent_directory(&artifact.parent, &target_parent)?;Ok((target_parent, target_name, same_parent))})().map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;@@ -172,12 +160,7 @@ fn open_parent(root: &OwnedHandle, parts: &[&str]) -> io::Result<(OwnedHandle, Vlet mut current = root.try_clone()?;for component in &parts[..parts.len().saturating_sub(1)] {current = nt::open_mutable_directory(¤t, &nt::wide_name(component)?)?;- if !query_stamp(¤t)?.directory {- return Err(io::Error::new(- io::ErrorKind::InvalidInput,- "Windows path component is not a directory",- ));- }+ metadata::ensure_directory(¤t)?;}Ok((current,diff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rsindex 866b38c8..8dbf65cf 100644--- a/packages/finalize-fs/src/platform/windows/tests.rs+++ b/packages/finalize-fs/src/platform/windows/tests.rs@@ -245,3 +245,76 @@ fn rename_admission_waits_for_a_reader_that_denies_delete_sharing() {);assert!(!scratch.path().join("source.motrix").exists());}++#[test]+#[ignore = "requires MOTRIX_FINALIZE_EXFAT_ROOT on a disposable exFAT volume"]+fn exfat_volume_root_and_nested_directory_support_no_replace_rename() {+ use std::io::Write;+ use std::os::windows::io::AsRawHandle;+ use windows_sys::Win32::Storage::FileSystem::GetVolumeInformationByHandleW;++ let volume =+ PathBuf::from(std::env::var("MOTRIX_FINALIZE_EXFAT_ROOT").expect("exFAT volume root"));+ let (_, parts) = super::split_absolute_root(&volume).unwrap();+ assert!(parts.is_empty(), "test must include the volume root itself");+ let root = open_root(volume.to_str().unwrap()).expect("admit exFAT root without a file ID");+ let mut filesystem = [0_u16; 32];+ let result = unsafe {+ GetVolumeInformationByHandleW(+ root.handle.as_raw_handle(),+ std::ptr::null_mut(),+ 0,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ filesystem.as_mut_ptr(),+ filesystem.len() as u32,+ )+ };+ assert_ne!(+ result,+ 0,+ "query exFAT volume: {}",+ std::io::Error::last_os_error()+ );+ let end = filesystem.iter().position(|value| *value == 0).unwrap();+ assert!(String::from_utf16_lossy(&filesystem[..end]).eq_ignore_ascii_case("exfat"));++ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let prefix = format!("motrix-exfat-{}-{nonce}", std::process::id());+ let scratch = Scratch(volume.join(&prefix));+ fs::create_dir(scratch.path()).unwrap();+ fs::create_dir(scratch.path().join("nested")).unwrap();+ for directory in [volume, scratch.path().join("nested")] {+ let root = open_root(directory.to_str().unwrap()).unwrap();+ let source = format!("{prefix}.rar.motrix");+ let target = format!("{prefix}.rar");+ for (name, bytes) in [+ (&source, b"download".as_slice()),+ (&target, b"existing".as_slice()),+ ] {+ let mut file = fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(directory.join(name))+ .unwrap();+ file.write_all(bytes).unwrap();+ file.sync_all().unwrap();+ }+ let artifact = super::open_artifact_for_rename(&root, &source).unwrap();+ assert!(rename_opened_no_replace(&artifact, &root, &target).is_err());+ assert_eq!(fs::read(directory.join(&target)).unwrap(), b"existing");+ assert_eq!(fs::read(directory.join(&source)).unwrap(), b"download");+ fs::remove_file(directory.join(&target)).unwrap();+ let result = rename_opened_no_replace(&artifact, &root, &target).unwrap();+ assert_eq!(result.directory_sync_mode, "directory_flushed");+ sync_root(&root).unwrap();+ drop(artifact);+ assert!(!directory.join(&source).exists());+ assert_eq!(fs::read(directory.join(&target)).unwrap(), b"download");+ fs::remove_file(directory.join(target)).unwrap();+ }+}