diff --git a/OpenCfDrive.Core/CloudFiles/CloudPlaceholderService.cs b/OpenCfDrive.Core/CloudFiles/CloudPlaceholderService.cs index 2451680..7cfef56 100644 --- a/OpenCfDrive.Core/CloudFiles/CloudPlaceholderService.cs +++ b/OpenCfDrive.Core/CloudFiles/CloudPlaceholderService.cs @@ -231,10 +231,14 @@ public int UpdateFromRemote( return WithMetadataHandle(localPath, replace); } - // Such a file can hold local writes too: a program can write to it - // without reading the rest. So it is checked and replaced while a - // handle that shares nothing holds it, as a file fully on disk is - // (pinned by UpdateFromRemote_UnchangedFrom_RefusesAFileNotFullyOnDiskWhileOpenInAnotherProgram). + // Such a file holds nothing local: a program's write makes the + // platform download all of it first (FULL hydration, pinned by + // AWrite_ToAFileNotFullyOnDisk_DownloadsAllOfItFirst). But a + // program that has it open can have a write waiting for that + // download, which could land between the check and the replace. + // So it is checked and replaced while a handle that shares nothing + // holds it, as a file fully on disk is (pinned by + // UpdateFromRemote_UnchangedFrom_RefusesAFileNotFullyOnDiskWhileOpenInAnotherProgram). return WithSoleHandle( localPath, held => LocalVersion(held) == before ? WithMetadataHandle(localPath, replace) : ChangedSinceLookedAt); diff --git a/OpenCfDrive.Core/CloudFiles/SyncRootRegistrar.cs b/OpenCfDrive.Core/CloudFiles/SyncRootRegistrar.cs index 350a495..bf73859 100644 --- a/OpenCfDrive.Core/CloudFiles/SyncRootRegistrar.cs +++ b/OpenCfDrive.Core/CloudFiles/SyncRootRegistrar.cs @@ -130,7 +130,7 @@ private static void RegisterWithShell(string syncRootPath, string shellId, byte[ IconResource = $"{Environment.ProcessPath ?? "%SystemRoot%\\system32\\imageres.dll"},0", // Same policies as the CfRegisterSyncRoot fallback below; see the // comments there for why each one is set this way. - HydrationPolicy = StorageProviderHydrationPolicy.Partial, + HydrationPolicy = StorageProviderHydrationPolicy.Full, HydrationPolicyModifier = StorageProviderHydrationPolicyModifier.None, PopulationPolicy = StorageProviderPopulationPolicy.Full, InSyncPolicy = StorageProviderInSyncPolicy.FileLastWriteTime, @@ -222,16 +222,24 @@ internal RegistrationResult RegisterWithDriverOnly( var policies = new CF_SYNC_POLICIES { StructSize = (uint)Marshal.SizeOf(), - // Partial hydration hydrates on demand (including byte ranges), - // and the platform persists what the provider transfers. The - // STREAMING_ALLOWED modifier must NOT be set here: it makes the - // platform treat hydrated bytes as streamed, discard them when - // the handle closes, and keep RECALL_ON_DATA_ACCESS set - which - // breaks subsequent reads and every write with + // FULL, as Nextcloud (cfapiwrapper.cpp) and OneDrive register: + // a program's read returns only once the whole file is on disk + // and the platform has finished downloading it. PARTIAL (which + // Microsoft documents as not supported, and which runs as + // PROGRESSIVE, the default for programs) let a read through as + // soon as its bytes arrived and finished a moment later; a + // write in between could lose the downloaded bytes, so the + // file read back as zeros followed by what was written (pinned + // by UpdatePlaceholderContractTest). The platform still + // persists what the provider transfers. The STREAMING_ALLOWED + // modifier must NOT be set here: it makes the platform treat + // hydrated bytes as streamed, discard them when the handle + // closes, and keep RECALL_ON_DATA_ACCESS set - which breaks + // subsequent reads and every write with // ERROR_CLOUD_FILE_REQUEST_TIMEOUT. Hydration = new CF_HYDRATION_POLICY { - Primary = (ushort)CF_HYDRATION_POLICY_PRIMARY.CF_HYDRATION_POLICY_PARTIAL, + Primary = (ushort)CF_HYDRATION_POLICY_PRIMARY.CF_HYDRATION_POLICY_FULL, Modifier = (ushort)CF_HYDRATION_POLICY_MODIFIER.CF_HYDRATION_POLICY_MODIFIER_NONE, }, // FULL: before a directory enumeration completes, the platform diff --git a/OpenCfDrive.Tests/UpdatePlaceholderContractTest.cs b/OpenCfDrive.Tests/UpdatePlaceholderContractTest.cs index 28ba6a1..aef85da 100644 --- a/OpenCfDrive.Tests/UpdatePlaceholderContractTest.cs +++ b/OpenCfDrive.Tests/UpdatePlaceholderContractTest.cs @@ -53,6 +53,75 @@ public void UpdateFromRemote_DropsTheLocalCopy_AndTheNextReadGetsNewContent(bool }); } + /// + /// A read returns only once the whole file is here: on disk, and no + /// longer marked to be downloaded (RECALL_ON_DATA_ACCESS). The drive + /// registers FULL hydration, as Nextcloud and OneDrive do. With PARTIAL + /// (which Windows runs as PROGRESSIVE) the read was let through as soon + /// as its bytes arrived and the download finished a moment later, and a + /// write in between could lose the downloaded bytes: the file then read + /// back as zeros followed by what was written (seen on CI in the read and + /// append above, and in UpdateFromRemote_UnchangedFrom_RefusesAFileSavedSince). + /// So that the read itself is what downloads the file, nothing else may + /// download it first: an on-access scanner (Defender's, on a PC; CI + /// runners have it off) downloads a file when a program opens it for + /// reading, and after a write handle to it closes. So the read is through + /// a handle opened while the file was still on disk (as a program that + /// keeps a file open reads it again), and the file is freed up meanwhile + /// through a handle without data access. + /// + [SkippableFact] + public void ARead_ReturnsOnlyOnceTheWholeFileIsHere() + { + var content = Encoding.UTF8.GetBytes("old-content"); + + RunInSyncRoot(() => content, (syncRoot, placeholders, fetches) => + { + var path = Path.Combine(syncRoot, "file.txt"); + Assert.Equal("old-content", File.ReadAllText(path)); + + // One read call, checked at once: a second read (at the end of + // the file) gave the platform time to finish. + using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 0); + var hr = FreeUpWithoutDataAccess(path); + Assert.True(CfApi.Succeeded(hr), $"Freeing up space failed with {HResult.Describe(hr)}"); + Assert.False(CloudPlaceholderService.HasLocalData(path), "Freeing up space left the file on disk."); + + var before = fetches(); + var buffer = new byte[64]; + var read = reader.Read(buffer); + var finished = CloudPlaceholderService.HasLocalData(path); + + Assert.Equal("old-content", Encoding.UTF8.GetString(buffer, 0, read)); + Assert.Equal(before + 1, fetches()); + Assert.True(finished, "The read returned before the platform finished downloading the file."); + Assert.False(placeholders.QueryState(path).Partial, "The file is not all on disk after a read of all of it."); + }); + } + + /// Frees up a file's space through a handle that has no data access (WRITE_DAC), which a scanner does not look at. + private static int FreeUpWithoutDataAccess(string path) + { + const uint writeDac = 0x00040000; + const uint shareAll = 7; + const uint openExisting = 3; + const uint backupSemantics = 0x02000000; + using var handle = CreateFileW(path, writeDac, shareAll, IntPtr.Zero, openExisting, backupSemantics, IntPtr.Zero); + if (handle.IsInvalid) + { + return Marshal.GetHRForLastWin32Error(); + } + + return CfApi.CfUpdatePlaceholder( + handle.DangerousGetHandle(), IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, 0, + CF_UPDATE_FLAGS.CF_UPDATE_FLAG_DEHYDRATE, out _, IntPtr.Zero); + } + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFileW( + string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, + uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile); + [SkippableFact] public void UpdateFromRemote_DiscardingLocalChanges_ReplacesAnEditedFile() { @@ -404,10 +473,11 @@ public void UpdateFromRemote_OnAPartlyDownloadedFile_DownloadsNothingMore() /// /// A file that is not fully on disk (online-only, or a download that broke - /// off) can hold local writes too: a program can write to it without - /// reading the rest, and nothing is downloaded. Replacing it is refused - /// while another program has it open, as for a file that is fully on - /// disk, and it downloads nothing either way. + /// off) holds nothing local (see AWrite_ToAFileNotFullyOnDisk_DownloadsAllOfItFirst), + /// but a program that has it open can have a write waiting for the + /// download that write starts, which could land between the check and the + /// replace. So replacing it is refused while another program has it open, + /// as for a file that is fully on disk, and it downloads nothing either way. /// [SkippableTheory] [InlineData(false)] @@ -428,15 +498,11 @@ public void UpdateFromRemote_UnchangedFrom_RefusesAFileNotFullyOnDiskWhileOpenIn limit = long.MaxValue; } - var edit = Encoding.UTF8.GetBytes("-edited"); var before = fetches(); - using (var program = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) + var looked = CloudPlaceholderService.LocalVersion(path)!.Value; + using (new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) { - program.Seek(0, SeekOrigin.End); - program.Write(edit); - program.Flush(); - Assert.True(placeholders.QueryState(path).Partial, "Writing to the file downloaded all of it."); - var looked = CloudPlaceholderService.LocalVersion(path)!.Value; + Assert.True(placeholders.QueryState(path).Partial, "Opening the file for writing downloaded all of it."); var inUse = placeholders.UpdateFromRemote(path, content.Length, DateTimeOffset.UtcNow, discardLocalChanges: true, unchangedFrom: looked); output.WriteLine($"open in another program -> {HResult.Describe(inUse)}"); @@ -445,10 +511,9 @@ public void UpdateFromRemote_UnchangedFrom_RefusesAFileNotFullyOnDiskWhileOpenIn } Assert.Equal(before, fetches()); - Assert.Equal(content.Length + edit.Length, new FileInfo(path).Length); - Assert.True(CloudPlaceholderService.GetOnDiskSize(path) > 0, "The local write is gone."); + Assert.True(placeholders.QueryState(path).Partial, "The file was downloaded."); - var hr = placeholders.UpdateFromRemote(path, content.Length, DateTimeOffset.UtcNow, discardLocalChanges: true, unchangedFrom: CloudPlaceholderService.LocalVersion(path)); + var hr = placeholders.UpdateFromRemote(path, content.Length, DateTimeOffset.UtcNow, discardLocalChanges: true, unchangedFrom: looked); output.WriteLine($"no longer open -> {HResult.Describe(hr)}, fetches {fetches() - before}"); Assert.True(CfApi.Succeeded(hr), $"UpdateFromRemote failed with {HResult.Describe(hr)}"); Assert.Equal(before, fetches()); @@ -458,6 +523,47 @@ public void UpdateFromRemote_UnchangedFrom_RefusesAFileNotFullyOnDiskWhileOpenIn }); } + /// + /// Why a file that is not fully on disk holds nothing local: a program's + /// write to it makes Windows download all of it first (FULL hydration, + /// see SyncRootRegistrar), and the write then lands on the whole file. + /// With PARTIAL the write went in with nothing downloaded, and for a + /// file of 70 KB the written bytes were lost once it was read. + /// + [SkippableTheory] + [InlineData(false)] + [InlineData(true)] + public void AWrite_ToAFileNotFullyOnDisk_DownloadsAllOfItFirst(bool brokenOff) + { + var content = new byte[1024 * 1024]; + Random.Shared.NextBytes(content); + var limit = long.MaxValue; + + RunInSyncRoot(() => content, deliverAtMost: () => limit, test: (syncRoot, placeholders, fetches) => + { + var path = Path.Combine(syncRoot, "file.txt"); + if (brokenOff) + { + limit = 64 * 1024; + Assert.ThrowsAny(() => File.ReadAllBytes(path)); + limit = long.MaxValue; + } + + Assert.True(placeholders.QueryState(path).Partial, "The file is already all on disk."); + var edit = Encoding.UTF8.GetBytes("-edited"); + using (var program = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) + { + program.Seek(0, SeekOrigin.End); + program.Write(edit); + program.Flush(); + Assert.False(placeholders.QueryState(path).Partial, "The write went in without the file being downloaded."); + Assert.True(CloudPlaceholderService.HasLocalData(path), "The write went in before the download finished."); + } + + Assert.Equal(content.Concat(edit).ToArray(), File.ReadAllBytes(path)); + }); + } + [SkippableTheory] [InlineData(true)] [InlineData(false)] diff --git a/docs/architecture.md b/docs/architecture.md index 8f35c06..dde5110 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -268,8 +268,11 @@ The invariants below spell out how. that is not fully local go through a `WRITE_DAC`-only handle (`WithMetadataHandle`), and nothing is downloaded. - **A file not fully on disk is held too before a server change replaces it.** - It can hold local writes: a program can write to an online-only or partly - downloaded file without reading the rest, and nothing is downloaded. The + It holds nothing local: a program's write to it makes Windows download all + of it first (see "A read returns once the whole file is downloaded" below). + But a program that has it open + can have a write waiting for that download, which could land between the + check and the replace. The `WRITE_DAC`-only handle keeps no one out, so the file is first held by a plain handle that shares nothing and has `DELETE` access (`WithSoleHandle`), which is what makes Windows check sharing at all. It is refused while another @@ -291,6 +294,19 @@ The invariants below spell out how. when the program runs in session 0 (Windows Installer reading a package). The callback log line names that session. Reporting also resets the callback's 60 s timeout. +- **A read returns once the whole file is downloaded** (hydration policy + `FULL`, as Nextcloud and OneDrive register). With `PARTIAL`, which Microsoft + documents as not supported and which Windows runs as `PROGRESSIVE`, a read + was let through as soon as its bytes arrived and Windows finished the + download a moment later. A program's write in between could lose the + downloaded bytes: the file read back as zeros, then what was written. An + on-access scanner (Defender's) that downloads a file when a program opens it + hid this on a PC; CI runners have it off. Pinned by + `UpdatePlaceholderContractTest.ARead_ReturnsOnlyOnceTheWholeFileIsHere`. + The same goes for writes: a program's write to a file that is not fully on + disk makes Windows download all of it first, so such a file holds nothing + local (`AWrite_ToAFileNotFullyOnDisk_DownloadsAllOfItFirst`). With + `PARTIAL` the write went in with nothing downloaded. - **After an upload, one lookup.** The store keeps the server's own size and time, which most remotes stamp themselves, so the client reads them back with `operations/stat` on that one file, not a listing of its folder. diff --git a/scripts/tests/E2E-Run.ps1 b/scripts/tests/E2E-Run.ps1 index 412685b..8c785a5 100644 --- a/scripts/tests/E2E-Run.ps1 +++ b/scripts/tests/E2E-Run.ps1 @@ -112,11 +112,13 @@ $mountCheck = { # The hydrated bytes must be kept: if the placeholder is still marked for # recall afterwards, every later read and any write will hit cfapi timeouts. - # Windows lets the read through as soon as its bytes arrive and clears the - # mark a moment later (on CI the read has returned first), so wait for it. - if (-not (Wait-ForAttributes $beta { -not (& $isDehydrated $beta) })) { + # And the read returns only once Windows has finished the download (FULL + # hydration, see SyncRootRegistrar), so the mark is already gone: a write + # right after a read must not race the download's last step, which could + # lose the downloaded bytes. + if (& $isDehydrated $beta) { $after = (Get-Item -LiteralPath $beta -Force).Attributes - throw "beta.txt is still dehydrated after a successful read (attributes: $after); hydration is not persisting." + throw "beta.txt is still marked to be downloaded right after a read returned it (attributes: $after); the read was let through before the download finished, or hydration is not persisting." } Write-E2ELog "MOUNT: beta.txt is locally available (attributes: $((Get-Item -LiteralPath $beta -Force).Attributes))"