Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agent/reference/provenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 12 additions & 2 deletions docs/modules/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ value.

| Header | What it has |
|---|---|
| `<core/fs/Descriptor.hpp>` | `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 |
| `<core/fs/Descriptor.hpp>` | `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 |
| `<core/fs/NativeFileSystem.hpp>` | `makeNativeDescriptorFileSystem(home, blocking, wallClock, random, options)`, `NativeFileSystemOptions`, `BeneathStrategy`, `DefaultMaxSymlinkHops` (40), `DefaultMaxAncestorDepth` (4,096) |
| `<core/fs/FsError.hpp>` | `FsErrorCode` and its `toString()`, `FsError` (a category, the raw errno, Win32 error or NTSTATUS, and a context), `FsResult<T>`; the classification tables `systemErrorTable()`, `ntStatusTable()`, `noFollowSymlinkErrnos()`, and `fsErrorFromSystemCode()`, `fsErrorFromNtStatus()` |
| `<core/fs/PathPolicy.hpp>` | `PathPolicy` (`PathEncoding`, `CaseRule`, `TrailingDotsAndSpaces`), `posixPathPolicy()`, `windowsPathPolicy()`, `nativePathPolicy()`, and `isRootedLinkTarget()` |
| `<core/fs/Rights.hpp>` | `Operation`, `RightsRow`, `rightsTable()`, `checkRights()`, `checkOpenRights()`, `grantedFlags()` |
| `<core/fs/Rights.hpp>` | `Operation`, `RightsRow`, `rightsTable()`, `checkRights()`, `checkOpenRights()`, `checkHostOpenFlags()`, `grantedFlags()` |
| `<core/fs/AccessScope.hpp>` | `AccessScope`, `AccessFacts`, `AccessEntry` and `classifyAccess()`, the pure decision of who may reach an object |
| `<core/fs/testing/InMemoryDescriptorFileSystem.hpp>` | `testing::InMemoryDescriptorFileSystem` and `testing::IdentityModel`: the same contract over nodes in memory |

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/core/fs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions src/core/fs/Descriptor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,27 @@ class IDescriptorFileSystem
[[nodiscard]] virtual async::Task<FsResult<std::unique_ptr<IDescriptor>>> 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<FsResult<std::unique_ptr<IDescriptor>>> 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
Expand Down
181 changes: 181 additions & 0 deletions src/core/fs/HostFile_test.cpp
Original file line number Diff line number Diff line change
@@ -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 <core/fs/Descriptor.hpp>
#include <core/fs/DescriptorTestSupport.hpp>
#include <core/fs/FsError.hpp>
#include <core/fs/testing/InMemoryDescriptorFileSystem.hpp>

#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>

#include <filesystem>
#include <initializer_list>
#include <memory>
#include <string>
#include <system_error>

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<std::unique_ptr<IDescriptor>> 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);
}
7 changes: 7 additions & 0 deletions src/core/fs/Rights.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ FsResult<void> checkOpenRights(DescriptorFlags parent, OpenFlags open, Descripto
return {};
}

FsResult<void> checkHostOpenFlags(OpenFlags open) noexcept
{
if ((static_cast<std::uint8_t>(open) & ~static_cast<std::uint8_t>(OpenFlags::Directory)) != 0)
return refuse(FsErrorCode::Invalid);
return {};
}

DescriptorFlags grantedFlags(DescriptorType type, DescriptorFlags requested) noexcept
{
if (type == DescriptorType::Directory)
Expand Down
6 changes: 6 additions & 0 deletions src/core/fs/Rights.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> 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
Expand Down
7 changes: 4 additions & 3 deletions src/core/fs/linux/Lease.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,17 @@ FsResult<UniqueHandle> 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 {};
if (::fstat(path.get(), &status) != 0)
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)); });
Expand Down
Loading
Loading