From 85309dcbd38e05a716efcc0a25ae702747a50760 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Mon, 30 Nov 2026 03:49:51 +0100 Subject: [PATCH] feat(fs): open a host file by path, following links, decided on the handle IDescriptorFileSystem::openHostFile(path, open) opens a file a tool's user named, the way any tool does: the system resolves the path and follows every link on it, absolute targets included, and needs only search access on the way, so a file under a 0711 home opens. The open never waits: POSIX opens O_NONBLOCK and clears the flag for a regular file only (a leased file is opened again through the path handle, which now follows a final link unless the open says O_NOFOLLOW); Windows opens with CreateFileW sharing read, write and delete. Nothing else is decided: a directory or a FIFO opens too, and the caller refuses it on the handle. Only None and Directory are accepted (checkHostOpenFlags). The in-memory model resolves the path from its root. Closes #109. Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 1 + CHANGELOG.md | 15 ++ docs/modules/fs.md | 14 +- src/core/fs/CMakeLists.txt | 1 + src/core/fs/Descriptor.hpp | 21 ++ src/core/fs/HostFile_test.cpp | 181 ++++++++++++++++++ src/core/fs/Rights.cpp | 7 + src/core/fs/Rights.hpp | 6 + src/core/fs/linux/Lease.cpp | 7 +- src/core/fs/linux/Lease_test.cpp | 24 ++- src/core/fs/posix/PosixDescriptor.cpp | 49 +++++ src/core/fs/posix/PosixDescriptor_test.cpp | 48 ++++- src/core/fs/posix/PosixSystem.hpp | 5 +- .../testing/InMemoryDescriptorFileSystem.cpp | 78 ++++++++ .../testing/InMemoryDescriptorFileSystem.hpp | 12 ++ src/core/fs/windows/WindowsDescriptor.cpp | 134 ++++++++----- 16 files changed, 551 insertions(+), 52 deletions(-) create mode 100644 src/core/fs/HostFile_test.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 350558d5..037e1a3b 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -172,6 +172,7 @@ others in notes. | `src/core/fs/FsError.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/FsError.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one code per WASI 0.3 `wasi:filesystem` `error-code` case, plus `WouldBlock` | | `src/core/fs/FsError_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/HostFile_test.cpp` | origin: core-cpp | - | - | 0.25.0 (#109): openHostFile, per fixture kind | | `src/core/fs/NativeDescriptor_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no system call on the caller's executor, a handle that outlives a parked call (C2), the keyed metadata hash | | `src/core/fs/NativeFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `makeNativeDescriptorFileSystem` and its options | | `src/core/fs/PathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX and Windows rows | diff --git a/CHANGELOG.md b/CHANGELOG.md index e59acf01..2c336383 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,21 @@ workflow refuses one without a section here. ## [Unreleased] +### Breaking + +- **`IDescriptorFileSystem` has a new pure virtual, `openHostFile(std::filesystem::path, OpenFlags)`** + ([#109](https://github.com/contour-terminal/core-cpp/issues/109)). Migration: an implementation outside + core-cpp, a test double included, overrides it (a decorator forwards it). Consumers grepped (contour, endo, + fastcached, Lightweight): none implements `IDescriptorFileSystem`; Isoline's test doubles do. + +### Added + +- **`IDescriptorFileSystem::openHostFile(path, open)`**: opens a file a tool's user named by an ambient path, + following every link on it (absolute targets included) and needing only search access on the way. The open + never waits (POSIX `O_NONBLOCK`, cleared for a regular file; Windows shares read, write and delete), and + every decision is the caller's, on the handle. `open` is `None` or `Directory`; anything else is `Invalid` + (`checkHostOpenFlags()`). The in-memory model resolves the path from its root. + ## [0.24.0] - 2026-11-28 ### Breaking diff --git a/docs/modules/fs.md b/docs/modules/fs.md index 2c0d66a3..087fdf7c 100644 --- a/docs/modules/fs.md +++ b/docs/modules/fs.md @@ -13,11 +13,11 @@ value. | Header | What it has | |---|---| -| `` | `IDescriptorFileSystem` (`openPreopen()`, `relation()`), `IDescriptor` (the byte, metadata and `*At` operations), `IDirectoryStream`; `DescriptorFlags`, `OpenFlags`, `CreationAccess`, `SymlinkPolicy`, `Advice`, `StreamEnd`, `DescriptorType`, `DescriptorStat`, `FileTime`, `NewTimestamp` (`NoChange`, `SetToNow` or a `FileTime`), `DirectoryEntry`, `MetadataHash`, `ReadChunk`, `Relation`; `hasFlag()` and `operator|` for both masks | +| `` | `IDescriptorFileSystem` (`openPreopen()`, `openHostFile()`, `relation()`), `IDescriptor` (the byte, metadata and `*At` operations), `IDirectoryStream`; `DescriptorFlags`, `OpenFlags`, `CreationAccess`, `SymlinkPolicy`, `Advice`, `StreamEnd`, `DescriptorType`, `DescriptorStat`, `FileTime`, `NewTimestamp` (`NoChange`, `SetToNow` or a `FileTime`), `DirectoryEntry`, `MetadataHash`, `ReadChunk`, `Relation`; `hasFlag()` and `operator|` for both masks | | `` | `makeNativeDescriptorFileSystem(home, blocking, wallClock, random, options)`, `NativeFileSystemOptions`, `BeneathStrategy`, `DefaultMaxSymlinkHops` (40), `DefaultMaxAncestorDepth` (4,096) | | `` | `FsErrorCode` and its `toString()`, `FsError` (a category, the raw errno, Win32 error or NTSTATUS, and a context), `FsResult`; the classification tables `systemErrorTable()`, `ntStatusTable()`, `noFollowSymlinkErrnos()`, and `fsErrorFromSystemCode()`, `fsErrorFromNtStatus()` | | `` | `PathPolicy` (`PathEncoding`, `CaseRule`, `TrailingDotsAndSpaces`), `posixPathPolicy()`, `windowsPathPolicy()`, `nativePathPolicy()`, and `isRootedLinkTarget()` | -| `` | `Operation`, `RightsRow`, `rightsTable()`, `checkRights()`, `checkOpenRights()`, `grantedFlags()` | +| `` | `Operation`, `RightsRow`, `rightsTable()`, `checkRights()`, `checkOpenRights()`, `checkHostOpenFlags()`, `grantedFlags()` | | `` | `AccessScope`, `AccessFacts`, `AccessEntry` and `classifyAccess()`, the pure decision of who may reach an object | | `` | `testing::InMemoryDescriptorFileSystem` and `testing::IdentityModel`: the same contract over nodes in memory | @@ -96,6 +96,16 @@ the trailing dot or space rule. `nativePathPolicy()` is the build's row, overrid `openPreopen()` takes a `std::filesystem::path` the host chose, which is not held to a policy. +`openHostFile(path, open)` is the one entry point that takes an ambient path, for a tool opening a +file its user named: the system resolves the path and follows every link on it, an absolute one +included, and needs only search access to the directories on the way (a file under a home of mode +0711 opens). It opens to read, without waiting: POSIX opens `O_NONBLOCK` and clears the flag for a +regular file only, so a FIFO with no writer opens at once; Windows shares read, write and delete +with every other handle. Nothing else is decided: a directory, a FIFO or a device opens too, and the +caller reads `stat()` on the handle and refuses what it does not want. `open` is `None` or +`Directory`; a flag that creates or changes a file is `Invalid`. The in-memory model resolves the +path from its root. + On Windows a junction, a mount point and every other reparse point that names an object by an absolute path is a link that is never followed (`NotPermitted`), and `readlinkAt` of one is `NotPermitted` too, so no host path is handed out; the full list of Windows differences is the doc diff --git a/src/core/fs/CMakeLists.txt b/src/core/fs/CMakeLists.txt index ce263868..8601e45e 100644 --- a/src/core/fs/CMakeLists.txt +++ b/src/core/fs/CMakeLists.txt @@ -172,6 +172,7 @@ core_cpp_add_test(fs DescriptorTestSupport.hpp DirectoryStream_test.cpp FsError_test.cpp + HostFile_test.cpp NativeDescriptor_test.cpp PathPolicy_test.cpp Relation_test.cpp diff --git a/src/core/fs/Descriptor.hpp b/src/core/fs/Descriptor.hpp index ace4b0ac..87c9fc15 100644 --- a/src/core/fs/Descriptor.hpp +++ b/src/core/fs/Descriptor.hpp @@ -447,6 +447,27 @@ class IDescriptorFileSystem [[nodiscard]] virtual async::Task>> openPreopen( std::filesystem::path hostDirectory, DescriptorFlags flags) = 0; + /// Opens @p hostPath to read, the way a tool opens a file its user named: the one entry point + /// that takes an ambient path, beside the capability-scoped API, which it leaves as it is. The + /// system resolves the path, following every link on it, the final one included, whatever its + /// target (an absolute one, or one that leaves any directory), and no directory on it needs more + /// than search access. The open never waits: on POSIX it is made `O_NONBLOCK`, so a FIFO with no + /// writer opens at once, and the flag is cleared again for a regular file only, whose reads then + /// wait as any file's do (a FIFO's or a device's descriptor stays non-blocking, and a read that + /// would wait answers `WouldBlock`); on Windows it shares read, write and delete with every other + /// handle. **Every decision is the caller's, on the handle**: a directory, a FIFO or a device + /// opens like a regular file, so a caller that wants one reads @c IDescriptor::stat and refuses + /// the rest, its size included. + /// @param hostPath The file, in the host's own terms: absolute, or relative to the process's + /// working directory. An in-memory model resolves it from its root. + /// @param open `None`, or `Directory` to refuse anything but a directory (`NotDirectory`). Every + /// other flag creates or changes a file and is `Invalid`. + /// @return The descriptor, carrying `Read` (and what a directory's `Read` grants); `NoEntry` + /// where nothing has the path, `Loop` past the system's link limit, `Access` where a + /// directory on the way may not be searched or the object may not be read. + [[nodiscard]] virtual async::Task>> openHostFile( + std::filesystem::path hostPath, OpenFlags open) = 0; + /// Decides whether @p first is, contains or lies beneath @p second on the opened handles: each /// one's real parents are walked up to the root and compared by identity (device and inode; /// volume serial and file id on Windows), never by path text. So a component of the path either diff --git a/src/core/fs/HostFile_test.cpp b/src/core/fs/HostFile_test.cpp new file mode 100644 index 00000000..3859c26e --- /dev/null +++ b/src/core/fs/HostFile_test.cpp @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What IDescriptorFileSystem::openHostFile owes a tool that opens a path its user named, whichever +// file system is under it: every link on the path is followed, an absolute one included; nothing +// is decided but what the open itself must refuse, so a directory opens and the caller's check on +// the handle is what turns it away; and the descriptor carries Read alone. +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::IDescriptor; +using core::fs::OpenFlags; +using core::fs::test::DescriptorFixture; +using core::fs::test::FixtureKind; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; +using core::fs::test::textOf; + +namespace +{ + +/// Creates the link @p name beside the files, naming @p target verbatim, through the host: an +/// absolute target, which no `symlinkAt` makes. +/// @param fixture The fixture. +/// @param name The link's name beneath the root. +/// @param target What it names. +/// @return Whether the link exists; a native file system may refuse (Windows without the privilege). +bool hostLink(DescriptorFixture const& fixture, std::string const& name, std::filesystem::path const& target) +{ + if (fixture.kind() == FixtureKind::InMemory) + { + fixture.inMemory().addSymlink("root/" + name, target.generic_string()); + return true; + } + // Windows tells a link to a directory from one to a file; POSIX makes both alike. + auto const named = target.is_absolute() ? target : fixture.hostDirectory() / target; + auto error = std::error_code {}; + if (std::filesystem::is_directory(named, error)) + std::filesystem::create_directory_symlink(target, fixture.hostDirectory() / name, error); + else + std::filesystem::create_symlink(target, fixture.hostDirectory() / name, error); + return !error; +} + +/// @param fixture The fixture. +/// @param path The host path. +/// @param open How to open it. +/// @return What the open answered. +FsResult> openHost(DescriptorFixture const& fixture, + std::filesystem::path const& path, + OpenFlags open = OpenFlags::None) +{ + return fixture.run(fixture.fileSystem().openHostFile(path, open)); +} + +/// @return The first 64 bytes @p descriptor reads, as text. +std::string contentOf(DescriptorFixture const& fixture, IDescriptor& descriptor) +{ + return textOf(fixture.run(descriptor.read(64, 0)).value().bytes); +} + +} // namespace + +TEST_CASE("host file: every link on the path is followed, an absolute one included", "[fs][contract][host]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.writeFile("data/target", "payload"); + auto const& host = fixture.hostDirectory(); + REQUIRE(hostLink(fixture, "absolute", host / "data" / "target")); + REQUIRE(hostLink(fixture, "via", host / "data")); + REQUIRE(hostLink(fixture, "relative", std::filesystem::path { "data" } / "target")); + REQUIRE(hostLink(fixture, "chain", host / "absolute")); + + for (auto const* name: { "absolute", "via/target", "relative", "chain" }) + { + INFO(name); + auto opened = openHost(fixture, host / name); + REQUIRE(opened.has_value()); + CHECK(fixture.run((*opened)->type()) == DescriptorType::RegularFile); + CHECK(contentOf(fixture, **opened) == "payload"); + } +} + +TEST_CASE("host file: a directory opens, and the caller's check on the handle refuses it", + "[fs][contract][host]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.writeFile("data/target", "payload"); + auto const& host = fixture.hostDirectory(); + + auto directory = openHost(fixture, host / "data"); + REQUIRE(directory.has_value()); + CHECK(fixture.run((*directory)->stat())->type == DescriptorType::Directory); + CHECK(openHost(fixture, host / "data", OpenFlags::Directory).has_value()); + CHECK(outcomeOf(openHost(fixture, host / "data" / "target", OpenFlags::Directory)) + == FsErrorCode::NotDirectory); +} + +TEST_CASE("host file: the descriptor carries Read alone", "[fs][contract][host]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.writeFile("target", "payload"); + + auto opened = openHost(fixture, fixture.hostDirectory() / "target"); + REQUIRE(opened.has_value()); + CHECK((*opened)->flags() == DescriptorFlags::Read); + CHECK(outcomeOf(fixture.run((*opened)->write(core::fs::test::bytesOf("x"), 0))) + == FsErrorCode::NotPermitted); + CHECK(contentOf(fixture, **opened) == "payload"); +} + +TEST_CASE("host file: what the open itself refuses", "[fs][contract][host]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.writeFile("target", "payload"); + auto const& host = fixture.hostDirectory(); + + CHECK(outcomeOf(openHost(fixture, host / "missing")) == FsErrorCode::NoEntry); + for (auto const open: { OpenFlags::Create, + OpenFlags::Truncate, + OpenFlags::Exclusive, + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly }) + CHECK(outcomeOf(openHost(fixture, host / "target", open)) == FsErrorCode::Invalid); + + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + return; + REQUIRE(hostLink(fixture, "loop", host / "loop")); + CHECK(outcomeOf(openHost(fixture, host / "loop")) == FsErrorCode::Loop); +} + +TEST_CASE("host file: the open file can be renamed and removed by another", "[fs][native][host]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.writeFile("target", "payload"); + auto const& host = fixture.hostDirectory(); + + auto opened = openHost(fixture, host / "target"); + REQUIRE(opened.has_value()); + // Windows: the open shares delete, so neither the rename nor the removal is refused by it. + auto error = std::error_code {}; + std::filesystem::rename(host / "target", host / "renamed", error); + CHECK_FALSE(error); + CHECK(contentOf(fixture, **opened) == "payload"); + CHECK(std::filesystem::remove(host / "renamed", error)); + CHECK_FALSE(error); +} + +TEST_CASE("host file: the model resolves a path from its root", "[fs][host]") +{ + auto fixture = DescriptorFixture::createInMemory(); + fixture.writeFile("data/target", "payload"); + + // `..` at the root stays there, and a path without a leading `/` starts there too. + for (auto const* path: { "/../root/data/target", "root/data/target", "/root/data/./target" }) + { + INFO(path); + auto opened = openHost(fixture, path); + REQUIRE(opened.has_value()); + CHECK(contentOf(fixture, **opened) == "payload"); + } + CHECK(outcomeOf(openHost(fixture, "/root/data/target/")) == FsErrorCode::NotDirectory); + CHECK(outcomeOf(openHost(fixture, "/root/data/target/below")) == FsErrorCode::NotDirectory); + fixture.inMemory().addSymlink("root/empty", ""); + CHECK(outcomeOf(openHost(fixture, "/root/empty")) == FsErrorCode::NoEntry); +} diff --git a/src/core/fs/Rights.cpp b/src/core/fs/Rights.cpp index 3a43bda3..4c8fbd2f 100644 --- a/src/core/fs/Rights.cpp +++ b/src/core/fs/Rights.cpp @@ -102,6 +102,13 @@ FsResult checkOpenRights(DescriptorFlags parent, OpenFlags open, Descripto return {}; } +FsResult checkHostOpenFlags(OpenFlags open) noexcept +{ + if ((static_cast(open) & ~static_cast(OpenFlags::Directory)) != 0) + return refuse(FsErrorCode::Invalid); + return {}; +} + DescriptorFlags grantedFlags(DescriptorType type, DescriptorFlags requested) noexcept { if (type == DescriptorType::Directory) diff --git a/src/core/fs/Rights.hpp b/src/core/fs/Rights.hpp index f244a6a2..3409c0d9 100644 --- a/src/core/fs/Rights.hpp +++ b/src/core/fs/Rights.hpp @@ -74,6 +74,12 @@ struct RightsRow OpenFlags open, DescriptorFlags child) noexcept; +/// Checks how @c IDescriptorFileSystem::openHostFile is asked to open: it opens to read, so only +/// `Directory` may be given; every flag that creates or changes a file is `Invalid`. +/// @param open How the host file is opened. +/// @return Nothing, or `Invalid`. +[[nodiscard]] CORE_FS_API FsResult checkHostOpenFlags(OpenFlags open) noexcept; + /// The flags a descriptor opened with @p requested carries once its object is known: only a /// directory carries `MutateDirectory`, so a file asked for it gets the rest, as in wasmtime. /// Together with @c checkOpenRights' rule that a directory never carries `Write`, this is what lets diff --git a/src/core/fs/linux/Lease.cpp b/src/core/fs/linux/Lease.cpp index 67803c80..fa34f273 100644 --- a/src/core/fs/linux/Lease.cpp +++ b/src/core/fs/linux/Lease.cpp @@ -27,7 +27,7 @@ FsResult openAfterWouldBlock(int directory, std::string const& nam .code = FsErrorCode::WouldBlock, .systemCode = EWOULDBLOCK, .context = why } }; }; auto const path = UniqueHandle { retryOnInterrupt( - [&] { return ::openat(directory, name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC); }) }; + [&] { return ::openat(directory, name.c_str(), O_PATH | (flags & O_NOFOLLOW) | O_CLOEXEC); }) }; if (path.get() < 0) return errnoError("openat(O_PATH)"); struct ::stat status {}; @@ -35,8 +35,9 @@ FsResult openAfterWouldBlock(int directory, std::string const& nam return errnoError("fstat"); if (!S_ISREG(status.st_mode)) return wouldBlock("the name no longer names a regular file"); - // The magic link resolves to the inode itself, so O_NOFOLLOW (which would refuse the link) and - // the creating flags (it exists) are dropped. + // The path handle follows a final link only where the flags do (a host file's open); the magic + // link resolves to the inode itself, so O_NOFOLLOW (which would refuse the link) and the + // creating flags (it exists) are dropped. auto const reopen = "/proc/self/fd/" + std::to_string(path.get()); auto const opened = retryOnInterrupt( [&] { return ::open(reopen.c_str(), flags & ~(O_NOFOLLOW | O_CREAT | O_EXCL | O_NONBLOCK)); }); diff --git a/src/core/fs/linux/Lease_test.cpp b/src/core/fs/linux/Lease_test.cpp index 937694de..5ddc72a6 100644 --- a/src/core/fs/linux/Lease_test.cpp +++ b/src/core/fs/linux/Lease_test.cpp @@ -4,7 +4,8 @@ // FIFO renamed over the name between the non-blocking open and this one is what the case below // stands for, deterministically: the name is a FIFO when the retry looks, and the retry answers // WouldBlock at once rather than waiting for a writer that never comes. Then the whole way, through -// openAt: a real lease the open must wait for, released by a thread that sees it being broken. +// openAt: a real lease the open must wait for, released by a thread that sees it being broken. A host +// path's final link is followed, unless the open says O_NOFOLLOW. #include #include #include @@ -59,6 +60,27 @@ TEST_CASE("lease retry: only a regular file is opened again, waiting", "[fs][nat CHECK(::pread(file->get(), text.data(), text.size(), 0) == 3); } +TEST_CASE("lease retry: a host path's final link is followed unless the open says O_NOFOLLOW", "[fs][native]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-lease-link" }; + { + auto file = std::ofstream { directory.path() / "f" }; + file << "abc"; + } + std::filesystem::create_symlink(directory.path() / "f", directory.path() / "link"); + auto const link = (directory.path() / "link").native(); + + auto const followed = openAfterWouldBlock(AT_FDCWD, link, O_RDONLY | O_CLOEXEC); + REQUIRE(followed.has_value()); + auto text = std::array {}; + CHECK(::pread(followed->get(), text.data(), text.size(), 0) == 3); + + // The path handle is the link's own then, which is no regular file. + auto const kept = openAfterWouldBlock(AT_FDCWD, link, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + REQUIRE_FALSE(kept.has_value()); + CHECK(kept.error().code == FsErrorCode::WouldBlock); +} + TEST_CASE("lease retry: openAt waits for a lease rather than answering WouldBlock", "[fs][native]") { auto fixture = DescriptorFixture::createNative(); diff --git a/src/core/fs/posix/PosixDescriptor.cpp b/src/core/fs/posix/PosixDescriptor.cpp index a804b4af..b8c23966 100644 --- a/src/core/fs/posix/PosixDescriptor.cpp +++ b/src/core/fs/posix/PosixDescriptor.cpp @@ -922,12 +922,61 @@ namespace }); } + async::Task>> openHostFile(std::filesystem::path hostPath, + OpenFlags open) override + { + return async::offload(_context->home, + _context->blocking, + [context = _context, + path = std::move(hostPath), + open]() -> FsResult> { + if (auto checked = checkHostOpenFlags(open); !checked) + return std::unexpected { checked.error() }; + // The user named this path, so the kernel resolves it and follows its + // links; only search access is needed on the way, as for any open by + // path. + auto flags = O_RDONLY | O_CLOEXEC | O_NOCTTY; + if (hasFlag(open, OpenFlags::Directory)) + flags |= O_DIRECTORY; + auto handle = openHostPath(path, flags); + if (!handle) + return std::unexpected { handle.error() }; + auto const status = statHandle(handle->get()); + if (!status) + return std::unexpected { status.error() }; + auto const type = typeOfMode(status->st_mode); + if (type == DescriptorType::RegularFile) + if (auto cleared = clearNonBlocking(handle->get()); !cleared) + return std::unexpected { cleared.error() }; + return std::make_unique( + context, + detail::shareHandle(std::move(*handle), *context->blocking), + SharedHandle {}, + grantedFlags(type, DescriptorFlags::Read), + type); + }); + } + async::Task> relation(IDescriptor const& first, IDescriptor const& second) override { return detail::relationOf(_context, first, second); } private: + /// Opens @p path `O_NONBLOCK`, so a FIFO with no writer opens at once; a regular file under + /// a lease answers EWOULDBLOCK then, and is opened again, waiting, through + /// @c detail::openAfterWouldBlock, which follows the link as this open did. + static FsResult openHostPath(std::filesystem::path const& path, int flags) + { + auto const opened = + detail::retryOnInterrupt([&] { return ::open(path.c_str(), flags | O_NONBLOCK); }); + if (opened >= 0) + return UniqueHandle { opened }; + if (std::ranges::find(WouldBlockErrnos, errno) != WouldBlockErrnos.end()) + return detail::openAfterWouldBlock(AT_FDCWD, path.native(), flags); + return detail::errnoError("open"); + } + SharedContext _context; }; diff --git a/src/core/fs/posix/PosixDescriptor_test.cpp b/src/core/fs/posix/PosixDescriptor_test.cpp index c95b13ba..568862f0 100644 --- a/src/core/fs/posix/PosixDescriptor_test.cpp +++ b/src/core/fs/posix/PosixDescriptor_test.cpp @@ -2,7 +2,9 @@ // // What only the POSIX descriptors owe: an open of a FIFO never waits for its other end, while a // regular file is opened blocking (a lease is broken and waited for rather than refused); a name -// that is not UTF-8, which only a POSIX file system holds, is refused for its entry alone. +// that is not UTF-8, which only a POSIX file system holds, is refused for its entry alone. A host +// file opens the same way, through links and beneath a directory its user may only search. +#include #include #include #include @@ -13,7 +15,9 @@ #include #include +#include #include +#include #include #include @@ -26,6 +30,7 @@ using core::fs::OpenFlags; using core::fs::SymlinkPolicy; using core::fs::test::DescriptorFixture; using core::fs::test::outcomeOf; +using core::fs::test::textOf; TEST_CASE("posix: a FIFO with no other end opens without waiting", "[fs][native]") { @@ -74,3 +79,44 @@ TEST_CASE("posix: a name that is not UTF-8 is IllegalByteSequence, and the strea CHECK(names == std::vector { "after", "before" }); CHECK(refused == std::vector { FsErrorCode::IllegalByteSequence }); } + +TEST_CASE("posix: a host FIFO opens without waiting, through a link", "[fs][native][host]") +{ + auto fixture = DescriptorFixture::createNative(); + auto const fifo = fixture.hostDirectory() / "fifo"; + REQUIRE(::mkfifo(fifo.c_str(), 0600) == 0); + REQUIRE(::symlink(fifo.c_str(), (fixture.hostDirectory() / "link").c_str()) == 0); + + // No writer will ever come: an open that waited for one would never return. + auto opened = + fixture.run(fixture.fileSystem().openHostFile(fixture.hostDirectory() / "link", OpenFlags::None)); + REQUIRE(opened.has_value()); + CHECK(fixture.run((*opened)->type()) == DescriptorType::Fifo); +} + +TEST_CASE("posix: a host file opens beneath a directory its user may only search", "[fs][native][host]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.writeFile("home/f", "payload"); + auto const home = fixture.hostDirectory() / "home"; + // A home of mode 0711 is search-only for everyone but its owner; 0100 makes it so for the owner too. + REQUIRE(::chmod(home.c_str(), 0100) == 0); + auto const restore = core::Finally { [&] { std::ignore = ::chmod(home.c_str(), 0700); } }; + + auto opened = fixture.run(fixture.fileSystem().openHostFile(home / "f", OpenFlags::None)); + REQUIRE(opened.has_value()); + CHECK(textOf(fixture.run((*opened)->read(64, 0)).value().bytes) == "payload"); + // What a preopen of the parent needs and is refused, unless the process may read anything. + if (::geteuid() != 0) + CHECK(outcomeOf(fixture.run(fixture.fileSystem().openPreopen(home, DescriptorFlags::Read))) + == FsErrorCode::Access); +} + +TEST_CASE("posix: a host path through a file is NotDirectory", "[fs][native][host]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.writeFile("f", "payload"); + CHECK(outcomeOf(fixture.run( + fixture.fileSystem().openHostFile(fixture.hostDirectory() / "f" / "below", OpenFlags::None))) + == FsErrorCode::NotDirectory); +} diff --git a/src/core/fs/posix/PosixSystem.hpp b/src/core/fs/posix/PosixSystem.hpp index 20a5c8a4..85c8f753 100644 --- a/src/core/fs/posix/PosixSystem.hpp +++ b/src/core/fs/posix/PosixSystem.hpp @@ -97,8 +97,9 @@ struct StatTimes /// only a lease on a regular file makes it answer. Where the system has leases (Linux), the name is /// opened as a path handle, checked by that handle to be a regular file, and reopened through it /// with @p flags, waiting for the lease to be broken: whatever was renamed over the name between -/// the two opens, a FIFO is never opened blocking. Elsewhere the answer is `WouldBlock`. -/// @param directory The directory @p name is in. +/// the two opens, a FIFO is never opened blocking. The path handle follows a final link unless +/// @p flags carry `O_NOFOLLOW`. Elsewhere the answer is `WouldBlock`. +/// @param directory The directory @p name is in, or `AT_FDCWD` for a host path. /// @param name The name. /// @param flags The open's flags, without `O_NONBLOCK`. /// @return The handle; `WouldBlock` where @p name no longer names a regular file or the system diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp index 4a9530e4..d8622bb0 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp @@ -353,6 +353,65 @@ struct InMemoryState }); } + /// Resolves @p path from the root as a host resolves a path its user named: every link is + /// followed, the final one included, an absolute target starts from the root again, and `..` at + /// the root stays there. A trailing `/` requires a directory. + /// @return What it names; `NoEntry`, `NotDirectory` where a component that is not a directory + /// has more after it, or `Loop` past @c DefaultMaxSymlinkHops links. + [[nodiscard]] FsResult resolveHost(std::string_view path) const + { + // The components still to walk, the next one last. + auto pending = std::vector {}; + auto const pushComponents = [&](std::string_view text) { + auto pieces = std::vector {}; + for (auto const piece: text | std::views::split('/')) + if (!std::string_view { piece }.empty()) + pieces.emplace_back(std::string_view { piece }); + if (text.ends_with('/')) + pieces.emplace_back("."); + for (auto& piece: pieces | std::views::reverse) + pending.push_back(std::move(piece)); + }; + auto directories = std::vector { RootInode }; + auto reached = std::optional {}; + auto hops = std::size_t { 0 }; + pushComponents(path); + while (!pending.empty()) + { + auto const name = std::move(pending.back()); + pending.pop_back(); + if (reached) + return refuse(FsErrorCode::NotDirectory); + if (name == ".") + continue; + if (name == "..") + { + if (directories.size() > 1) + directories.pop_back(); + continue; + } + auto const found = lookup(directories.back(), name); + if (!found) + return refuse(FsErrorCode::NoEntry); + auto const& node = nodes.at(*found); + if (node.type == DescriptorType::SymbolicLink) + { + if (node.target.empty()) + return refuse(FsErrorCode::NoEntry); + if (++hops > DefaultMaxSymlinkHops) + return refuse(FsErrorCode::Loop); + if (node.target.starts_with('/')) + directories.resize(1); + pushComponents(node.target); + } + else if (node.type == DescriptorType::Directory) + directories.push_back(*found); + else + reached = found; + } + return reached.value_or(directories.back()); + } + /// @return What @p path names; `NoEntry` where nothing does. [[nodiscard]] FsResult existing(std::uint64_t start, std::string_view path, @@ -1126,6 +1185,25 @@ async::Task>> InMemoryDescriptorFileSystem }); } +async::Task>> InMemoryDescriptorFileSystem::openHostFile( + std::filesystem::path hostPath, OpenFlags open) +{ + return async::offload( + _state->home, + _state->blocking, + [state = _state, path = hostPath.generic_string(), open]() -> FsResult> { + auto const lock = std::scoped_lock { state->mutex }; + auto const found = checkHostOpenFlags(open).and_then([&] { return state->resolveHost(path); }); + if (!found) + return std::unexpected { found.error() }; + auto const type = state->nodes.at(*found).type; + if (hasFlag(open, OpenFlags::Directory) && type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return std::make_unique( + state, *found, grantedFlags(type, DescriptorFlags::Read)); + }); +} + async::Task> InMemoryDescriptorFileSystem::relation(IDescriptor const& first, IDescriptor const& second) { diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp index 579884ed..1be39d7d 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp @@ -112,6 +112,18 @@ class CORE_FS_API InMemoryDescriptorFileSystem final: public IDescriptorFileSyst [[nodiscard]] async::Task>> openPreopen( std::filesystem::path hostDirectory, DescriptorFlags flags) override; + /// Opens the object @p hostPath names in the model, as a host resolves a path its user named: + /// from the model's root, whether the path is absolute or not, following every link on it, the + /// final one included, an absolute target from the root again and `..` at the root staying + /// there. A directory opens too; the caller decides on the handle. + /// @param hostPath A `/`-separated path from the root. + /// @param open `None`, or `Directory`; any other flag is `Invalid`. + /// @return The descriptor, carrying `Read`; `NoEntry`, `NotDirectory` where a component that is + /// not a directory has more after it (or `Directory` was asked of a file), or `Loop` past + /// @c DefaultMaxSymlinkHops links. + [[nodiscard]] async::Task>> openHostFile( + std::filesystem::path hostPath, OpenFlags open) override; + /// Walks each directory's parent links up to the model's root. A directory removed since it was /// opened has no parent: `NoEntry`, as a native `..` of it answers. /// @param first A directory of this model. diff --git a/src/core/fs/windows/WindowsDescriptor.cpp b/src/core/fs/windows/WindowsDescriptor.cpp index d437ece5..5b443206 100644 --- a/src/core/fs/windows/WindowsDescriptor.cpp +++ b/src/core/fs/windows/WindowsDescriptor.cpp @@ -1320,49 +1320,70 @@ namespace async::Task>> openPreopen(std::filesystem::path hostDirectory, DescriptorFlags flags) override { - return async::offload( - _context->home, - _context->blocking, - [context = _context, - path = std::move(hostDirectory), - flags]() -> FsResult> { - if (hasFlag(flags, DescriptorFlags::Write)) - return refuse(FsErrorCode::IsDirectory); - // READ_CONTROL: the root's stat reads who may reach it from this handle. - auto access = DWORD { FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES - | READ_CONTROL | SYNCHRONIZE }; - if (hasFlag(flags, DescriptorFlags::MutateDirectory)) - access |= FILE_WRITE_ATTRIBUTES; - // The host chose this directory, so the system resolves its path. - auto const openWith = [&](DWORD wanted) { - return ::CreateFileW(path.c_str(), - wanted, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, - OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT - | SECURITY_IDENTIFICATION, - nullptr); - }; - auto opened = openWith(access); - // A DACL that withholds READ_CONTROL opens the root without it: its access is unknown. - if (opened == INVALID_HANDLE_VALUE && ::GetLastError() == ERROR_ACCESS_DENIED) - opened = openWith(access & ~DWORD { READ_CONTROL }); - if (opened == INVALID_HANDLE_VALUE) - return lastError("CreateFileW"); - auto handle = UniqueHandle { opened }; - auto const information = informationOf(opened); - if (!information) - return std::unexpected { information.error() }; - if (typeOf(*information) != DescriptorType::Directory) - return refuse(FsErrorCode::NotDirectory); - return std::make_unique( - context, - detail::shareHandle(std::move(handle), *context->blocking), - SharedHandle {}, - grantedFlags(DescriptorType::Directory, flags), - DescriptorType::Directory); - }); + return async::offload(_context->home, + _context->blocking, + [context = _context, + path = std::move(hostDirectory), + flags]() -> FsResult> { + if (hasFlag(flags, DescriptorFlags::Write)) + return refuse(FsErrorCode::IsDirectory); + // READ_CONTROL: the root's stat reads who may reach it from this + // handle. + auto access = + DWORD { FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES + | READ_CONTROL | SYNCHRONIZE }; + if (hasFlag(flags, DescriptorFlags::MutateDirectory)) + access |= FILE_WRITE_ATTRIBUTES; + // The host chose this directory, so the system resolves its path. + auto handle = openHostPath(path, access); + if (!handle) + return std::unexpected { handle.error() }; + auto const information = informationOf(handle->get()); + if (!information) + return std::unexpected { information.error() }; + if (typeOf(*information) != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return std::make_unique( + context, + detail::shareHandle(std::move(*handle), *context->blocking), + SharedHandle {}, + grantedFlags(DescriptorType::Directory, flags), + DescriptorType::Directory); + }); + } + + async::Task>> openHostFile(std::filesystem::path hostPath, + OpenFlags open) override + { + return async::offload(_context->home, + _context->blocking, + [context = _context, + path = std::move(hostPath), + open]() -> FsResult> { + if (auto checked = checkHostOpenFlags(open); !checked) + return std::unexpected { checked.error() }; + // The user named this path, so the system resolves it and follows its + // links. A directory opens too (FILE_FLAG_BACKUP_SEMANTICS), and its + // FILE_LIST_DIRECTORY is FILE_READ_DATA's bit, so it reads and opens + // beneath as a preopen does; FILE_GENERIC_READ holds READ_CONTROL and + // FILE_READ_ATTRIBUTES, which a stat reads. + auto handle = openHostPath(path, FILE_GENERIC_READ); + if (!handle) + return std::unexpected { handle.error() }; + auto const information = informationOf(handle->get()); + if (!information) + return std::unexpected { information.error() }; + auto const type = typeOf(*information); + if (hasFlag(open, OpenFlags::Directory) + && type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return std::make_unique( + context, + detail::shareHandle(std::move(*handle), *context->blocking), + SharedHandle {}, + grantedFlags(type, DescriptorFlags::Read), + type); + }); } async::Task> relation(IDescriptor const& first, IDescriptor const& second) override @@ -1371,6 +1392,33 @@ namespace } private: + /// Opens @p path through the system's own resolution, sharing read, write and delete with + /// every other handle, so a reader or writer elsewhere neither refuses this open nor is + /// refused a rename or a removal by it. A DACL that withholds `READ_CONTROL` opens the object + /// without it: its access is unknown to a stat. + /// @param path The host path. + /// @param access What the handle asks for, `READ_CONTROL` among it. + /// @return The handle, or what `CreateFileW` answered. + static FsResult openHostPath(std::filesystem::path const& path, DWORD access) + { + auto const openWith = [&](DWORD wanted) { + return ::CreateFileW(path.c_str(), + wanted, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT + | SECURITY_IDENTIFICATION, + nullptr); + }; + auto opened = openWith(access); + if (opened == INVALID_HANDLE_VALUE && ::GetLastError() == ERROR_ACCESS_DENIED) + opened = openWith(access & ~DWORD { READ_CONTROL }); + if (opened == INVALID_HANDLE_VALUE) + return lastError("CreateFileW"); + return UniqueHandle { opened }; + } + SharedContext _context; };