1669 lines
60 KiB
C++
1669 lines
60 KiB
C++
#pragma once
|
|
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/System/Types.hpp>
|
|
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <functional>
|
|
#include <optional>
|
|
#include <span>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
#ifndef _WIN32
|
|
#include <fcntl.h>
|
|
#include <sys/file.h>
|
|
#include <sys/ioctl.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/syscall.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
#if defined(__linux__)
|
|
#include <sys/random.h>
|
|
#if __has_include(<linux/fs.h>)
|
|
#include <linux/fs.h>
|
|
#endif
|
|
#endif
|
|
#else
|
|
#ifndef WIN32_LEAN_AND_MEAN
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#endif
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
#endif
|
|
|
|
namespace Void::FileSystem
|
|
{
|
|
|
|
struct ReadFileOptions {
|
|
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
|
};
|
|
|
|
/// How much `replace_file` guarantees before reporting success.
|
|
///
|
|
/// - `atomic_visibility`: publication is a single atomic directory-entry
|
|
/// replacement. A concurrent reader opens either the complete old file or the
|
|
/// complete new file, never a partial one. This survives an application
|
|
/// (process) crash: whatever rename already happened remains. It does *not*
|
|
/// promise that the new directory entry survives a power loss without a
|
|
/// subsequent `durable_sync`.
|
|
/// - `durable_sync`: additionally flushes the staged data before publication and
|
|
/// the parent directory after it. A successful return means the new contents
|
|
/// and their directory entry have reached stable storage (subject to the
|
|
/// device honoring flush requests).
|
|
///
|
|
/// Windows x64 notes:
|
|
/// - Staging uses an exclusively created (`CREATE_NEW`, share mode 0) temporary
|
|
/// file in the destination directory, so names never collide and no other
|
|
/// process can observe partial contents.
|
|
/// - Publication uses `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. On NTFS this is
|
|
/// one atomic directory-entry replacement, so readers observe old-or-new.
|
|
/// - `durable_sync` adds `MOVEFILE_WRITE_THROUGH`, `FlushFileBuffers` on the
|
|
/// staged file, and `FlushFileBuffers` on the parent directory handle. If the
|
|
/// flush after the rename fails the result is `ReplacePhase::sync_parent`
|
|
/// with `visible_on_disk = true` and `durability_unknown = true`: the new file
|
|
/// is visible but may not survive power loss.
|
|
/// - Application crash vs power loss: a crash keeps the rename that already
|
|
/// happened (atomic_visibility is enough); power loss may lose it unless
|
|
/// durable_sync succeeded. Even durable_sync depends on the volume and its
|
|
/// filter drivers honoring flushes (NTFS does; some network/antivirus layers
|
|
/// do not).
|
|
/// - Replacing a destination that another process opened without
|
|
/// `FILE_SHARE_DELETE` fails in the rename phase and leaves the destination
|
|
/// intact.
|
|
enum class ReplaceDurability {
|
|
atomic_visibility,
|
|
durable_sync,
|
|
};
|
|
|
|
enum class ReplacePhase {
|
|
validation,
|
|
create_stage,
|
|
write_stage,
|
|
sync_stage,
|
|
rename,
|
|
sync_parent,
|
|
};
|
|
|
|
struct ReplaceFailure {
|
|
Void::Result::Error error{};
|
|
ReplacePhase phase{ReplacePhase::validation};
|
|
bool visible_on_disk{false};
|
|
bool durability_unknown{false};
|
|
};
|
|
|
|
/// Optional test hook: return a POSIX errno to inject a failure at `phase`.
|
|
using ReplaceFaultHook = std::function<std::optional<int>(ReplacePhase phase)>;
|
|
|
|
struct ReplaceOptions {
|
|
ReplaceDurability durability{ReplaceDurability::durable_sync};
|
|
unsigned mode{0644};
|
|
ReplaceFaultHook fault_hook{};
|
|
};
|
|
|
|
namespace detail
|
|
{
|
|
|
|
[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept
|
|
{
|
|
static std::atomic<std::uint64_t> counter{0};
|
|
std::uint64_t rnd = 0;
|
|
#if defined(__linux__)
|
|
if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast<ssize_t>(sizeof(rnd))) {
|
|
return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12);
|
|
}
|
|
#endif
|
|
const auto now = static_cast<std::uint64_t>(
|
|
std::chrono::steady_clock::now().time_since_epoch().count());
|
|
return now ^ (counter.fetch_add(1, std::memory_order_relaxed) *
|
|
0x9e3779b97f4a7c15ULL);
|
|
}
|
|
|
|
#ifndef _WIN32
|
|
[[nodiscard]] inline int fsync_eintr(int fd) noexcept
|
|
{
|
|
for (;;) {
|
|
if (::fsync(fd) == 0) {
|
|
return 0;
|
|
}
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
return errno;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
} // namespace detail
|
|
|
|
#ifdef _WIN32
|
|
namespace detail
|
|
{
|
|
|
|
/// Owning wrapper for a Win32 HANDLE (INVALID_HANDLE_VALUE is the empty state).
|
|
class OwnedHandle
|
|
{
|
|
public:
|
|
OwnedHandle() noexcept = default;
|
|
explicit OwnedHandle(HANDLE handle) noexcept : handle_(handle) {}
|
|
~OwnedHandle() noexcept { reset(); }
|
|
|
|
OwnedHandle(const OwnedHandle&) = delete;
|
|
OwnedHandle& operator=(const OwnedHandle&) = delete;
|
|
|
|
OwnedHandle(OwnedHandle&& other) noexcept
|
|
: handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE))
|
|
{
|
|
}
|
|
|
|
OwnedHandle& operator=(OwnedHandle&& other) noexcept
|
|
{
|
|
if (this != &other) {
|
|
reset();
|
|
handle_ = std::exchange(other.handle_, INVALID_HANDLE_VALUE);
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
[[nodiscard]] bool valid() const noexcept
|
|
{
|
|
return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr;
|
|
}
|
|
[[nodiscard]] HANDLE get() const noexcept { return handle_; }
|
|
|
|
void reset(HANDLE handle = INVALID_HANDLE_VALUE) noexcept
|
|
{
|
|
const HANDLE old = std::exchange(handle_, handle);
|
|
if (old != INVALID_HANDLE_VALUE && old != nullptr) {
|
|
(void)::CloseHandle(old);
|
|
}
|
|
}
|
|
|
|
/// Close explicitly, reporting whether CloseHandle succeeded.
|
|
[[nodiscard]] bool close() noexcept
|
|
{
|
|
const HANDLE old = std::exchange(handle_, INVALID_HANDLE_VALUE);
|
|
if (old == INVALID_HANDLE_VALUE || old == nullptr) {
|
|
return true;
|
|
}
|
|
return ::CloseHandle(old) != 0;
|
|
}
|
|
|
|
private:
|
|
HANDLE handle_{INVALID_HANDLE_VALUE};
|
|
};
|
|
|
|
[[nodiscard]] inline std::string win32_message(DWORD error)
|
|
{
|
|
std::array<char, 512> buffer{};
|
|
const DWORD length = ::FormatMessageA(
|
|
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
|
nullptr,
|
|
error,
|
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
|
buffer.data(),
|
|
static_cast<DWORD>(buffer.size()),
|
|
nullptr);
|
|
std::string message = length != 0
|
|
? std::string{buffer.data(), length}
|
|
: std::string{"unknown error"};
|
|
while (!message.empty() &&
|
|
(message.back() == '\n' || message.back() == '\r' ||
|
|
message.back() == ' ' || message.back() == '.')) {
|
|
message.pop_back();
|
|
}
|
|
return message;
|
|
}
|
|
|
|
[[nodiscard]] inline Void::System::SystemErrorCode
|
|
map_win32_error(DWORD error) noexcept
|
|
{
|
|
switch (error) {
|
|
case ERROR_FILE_NOT_FOUND:
|
|
case ERROR_PATH_NOT_FOUND:
|
|
case ERROR_INVALID_DRIVE:
|
|
return Void::System::SystemErrorCode::not_found;
|
|
case ERROR_ACCESS_DENIED:
|
|
case ERROR_WRITE_PROTECT:
|
|
case ERROR_SHARING_VIOLATION:
|
|
case ERROR_LOCK_VIOLATION:
|
|
return Void::System::SystemErrorCode::permission_denied;
|
|
case ERROR_FILE_EXISTS:
|
|
case ERROR_ALREADY_EXISTS:
|
|
return Void::System::SystemErrorCode::already_exists;
|
|
case ERROR_INVALID_NAME:
|
|
case ERROR_INVALID_PARAMETER:
|
|
case ERROR_BAD_PATHNAME:
|
|
case ERROR_FILENAME_EXCED_RANGE:
|
|
return Void::System::SystemErrorCode::invalid_argument;
|
|
case ERROR_DISK_FULL:
|
|
case ERROR_HANDLE_DISK_FULL:
|
|
return Void::System::SystemErrorCode::limit_exceeded;
|
|
case ERROR_NOT_SUPPORTED:
|
|
case ERROR_CALL_NOT_IMPLEMENTED:
|
|
case ERROR_INVALID_FUNCTION:
|
|
return Void::System::SystemErrorCode::unsupported;
|
|
case ERROR_BUSY:
|
|
case ERROR_RETRY:
|
|
return Void::System::SystemErrorCode::busy;
|
|
case ERROR_OPERATION_ABORTED:
|
|
return Void::System::SystemErrorCode::cancelled;
|
|
case ERROR_TIMEOUT:
|
|
return Void::System::SystemErrorCode::timed_out;
|
|
case ERROR_NOT_ENOUGH_MEMORY:
|
|
case ERROR_OUTOFMEMORY:
|
|
return Void::System::SystemErrorCode::unavailable;
|
|
default:
|
|
return Void::System::SystemErrorCode::io_error;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] inline Void::Result::Error make_win32_error(
|
|
Void::System::SystemErrorCode code, std::string_view what, DWORD error)
|
|
{
|
|
return Void::System::make_system_error(
|
|
code,
|
|
std::format("{} (win32={}: {})", what, error, win32_message(error)));
|
|
}
|
|
|
|
} // namespace detail
|
|
#endif
|
|
|
|
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
|
///
|
|
/// The file is opened once and read through that single handle. The size is
|
|
/// checked before allocation and every chunk is checked again while reading,
|
|
/// so a file that grows after the initial size check still fails with
|
|
/// `limit_exceeded` and never returns partial contents.
|
|
///
|
|
/// Sharing: POSIX opens read-only; Windows opens with
|
|
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`, so another process
|
|
/// may append, rename or replace the path while a background read is pending.
|
|
/// The read continues from the already opened handle and sees one coherent
|
|
/// version of the file (the one that was opened), not a mixture with the
|
|
/// replacement. On both platforms the path is resolved once at open time.
|
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
|
read_file_bounded(const std::filesystem::path& path,
|
|
ReadFileOptions options = {})
|
|
{
|
|
#ifndef _WIN32
|
|
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::read_file: cannot open '{}'", path.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd guard{fd};
|
|
|
|
struct stat st {};
|
|
if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
|
|
const auto sz = static_cast<std::uint64_t>(st.st_size);
|
|
if (sz > options.max_bytes) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
|
|
path.string(),
|
|
sz,
|
|
options.max_bytes))};
|
|
}
|
|
}
|
|
|
|
std::string content;
|
|
std::array<char, 8192> buf{};
|
|
for (;;) {
|
|
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
|
if (n > 0) {
|
|
const auto un = static_cast<std::size_t>(n);
|
|
if (un > options.max_bytes - content.size()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
|
|
path.string(),
|
|
options.max_bytes))};
|
|
}
|
|
content.append(buf.data(), un);
|
|
} else if (n == 0) {
|
|
break;
|
|
} else {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"read_file: I/O error reading '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::read_file: I/O error reading '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
}
|
|
Void::Log::debug("FileSystem",
|
|
"read_file: '{}' ({} bytes)",
|
|
path.string(),
|
|
content.size());
|
|
return content;
|
|
#else
|
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
|
GENERIC_READ,
|
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
|
FILE_SHARE_DELETE,
|
|
nullptr,
|
|
OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL,
|
|
nullptr);
|
|
if (raw == INVALID_HANDLE_VALUE) {
|
|
const DWORD err = ::GetLastError();
|
|
Void::Log::warn(
|
|
"FileSystem", "read_file: cannot open '{}'", path.string());
|
|
return std::unexpected{detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::read_file: cannot open '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
detail::OwnedHandle handle{raw};
|
|
|
|
LARGE_INTEGER size{};
|
|
if (::GetFileSizeEx(handle.get(), &size) != 0 && size.QuadPart >= 0 &&
|
|
static_cast<std::uint64_t>(size.QuadPart) > options.max_bytes) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
|
|
path.string(),
|
|
static_cast<std::uint64_t>(size.QuadPart),
|
|
options.max_bytes))};
|
|
}
|
|
|
|
std::string content;
|
|
std::array<char, 8192> buffer{};
|
|
for (;;) {
|
|
DWORD read = 0;
|
|
if (::ReadFile(handle.get(),
|
|
buffer.data(),
|
|
static_cast<DWORD>(buffer.size()),
|
|
&read,
|
|
nullptr) == 0) {
|
|
const DWORD err = ::GetLastError();
|
|
Void::Log::warn(
|
|
"FileSystem", "read_file: I/O error reading '{}'", path.string());
|
|
return std::unexpected{detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::read_file: I/O error reading '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
if (read == 0) {
|
|
break;
|
|
}
|
|
const auto count = static_cast<std::size_t>(read);
|
|
if (count > options.max_bytes - content.size()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
|
|
path.string(),
|
|
options.max_bytes))};
|
|
}
|
|
content.append(buffer.data(), count);
|
|
}
|
|
Void::Log::debug("FileSystem",
|
|
"read_file: '{}' ({} bytes)",
|
|
path.string(),
|
|
content.size());
|
|
return content;
|
|
#endif
|
|
}
|
|
|
|
/// Read the entire contents of a file as a string (bounded at 16 MiB default).
|
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
|
read_file(const std::filesystem::path& path)
|
|
{
|
|
return read_file_bounded(path, ReadFileOptions{});
|
|
}
|
|
|
|
/// Write `content` to `path`, overwriting any existing file (not crash-safe).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
write_file(const std::filesystem::path& path, std::string_view content)
|
|
{
|
|
#ifndef _WIN32
|
|
const int fd =
|
|
::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
|
|
if (fd < 0) {
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"write_file: cannot open '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::write_file: cannot open '{}'", path.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd guard{fd};
|
|
|
|
std::size_t off = 0;
|
|
while (off < content.size()) {
|
|
const ssize_t n =
|
|
::write(fd, content.data() + off, content.size() - off);
|
|
if (n < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
Void::Log::warn("FileSystem",
|
|
"write_file: I/O error writing '{}'",
|
|
path.string());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::write_file: I/O error writing '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
off += static_cast<std::size_t>(n);
|
|
}
|
|
return guard.close();
|
|
#else
|
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
|
GENERIC_WRITE,
|
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
|
FILE_SHARE_DELETE,
|
|
nullptr,
|
|
CREATE_ALWAYS,
|
|
FILE_ATTRIBUTE_NORMAL,
|
|
nullptr);
|
|
if (raw == INVALID_HANDLE_VALUE) {
|
|
const DWORD err = ::GetLastError();
|
|
Void::Log::warn(
|
|
"FileSystem", "write_file: cannot open '{}'", path.string());
|
|
return std::unexpected{detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::write_file: cannot open '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
detail::OwnedHandle handle{raw};
|
|
|
|
std::size_t offset = 0;
|
|
while (offset < content.size()) {
|
|
const auto remaining = content.size() - offset;
|
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
|
const DWORD chunk = static_cast<DWORD>(
|
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
|
DWORD written = 0;
|
|
if (::WriteFile(handle.get(),
|
|
content.data() + offset,
|
|
chunk,
|
|
&written,
|
|
nullptr) == 0) {
|
|
const DWORD err = ::GetLastError();
|
|
Void::Log::warn(
|
|
"FileSystem", "write_file: I/O error writing '{}'", path.string());
|
|
return std::unexpected{detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::write_file: I/O error writing '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
offset += written;
|
|
}
|
|
if (!handle.close()) {
|
|
const DWORD err = ::GetLastError();
|
|
return std::unexpected{detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::write_file: close failed for '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
return {};
|
|
#endif
|
|
}
|
|
|
|
/// Atomically stage and replace `path`, distinguishing atomic visibility vs
|
|
/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir).
|
|
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
|
|
const std::filesystem::path& path,
|
|
std::span<const std::byte> bytes,
|
|
ReplaceOptions options = {})
|
|
{
|
|
#ifndef _WIN32
|
|
auto check_fault = [&](ReplacePhase phase,
|
|
bool visible,
|
|
bool unknown) -> std::optional<ReplaceFailure> {
|
|
if (options.fault_hook) {
|
|
if (const auto injected = options.fault_hook(phase)) {
|
|
return ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
unknown
|
|
? Void::System::SystemErrorCode::durability_unknown
|
|
: Void::System::map_errno_to_system_code(*injected),
|
|
std::format("FileSystem::replace_file: injected fault for '{}'",
|
|
path.string()),
|
|
*injected),
|
|
phase,
|
|
visible,
|
|
unknown};
|
|
}
|
|
}
|
|
return std::nullopt;
|
|
};
|
|
|
|
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
if (path.empty() || !path.has_filename()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: empty path or missing filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
const std::filesystem::path parent =
|
|
path.parent_path().empty() ? std::filesystem::path{"."}
|
|
: path.parent_path();
|
|
const std::string target_name = path.filename().string();
|
|
if (target_name == "." || target_name == "..") {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: invalid target filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
const int raw_dir_fd = ::open(
|
|
parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
|
if (raw_dir_fd < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: cannot open parent '{}'",
|
|
parent.string()),
|
|
err),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
Void::System::OwnedFd dir_fd{raw_dir_fd};
|
|
|
|
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::string tmp_name;
|
|
Void::System::OwnedFd tmp_fd;
|
|
int last_err = 0;
|
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
|
tmp_name = std::format(
|
|
".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy());
|
|
const int fd = ::openat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW |
|
|
O_CLOEXEC,
|
|
static_cast<mode_t>(options.mode));
|
|
if (fd >= 0) {
|
|
tmp_fd.reset(fd);
|
|
break;
|
|
}
|
|
last_err = errno;
|
|
if (last_err != EEXIST) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(last_err),
|
|
std::format(
|
|
"FileSystem::replace_file: cannot create temp in '{}'",
|
|
parent.string()),
|
|
last_err),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
if (!tmp_fd.valid()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::already_exists,
|
|
"FileSystem::replace_file: exhausted temp names",
|
|
last_err),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
bool cleanup_temp = true;
|
|
struct TempCleanup {
|
|
int dir_fd{-1};
|
|
const std::string* name{nullptr};
|
|
bool* active{nullptr};
|
|
~TempCleanup() noexcept
|
|
{
|
|
if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) {
|
|
(void)::unlinkat(dir_fd, name->c_str(), 0);
|
|
}
|
|
}
|
|
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp};
|
|
|
|
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::size_t off = 0;
|
|
while (off < bytes.size()) {
|
|
const ssize_t n =
|
|
::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off);
|
|
if (n < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: write failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
off += static_cast<std::size_t>(n);
|
|
}
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::sync_failed,
|
|
std::format(
|
|
"FileSystem::replace_file: stage fsync failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
|
|
if (auto closed = tmp_fd.close(); !closed.has_value()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
std::move(closed.error()),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
if (::renameat(
|
|
dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) !=
|
|
0) {
|
|
const int err = errno;
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::replace_file: rename failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::rename,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
// Rename succeeded: target is now visible on disk; never unlink target!
|
|
cleanup_temp = false;
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::durability_unknown,
|
|
std::format(
|
|
"FileSystem::replace_file: parent dir fsync failed after rename for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_parent,
|
|
true,
|
|
true}};
|
|
}
|
|
}
|
|
|
|
Void::Log::debug("FileSystem",
|
|
"replace_file: '{}' committed ({} bytes)",
|
|
path.string(),
|
|
bytes.size());
|
|
return {};
|
|
#else
|
|
auto check_fault = [&](ReplacePhase phase,
|
|
bool visible,
|
|
bool unknown) -> std::optional<ReplaceFailure> {
|
|
if (options.fault_hook) {
|
|
if (const auto injected = options.fault_hook(phase)) {
|
|
return ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
unknown
|
|
? Void::System::SystemErrorCode::durability_unknown
|
|
: Void::System::map_errno_to_system_code(*injected),
|
|
std::format("FileSystem::replace_file: injected fault for '{}'",
|
|
path.string()),
|
|
*injected),
|
|
phase,
|
|
visible,
|
|
unknown};
|
|
}
|
|
}
|
|
return std::nullopt;
|
|
};
|
|
|
|
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
if (path.empty() || !path.has_filename()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: empty path or missing filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
const std::filesystem::path parent =
|
|
path.parent_path().empty() ? std::filesystem::path{"."}
|
|
: path.parent_path();
|
|
const std::wstring target_name = path.filename().wstring();
|
|
if (target_name == L"." || target_name == L"..") {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::replace_file: invalid target filename"),
|
|
ReplacePhase::validation,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::filesystem::path temp_path;
|
|
detail::OwnedHandle temp_handle;
|
|
DWORD last_err = 0;
|
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
|
const auto entropy = detail::next_temp_entropy();
|
|
const std::string tail = std::format("{:016x}", entropy);
|
|
std::wstring name = L".";
|
|
name += target_name;
|
|
name += L".void_tmp_";
|
|
name.append(tail.begin(), tail.end());
|
|
temp_path = parent / name;
|
|
const HANDLE raw = ::CreateFileW(temp_path.c_str(),
|
|
GENERIC_WRITE,
|
|
0,
|
|
nullptr,
|
|
CREATE_NEW,
|
|
FILE_ATTRIBUTE_NORMAL,
|
|
nullptr);
|
|
if (raw != INVALID_HANDLE_VALUE) {
|
|
temp_handle.reset(raw);
|
|
break;
|
|
}
|
|
last_err = ::GetLastError();
|
|
if (last_err != ERROR_FILE_EXISTS && last_err != ERROR_ALREADY_EXISTS) {
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
detail::map_win32_error(last_err),
|
|
std::format(
|
|
"FileSystem::replace_file: cannot create temp in '{}'",
|
|
parent.string()),
|
|
last_err),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
if (!temp_handle.valid()) {
|
|
return std::unexpected{ReplaceFailure{
|
|
Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::already_exists,
|
|
"FileSystem::replace_file: exhausted temp names",
|
|
static_cast<int>(last_err)),
|
|
ReplacePhase::create_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
bool cleanup_temp = true;
|
|
struct TempCleanup {
|
|
const std::filesystem::path* path{nullptr};
|
|
bool* active{nullptr};
|
|
~TempCleanup() noexcept
|
|
{
|
|
if (active != nullptr && *active && path != nullptr) {
|
|
(void)::DeleteFileW(path->c_str());
|
|
}
|
|
}
|
|
} temp_guard{&temp_path, &cleanup_temp};
|
|
|
|
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
std::size_t offset = 0;
|
|
while (offset < bytes.size()) {
|
|
const auto remaining = bytes.size() - offset;
|
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
|
const DWORD chunk = static_cast<DWORD>(
|
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
|
DWORD written = 0;
|
|
if (::WriteFile(temp_handle.get(),
|
|
bytes.data() + offset,
|
|
chunk,
|
|
&written,
|
|
nullptr) == 0) {
|
|
const DWORD err = ::GetLastError();
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format(
|
|
"FileSystem::replace_file: write failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
offset += written;
|
|
}
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
if (::FlushFileBuffers(temp_handle.get()) == 0) {
|
|
const DWORD err = ::GetLastError();
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
Void::System::SystemErrorCode::sync_failed,
|
|
std::format(
|
|
"FileSystem::replace_file: stage flush failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
}
|
|
|
|
if (!temp_handle.close()) {
|
|
const DWORD err = ::GetLastError();
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format(
|
|
"FileSystem::replace_file: close failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::write_stage,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
|
|
DWORD move_flags = MOVEFILE_REPLACE_EXISTING;
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
move_flags |= MOVEFILE_WRITE_THROUGH;
|
|
}
|
|
if (::MoveFileExW(temp_path.c_str(), path.c_str(), move_flags) == 0) {
|
|
const DWORD err = ::GetLastError();
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
detail::map_win32_error(err),
|
|
std::format("FileSystem::replace_file: rename failed for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::rename,
|
|
false,
|
|
false}};
|
|
}
|
|
|
|
// Rename succeeded: target is now visible on disk; never delete target!
|
|
cleanup_temp = false;
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
|
|
return std::unexpected{std::move(*f)};
|
|
}
|
|
bool flushed = false;
|
|
DWORD err = 0;
|
|
const HANDLE dir_raw = ::CreateFileW(parent.c_str(),
|
|
GENERIC_READ,
|
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
|
nullptr,
|
|
OPEN_EXISTING,
|
|
FILE_FLAG_BACKUP_SEMANTICS,
|
|
nullptr);
|
|
if (dir_raw != INVALID_HANDLE_VALUE) {
|
|
detail::OwnedHandle dir_handle{dir_raw};
|
|
flushed = ::FlushFileBuffers(dir_handle.get()) != 0;
|
|
if (!flushed) {
|
|
err = ::GetLastError();
|
|
}
|
|
} else {
|
|
err = ::GetLastError();
|
|
}
|
|
if (!flushed) {
|
|
return std::unexpected{ReplaceFailure{
|
|
detail::make_win32_error(
|
|
Void::System::SystemErrorCode::durability_unknown,
|
|
std::format(
|
|
"FileSystem::replace_file: parent dir flush failed after rename for '{}'",
|
|
path.string()),
|
|
err),
|
|
ReplacePhase::sync_parent,
|
|
true,
|
|
true}};
|
|
}
|
|
}
|
|
|
|
Void::Log::debug("FileSystem",
|
|
"replace_file: '{}' committed ({} bytes)",
|
|
path.string(),
|
|
bytes.size());
|
|
return {};
|
|
#endif
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
|
|
const std::filesystem::path& path,
|
|
std::string_view content,
|
|
ReplaceOptions options = {})
|
|
{
|
|
const auto* ptr = reinterpret_cast<const std::byte*>(content.data());
|
|
return replace_file(path, std::span<const std::byte>{ptr, content.size()}, std::move(options));
|
|
}
|
|
|
|
/// Crash-safe write: stages content in a unique temp file and atomically
|
|
/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to
|
|
/// preserve 1.x atomic replacement behavior safely across concurrent writers.
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
atomic_write(const std::filesystem::path& path, std::string_view content)
|
|
{
|
|
auto res = replace_file(
|
|
path,
|
|
content,
|
|
ReplaceOptions{.durability = ReplaceDurability::atomic_visibility});
|
|
if (!res.has_value()) {
|
|
Void::Log::warn("FileSystem",
|
|
"atomic_write: failed for '{}': {}",
|
|
path.string(),
|
|
res.error().error.message());
|
|
return std::unexpected{std::move(res.error().error)};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
/// Create `path` as a directory, including any missing parents.
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
ensure_directory(const std::filesystem::path& path)
|
|
{
|
|
std::error_code ec;
|
|
if (std::filesystem::is_directory(path, ec)) {
|
|
return {};
|
|
}
|
|
std::filesystem::create_directories(path, ec);
|
|
if (ec) {
|
|
Void::Log::warn("FileSystem",
|
|
"ensure_directory: cannot create '{}': {}",
|
|
path.string(),
|
|
ec.message());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(ec.value()),
|
|
std::format("FileSystem::ensure_directory: cannot create '{}': {}",
|
|
path.string(),
|
|
ec.message()))};
|
|
}
|
|
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
|
|
return {};
|
|
}
|
|
|
|
/// Remove a file or directory (recursively for directories).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
remove_path(const std::filesystem::path& path)
|
|
{
|
|
std::error_code ec;
|
|
std::filesystem::remove_all(path, ec);
|
|
if (ec) {
|
|
Void::Log::warn("FileSystem",
|
|
"remove_path: cannot remove '{}': {}",
|
|
path.string(),
|
|
ec.message());
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(ec.value()),
|
|
std::format("FileSystem::remove_path: cannot remove '{}': {}",
|
|
path.string(),
|
|
ec.message()))};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
|
|
|
|
enum class LockMode : std::uint8_t {
|
|
Shared,
|
|
Exclusive,
|
|
};
|
|
|
|
/// RAII advisory file lock backed by POSIX flock(2).
|
|
class FileLock final
|
|
{
|
|
public:
|
|
FileLock() noexcept = default;
|
|
~FileLock() noexcept { unlock(); }
|
|
|
|
FileLock(const FileLock&) = delete;
|
|
FileLock& operator=(const FileLock&) = delete;
|
|
|
|
FileLock(FileLock&& other) noexcept
|
|
: fd_(std::move(other.fd_))
|
|
, mode_(other.mode_)
|
|
{
|
|
}
|
|
|
|
FileLock& operator=(FileLock&& other) noexcept
|
|
{
|
|
if (this != &other) {
|
|
unlock();
|
|
fd_ = std::move(other.fd_);
|
|
mode_ = other.mode_;
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
|
|
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
|
|
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
|
|
|
|
void unlock() noexcept
|
|
{
|
|
#ifndef _WIN32
|
|
if (fd_.valid()) {
|
|
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
|
|
}
|
|
fd_.reset();
|
|
}
|
|
#endif
|
|
}
|
|
|
|
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
|
|
lock(const std::filesystem::path& path,
|
|
LockMode mode = LockMode::Exclusive)
|
|
{
|
|
auto res = acquire(path, mode, false);
|
|
if (!res.has_value()) {
|
|
return std::unexpected{std::move(res.error())};
|
|
}
|
|
if (!res->has_value()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::internal,
|
|
"FileSystem::FileLock::lock: unexpected empty result")};
|
|
}
|
|
return std::move(**res);
|
|
}
|
|
|
|
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
|
|
Void::Result::Error>
|
|
try_lock(const std::filesystem::path& path,
|
|
LockMode mode = LockMode::Exclusive)
|
|
{
|
|
return acquire(path, mode, true);
|
|
}
|
|
|
|
private:
|
|
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
|
|
: fd_(std::move(fd))
|
|
, mode_(mode)
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
|
|
Void::Result::Error>
|
|
acquire(const std::filesystem::path& path,
|
|
LockMode mode,
|
|
bool nonblocking)
|
|
{
|
|
#ifndef _WIN32
|
|
if (path.empty()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::FileLock: empty path")};
|
|
}
|
|
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
|
|
if (raw < 0 && mode == LockMode::Shared &&
|
|
(errno == EACCES || errno == EROFS)) {
|
|
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
}
|
|
if (raw < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::FileLock: cannot open '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd fd{raw};
|
|
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
|
|
(nonblocking ? LOCK_NB : 0);
|
|
for (;;) {
|
|
if (::flock(fd.get(), op) == 0) {
|
|
return std::optional<FileLock>{
|
|
FileLock{std::move(fd), mode}};
|
|
}
|
|
const int err = errno;
|
|
if (err == EINTR) {
|
|
continue;
|
|
}
|
|
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
|
|
return std::optional<FileLock>{std::nullopt};
|
|
}
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::FileLock: flock failed for '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
#else
|
|
(void)path;
|
|
(void)mode;
|
|
(void)nonblocking;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::FileLock: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
Void::System::OwnedFd fd_{};
|
|
LockMode mode_{LockMode::Exclusive};
|
|
};
|
|
|
|
/// Atomically create or replace symlink at `link_path` pointing to `target`
|
|
/// (symlinkat temp -> renameat -> optional parent dir fsync).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
atomic_symlink_swap(
|
|
const std::filesystem::path& link_path,
|
|
const std::filesystem::path& target,
|
|
ReplaceDurability durability = ReplaceDurability::durable_sync)
|
|
{
|
|
#ifndef _WIN32
|
|
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::atomic_symlink_swap: empty link or target path")};
|
|
}
|
|
const std::string target_name = link_path.filename().string();
|
|
if (target_name == "." || target_name == "..") {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::atomic_symlink_swap: invalid link filename")};
|
|
}
|
|
const std::filesystem::path parent =
|
|
link_path.parent_path().empty() ? std::filesystem::path{"."}
|
|
: link_path.parent_path();
|
|
const int raw_dir =
|
|
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
|
if (raw_dir < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
|
|
parent.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd dir_fd{raw_dir};
|
|
|
|
std::string tmp_name;
|
|
bool created = false;
|
|
int last_err = 0;
|
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
|
tmp_name = std::format(
|
|
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
|
|
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
|
|
created = true;
|
|
break;
|
|
}
|
|
last_err = errno;
|
|
if (last_err != EEXIST) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(last_err),
|
|
std::format(
|
|
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
|
|
parent.string()),
|
|
last_err)};
|
|
}
|
|
}
|
|
if (!created) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::already_exists,
|
|
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
|
|
last_err)};
|
|
}
|
|
|
|
bool cleanup = true;
|
|
struct CleanupGuard {
|
|
int dfd{-1};
|
|
const std::string* name{nullptr};
|
|
bool* active{nullptr};
|
|
~CleanupGuard() noexcept
|
|
{
|
|
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
|
|
(void)::unlinkat(dfd, name->c_str(), 0);
|
|
}
|
|
}
|
|
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
|
|
|
|
if (::renameat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
dir_fd.get(),
|
|
target_name.c_str()) != 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
|
|
link_path.string()),
|
|
err)};
|
|
}
|
|
cleanup = false;
|
|
|
|
if (durability == ReplaceDurability::durable_sync) {
|
|
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::durability_unknown,
|
|
std::format(
|
|
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
|
|
link_path.string()),
|
|
err)};
|
|
}
|
|
}
|
|
return {};
|
|
#else
|
|
(void)link_path;
|
|
(void)target;
|
|
(void)durability;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::atomic_symlink_swap: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
enum class CopyMethod : std::uint8_t {
|
|
Reflink,
|
|
PrivateCopy,
|
|
};
|
|
|
|
struct CopyResult {
|
|
std::uint64_t bytes{0};
|
|
CopyMethod method{CopyMethod::PrivateCopy};
|
|
};
|
|
|
|
struct CopyOptions {
|
|
bool overwrite{true};
|
|
bool preserve_permissions{true};
|
|
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
|
|
};
|
|
|
|
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
|
|
/// staging and private-copy fallback. Explicitly never creates hardlinks.
|
|
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
|
|
reflink_copy_file(const std::filesystem::path& src,
|
|
const std::filesystem::path& dst,
|
|
CopyOptions options = {})
|
|
{
|
|
#ifndef _WIN32
|
|
if (src.empty() || dst.empty() || !dst.has_filename()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::reflink_copy_file: invalid source or destination path")};
|
|
}
|
|
const std::string dst_name = dst.filename().string();
|
|
if (dst_name == "." || dst_name == "..") {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::reflink_copy_file: invalid destination filename")};
|
|
}
|
|
|
|
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
|
|
if (raw_src < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
|
|
src.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd src_fd{raw_src};
|
|
|
|
struct stat src_st {};
|
|
if (::fstat(src_fd.get(), &src_st) != 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
|
|
src.string()),
|
|
err)};
|
|
}
|
|
if (!S_ISREG(src_st.st_mode)) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
|
|
src.string()))};
|
|
}
|
|
|
|
const std::filesystem::path parent =
|
|
dst.parent_path().empty() ? std::filesystem::path{"."}
|
|
: dst.parent_path();
|
|
const int raw_dir =
|
|
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
|
if (raw_dir < 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
|
|
parent.string()),
|
|
err)};
|
|
}
|
|
Void::System::OwnedFd dir_fd{raw_dir};
|
|
|
|
const mode_t create_mode = options.preserve_permissions
|
|
? static_cast<mode_t>(src_st.st_mode & 0777)
|
|
: static_cast<mode_t>(0644);
|
|
std::string tmp_name;
|
|
Void::System::OwnedFd tmp_fd;
|
|
int last_err = 0;
|
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
|
tmp_name = std::format(
|
|
".{}.void_cp_{:016x}", dst_name, detail::next_temp_entropy());
|
|
const int fd = ::openat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
|
|
O_CLOEXEC,
|
|
create_mode);
|
|
if (fd >= 0) {
|
|
tmp_fd.reset(fd);
|
|
break;
|
|
}
|
|
last_err = errno;
|
|
if (last_err != EEXIST) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(last_err),
|
|
std::format("FileSystem::reflink_copy_file: create temp in '{}'",
|
|
parent.string()),
|
|
last_err)};
|
|
}
|
|
}
|
|
if (!tmp_fd.valid()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::already_exists,
|
|
"FileSystem::reflink_copy_file: exhausted temp names",
|
|
last_err)};
|
|
}
|
|
|
|
bool cleanup_tmp = true;
|
|
struct TempGuard {
|
|
int dfd{-1};
|
|
const std::string* name{nullptr};
|
|
bool* active{nullptr};
|
|
~TempGuard() noexcept
|
|
{
|
|
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
|
|
(void)::unlinkat(dfd, name->c_str(), 0);
|
|
}
|
|
}
|
|
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
|
|
|
|
CopyResult result;
|
|
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
|
|
bool cloned = false;
|
|
|
|
#if defined(__linux__) && defined(FICLONE)
|
|
for (;;) {
|
|
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
|
|
cloned = true;
|
|
result.method = CopyMethod::Reflink;
|
|
break;
|
|
}
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
|
|
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
|
|
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|
|
|| err == ENOTSUP
|
|
#endif
|
|
) {
|
|
break;
|
|
}
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
#endif
|
|
|
|
if (!cloned) {
|
|
result.method = CopyMethod::PrivateCopy;
|
|
std::vector<char> buf(64ULL * 1024ULL);
|
|
std::uint64_t copied = 0;
|
|
for (;;) {
|
|
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
|
|
if (r > 0) {
|
|
std::size_t off = 0;
|
|
const auto ur = static_cast<std::size_t>(r);
|
|
while (off < ur) {
|
|
const ssize_t w =
|
|
::write(tmp_fd.get(), buf.data() + off, ur - off);
|
|
if (w < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format(
|
|
"FileSystem::reflink_copy_file: write failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
off += static_cast<std::size_t>(w);
|
|
}
|
|
copied += ur;
|
|
} else if (r == 0) {
|
|
break;
|
|
} else {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format(
|
|
"FileSystem::reflink_copy_file: read failed on '{}'",
|
|
src.string()),
|
|
err)};
|
|
}
|
|
}
|
|
result.bytes = copied;
|
|
}
|
|
|
|
if (options.preserve_permissions) {
|
|
(void)::fchmod(tmp_fd.get(), create_mode);
|
|
}
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::sync_failed,
|
|
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
}
|
|
|
|
if (auto closed = tmp_fd.close(); !closed.has_value()) {
|
|
return std::unexpected{std::move(closed.error())};
|
|
}
|
|
|
|
if (options.overwrite) {
|
|
if (::renameat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
dir_fd.get(),
|
|
dst_name.c_str()) != 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
} else {
|
|
if (::linkat(dir_fd.get(),
|
|
tmp_name.c_str(),
|
|
dir_fd.get(),
|
|
dst_name.c_str(),
|
|
0) != 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
|
|
}
|
|
cleanup_tmp = false;
|
|
|
|
if (options.durability == ReplaceDurability::durable_sync) {
|
|
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::durability_unknown,
|
|
std::format(
|
|
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
|
|
dst.string()),
|
|
err)};
|
|
}
|
|
}
|
|
|
|
return result;
|
|
#else
|
|
(void)src;
|
|
(void)dst;
|
|
(void)options;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::reflink_copy_file: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
/// Set access and modification timestamps without dereferencing symlinks.
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
set_timestamps_nofollow(const std::filesystem::path& path,
|
|
std::int64_t atime_sec,
|
|
std::int32_t atime_nsec,
|
|
std::int64_t mtime_sec,
|
|
std::int32_t mtime_nsec)
|
|
{
|
|
#ifndef _WIN32
|
|
if (path.empty()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::set_timestamps_nofollow: empty path")};
|
|
}
|
|
auto valid_nsec = [](std::int32_t ns) noexcept {
|
|
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
|
|
ns == UTIME_OMIT;
|
|
};
|
|
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
|
|
}
|
|
struct timespec ts[2]{};
|
|
ts[0].tv_sec = static_cast<time_t>(atime_sec);
|
|
ts[0].tv_nsec = static_cast<long>(atime_nsec);
|
|
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
|
|
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
|
|
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
|
|
const int err = errno;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::map_errno_to_system_code(err),
|
|
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
|
|
path.string()),
|
|
err)};
|
|
}
|
|
return {};
|
|
#else
|
|
(void)path;
|
|
(void)atime_sec;
|
|
(void)atime_nsec;
|
|
(void)mtime_sec;
|
|
(void)mtime_nsec;
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::unsupported,
|
|
"FileSystem::set_timestamps_nofollow: unsupported platform")};
|
|
#endif
|
|
}
|
|
|
|
/// Set canonical modification and access timestamps (default UNIX epoch 0)
|
|
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
set_canonical_mtime(const std::filesystem::path& path,
|
|
std::int64_t unix_seconds = 0,
|
|
std::int32_t nanoseconds = 0)
|
|
{
|
|
return set_timestamps_nofollow(
|
|
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
|
|
}
|
|
|
|
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
|
|
set_canonical_mtime(const std::filesystem::path& path,
|
|
std::chrono::sys_seconds tp)
|
|
{
|
|
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
|
|
}
|
|
|
|
} // namespace Void::FileSystem
|