1 parent
8583a479dd
commit
3851aeb703
42 files changed
+6948
-759
No files matched your search
@@ -0,0 +1,652 @@
|
||||
#include <Void/Archive/Archive.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#else
|
||||
#include <fstream>
|
||||
#endif
|
||||
|
||||
namespace Void::Archive
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using ArchiveHandle =
|
||||
std::unique_ptr<archive, decltype(&archive_read_free)>;
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
archive_error(archive *reader, std::string_view operation)
|
||||
{
|
||||
const char *message = archive_error_string(reader);
|
||||
return Void::Result::Error{std::format(
|
||||
"Archive::extract: {}: {}", operation,
|
||||
message == nullptr ? "unknown archive error" : message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::filesystem::path>
|
||||
safe_relative_path(std::string_view rawPath, bool directory)
|
||||
{
|
||||
if (rawPath.empty() ||
|
||||
rawPath.find('\\') != std::string_view::npos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if (rawPath.back() == '/') {
|
||||
if (!directory) {
|
||||
return std::nullopt;
|
||||
}
|
||||
rawPath.remove_suffix(1);
|
||||
if (rawPath.empty() || rawPath.back() == '/') {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
if (rawPath.front() == '/' ||
|
||||
rawPath.find("//") != std::string_view::npos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const std::filesystem::path path{rawPath};
|
||||
if (path.empty() || path.is_absolute() || path.has_root_name() ||
|
||||
path.lexically_normal() != path) {
|
||||
return std::nullopt;
|
||||
}
|
||||
for (const auto &component : path) {
|
||||
if (component.empty() || component == "." ||
|
||||
component == "..") {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
class FileDescriptor
|
||||
{
|
||||
public:
|
||||
|
||||
explicit FileDescriptor(int descriptor = -1) noexcept
|
||||
: m_descriptor(descriptor)
|
||||
{
|
||||
}
|
||||
|
||||
~FileDescriptor() { reset(); }
|
||||
|
||||
FileDescriptor(FileDescriptor &&other) noexcept
|
||||
: m_descriptor(std::exchange(other.m_descriptor, -1))
|
||||
{
|
||||
}
|
||||
|
||||
FileDescriptor &operator=(FileDescriptor &&other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
reset(std::exchange(other.m_descriptor, -1));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
FileDescriptor(const FileDescriptor &) = delete;
|
||||
FileDescriptor &operator=(const FileDescriptor &) = delete;
|
||||
|
||||
[[nodiscard]] int get() const noexcept { return m_descriptor; }
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_descriptor >= 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] int release() noexcept
|
||||
{
|
||||
return std::exchange(m_descriptor, -1);
|
||||
}
|
||||
|
||||
void reset(int descriptor = -1) noexcept
|
||||
{
|
||||
if (m_descriptor >= 0) {
|
||||
(void)::close(m_descriptor);
|
||||
}
|
||||
m_descriptor = descriptor;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
int m_descriptor{-1};
|
||||
};
|
||||
|
||||
constexpr int directoryOpenFlags =
|
||||
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW;
|
||||
constexpr std::size_t maximumTemporaryAttempts = 128;
|
||||
std::atomic<std::uint64_t> temporaryCounter{0};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FileDescriptor>
|
||||
open_destination(const std::filesystem::path &destination)
|
||||
{
|
||||
FileDescriptor descriptor{
|
||||
::open(destination.c_str(), directoryOpenFlags)};
|
||||
if (!descriptor) {
|
||||
return Void::Result::fail(
|
||||
std::format("Archive::extract: open destination '{}': {}",
|
||||
destination.string(), std::strerror(errno)));
|
||||
}
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FileDescriptor>
|
||||
open_parent_directory(int rootDescriptor,
|
||||
const std::filesystem::path &relativeParent,
|
||||
const std::filesystem::path &displayRoot)
|
||||
{
|
||||
FileDescriptor current{
|
||||
::openat(rootDescriptor, ".", directoryOpenFlags)};
|
||||
if (!current) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: duplicate destination '{}': {}",
|
||||
displayRoot.string(), std::strerror(errno)));
|
||||
}
|
||||
|
||||
std::filesystem::path displayPath = displayRoot;
|
||||
for (const auto &component : relativeParent) {
|
||||
const std::string name{component.native()};
|
||||
displayPath /= component;
|
||||
int descriptor =
|
||||
::openat(current.get(), name.c_str(), directoryOpenFlags);
|
||||
if (descriptor < 0 && errno == ENOENT) {
|
||||
if (::mkdirat(current.get(), name.c_str(), 0755) != 0 &&
|
||||
errno != EEXIST) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: cannot create directory '{}': "
|
||||
"{}",
|
||||
displayPath.string(), std::strerror(errno)));
|
||||
}
|
||||
descriptor = ::openat(current.get(), name.c_str(),
|
||||
directoryOpenFlags);
|
||||
}
|
||||
if (descriptor < 0) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: unsafe parent '{}': {}",
|
||||
displayPath.string(), std::strerror(errno)));
|
||||
}
|
||||
current = FileDescriptor{descriptor};
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> create_directory_entry(
|
||||
int rootDescriptor, const std::filesystem::path &relative,
|
||||
const std::filesystem::path &displayRoot, bool overwrite)
|
||||
{
|
||||
auto openedParent = open_parent_directory(
|
||||
rootDescriptor, relative.parent_path(), displayRoot);
|
||||
if (!openedParent) {
|
||||
return std::unexpected{openedParent.error()};
|
||||
}
|
||||
auto parent = std::move(*openedParent);
|
||||
const std::string name{relative.filename().native()};
|
||||
const auto displayPath = displayRoot / relative;
|
||||
|
||||
if (::mkdirat(parent.get(), name.c_str(), 0755) == 0) {
|
||||
return {};
|
||||
}
|
||||
if (errno != EEXIST) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: cannot create directory '{}': {}",
|
||||
displayPath.string(), std::strerror(errno)));
|
||||
}
|
||||
if (!overwrite) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: destination '{}' already exists",
|
||||
displayPath.string()));
|
||||
}
|
||||
|
||||
FileDescriptor existing{
|
||||
::openat(parent.get(), name.c_str(), directoryOpenFlags)};
|
||||
if (!existing) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: destination '{}' is not a real "
|
||||
"directory",
|
||||
displayPath.string()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
extract_regular(archive *reader, int rootDescriptor,
|
||||
const std::filesystem::path &relative,
|
||||
const std::filesystem::path &displayRoot,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted, bool executable)
|
||||
{
|
||||
auto openedParent = open_parent_directory(
|
||||
rootDescriptor, relative.parent_path(), displayRoot);
|
||||
if (!openedParent) {
|
||||
return std::unexpected{openedParent.error()};
|
||||
}
|
||||
auto parent = std::move(*openedParent);
|
||||
const std::string outputName{relative.filename().native()};
|
||||
const auto displayPath = displayRoot / relative;
|
||||
|
||||
FileDescriptor descriptor;
|
||||
std::string temporaryName;
|
||||
for (std::size_t attempt = 0; attempt < maximumTemporaryAttempts;
|
||||
++attempt) {
|
||||
const auto sequence =
|
||||
temporaryCounter.fetch_add(1, std::memory_order_relaxed);
|
||||
temporaryName =
|
||||
std::format(".void-archive-{}-{}",
|
||||
static_cast<long long>(::getpid()), sequence);
|
||||
const int opened = ::openat(parent.get(), temporaryName.c_str(),
|
||||
O_WRONLY | O_CREAT | O_EXCL |
|
||||
O_CLOEXEC | O_NOFOLLOW,
|
||||
executable ? 0755 : 0644);
|
||||
if (opened >= 0) {
|
||||
descriptor = FileDescriptor{opened};
|
||||
break;
|
||||
}
|
||||
if (errno != EEXIST) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: create temporary file for '{}': {}",
|
||||
displayPath.string(), std::strerror(errno)));
|
||||
}
|
||||
}
|
||||
if (!descriptor) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: cannot allocate temporary file for '{}'",
|
||||
displayPath.string()));
|
||||
}
|
||||
|
||||
auto removeTemporary = [&]() noexcept {
|
||||
descriptor.reset();
|
||||
if (!temporaryName.empty()) {
|
||||
(void)::unlinkat(parent.get(), temporaryName.c_str(), 0);
|
||||
temporaryName.clear();
|
||||
}
|
||||
};
|
||||
auto fail = [&](std::string message)
|
||||
-> Void::Result::Result<std::uint64_t> {
|
||||
removeTemporary();
|
||||
return Void::Result::fail(std::move(message));
|
||||
};
|
||||
|
||||
std::array<std::byte, 64 * 1024> buffer{};
|
||||
std::uint64_t fileBytes = 0;
|
||||
for (;;) {
|
||||
const auto count =
|
||||
archive_read_data(reader, buffer.data(), buffer.size());
|
||||
if (count == 0) {
|
||||
break;
|
||||
}
|
||||
if (count < 0) {
|
||||
return fail(archive_error(reader, "read entry").message());
|
||||
}
|
||||
const auto amount = static_cast<std::uint64_t>(count);
|
||||
if (amount > options.maxFileBytes - fileBytes ||
|
||||
amount >
|
||||
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||
return fail(
|
||||
"Archive::extract: extracted size exceeds policy");
|
||||
}
|
||||
|
||||
std::size_t written = 0;
|
||||
while (written < static_cast<std::size_t>(count)) {
|
||||
const auto result = ::write(
|
||||
descriptor.get(),
|
||||
reinterpret_cast<const char *>(buffer.data()) + written,
|
||||
static_cast<std::size_t>(count) - written);
|
||||
if (result < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (result <= 0) {
|
||||
const int error = errno;
|
||||
return fail(std::format(
|
||||
"Archive::extract: write '{}': {}",
|
||||
displayPath.string(), std::strerror(error)));
|
||||
}
|
||||
written += static_cast<std::size_t>(result);
|
||||
}
|
||||
fileBytes += amount;
|
||||
}
|
||||
|
||||
if (::fsync(descriptor.get()) != 0) {
|
||||
const int error = errno;
|
||||
return fail(std::format("Archive::extract: fsync '{}': {}",
|
||||
displayPath.string(),
|
||||
std::strerror(error)));
|
||||
}
|
||||
const int rawDescriptor = descriptor.release();
|
||||
if (::close(rawDescriptor) != 0) {
|
||||
const int error = errno;
|
||||
return fail(std::format("Archive::extract: close '{}': {}",
|
||||
displayPath.string(),
|
||||
std::strerror(error)));
|
||||
}
|
||||
|
||||
if (options.overwriteExisting) {
|
||||
struct stat status{};
|
||||
if (::fstatat(parent.get(), outputName.c_str(), &status,
|
||||
AT_SYMLINK_NOFOLLOW) == 0) {
|
||||
if (!S_ISREG(status.st_mode)) {
|
||||
return fail(std::format(
|
||||
"Archive::extract: destination '{}' is not a "
|
||||
"regular file",
|
||||
displayPath.string()));
|
||||
}
|
||||
} else if (errno != ENOENT) {
|
||||
const int error = errno;
|
||||
return fail(std::format(
|
||||
"Archive::extract: inspect destination '{}': {}",
|
||||
displayPath.string(), std::strerror(error)));
|
||||
}
|
||||
|
||||
if (::renameat(parent.get(), temporaryName.c_str(),
|
||||
parent.get(), outputName.c_str()) != 0) {
|
||||
const int error = errno;
|
||||
return fail(std::format(
|
||||
"Archive::extract: publish '{}': {}",
|
||||
displayPath.string(), std::strerror(error)));
|
||||
}
|
||||
temporaryName.clear();
|
||||
} else {
|
||||
if (::linkat(parent.get(), temporaryName.c_str(), parent.get(),
|
||||
outputName.c_str(), 0) != 0) {
|
||||
const int error = errno;
|
||||
return fail(std::format(
|
||||
"Archive::extract: publish '{}': {}",
|
||||
displayPath.string(), std::strerror(error)));
|
||||
}
|
||||
|
||||
int unlinkResult = 0;
|
||||
do {
|
||||
unlinkResult =
|
||||
::unlinkat(parent.get(), temporaryName.c_str(), 0);
|
||||
} while (unlinkResult != 0 && errno == EINTR);
|
||||
if (unlinkResult != 0 && errno != ENOENT) {
|
||||
const int error = errno;
|
||||
return fail(std::format(
|
||||
"Archive::extract: remove temporary file for '{}': {}",
|
||||
displayPath.string(), std::strerror(error)));
|
||||
}
|
||||
temporaryName.clear();
|
||||
}
|
||||
return fileBytes;
|
||||
}
|
||||
#else
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
safe_parents(const std::filesystem::path &root,
|
||||
const std::filesystem::path &relativeParent)
|
||||
{
|
||||
std::filesystem::path current = root;
|
||||
for (const auto &component : relativeParent) {
|
||||
current /= component;
|
||||
std::error_code error;
|
||||
const auto status =
|
||||
std::filesystem::symlink_status(current, error);
|
||||
if (!error &&
|
||||
status.type() != std::filesystem::file_type::not_found) {
|
||||
if (std::filesystem::is_symlink(status) ||
|
||||
!std::filesystem::is_directory(status)) {
|
||||
return Void::Result::fail(
|
||||
std::format("Archive::extract: unsafe parent '{}'",
|
||||
current.string()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (error && error != std::errc::no_such_file_or_directory) {
|
||||
return Void::Result::fail(
|
||||
std::format("Archive::extract: cannot inspect '{}': {}",
|
||||
current.string(), error.message()));
|
||||
}
|
||||
error.clear();
|
||||
std::filesystem::create_directory(current, error);
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
std::format("Archive::extract: cannot create '{}': {}",
|
||||
current.string(), error.message()));
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create_directory_entry(const std::filesystem::path &path,
|
||||
bool overwrite)
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(path, error);
|
||||
if (!error &&
|
||||
status.type() != std::filesystem::file_type::not_found) {
|
||||
if (std::filesystem::is_symlink(status) ||
|
||||
!std::filesystem::is_directory(status) || !overwrite) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: destination '{}' already exists",
|
||||
path.string()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
error.clear();
|
||||
std::filesystem::create_directory(path, error);
|
||||
if (error) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: cannot create directory '{}': {}",
|
||||
path.string(), error.message()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
extract_regular(archive *reader, const std::filesystem::path &path,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted)
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(path, error);
|
||||
if (!error &&
|
||||
status.type() != std::filesystem::file_type::not_found &&
|
||||
(std::filesystem::is_symlink(status) ||
|
||||
!std::filesystem::is_regular_file(status))) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: destination '{}' is not a regular file",
|
||||
path.string()));
|
||||
}
|
||||
if (!options.overwriteExisting && !error &&
|
||||
status.type() != std::filesystem::file_type::not_found) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: destination '{}' already exists",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
std::ofstream output{path, std::ios::binary | std::ios::trunc};
|
||||
if (!output) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: create '{}' failed", path.string()));
|
||||
}
|
||||
auto fail = [&](std::string message)
|
||||
-> Void::Result::Result<std::uint64_t> {
|
||||
output.close();
|
||||
std::error_code removeError;
|
||||
std::filesystem::remove(path, removeError);
|
||||
return Void::Result::fail(std::move(message));
|
||||
};
|
||||
|
||||
std::array<std::byte, 64 * 1024> buffer{};
|
||||
std::uint64_t fileBytes = 0;
|
||||
for (;;) {
|
||||
const auto count =
|
||||
archive_read_data(reader, buffer.data(), buffer.size());
|
||||
if (count == 0) {
|
||||
break;
|
||||
}
|
||||
if (count < 0) {
|
||||
return fail(archive_error(reader, "read entry").message());
|
||||
}
|
||||
const auto amount = static_cast<std::uint64_t>(count);
|
||||
if (amount > options.maxFileBytes - fileBytes ||
|
||||
amount >
|
||||
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||
return fail(
|
||||
"Archive::extract: extracted size exceeds policy");
|
||||
}
|
||||
output.write(reinterpret_cast<const char *>(buffer.data()),
|
||||
count);
|
||||
if (!output) {
|
||||
return fail("Archive::extract: write failed");
|
||||
}
|
||||
fileBytes += amount;
|
||||
}
|
||||
return fileBytes;
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<ExtractionResult>
|
||||
extract(const std::filesystem::path &archivePath,
|
||||
const std::filesystem::path &destination,
|
||||
const ExtractionOptions &options)
|
||||
{
|
||||
if (options.maxEntries == 0 || options.maxFileBytes == 0 ||
|
||||
options.maxTotalBytes == 0) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: extraction limits must be positive");
|
||||
}
|
||||
std::error_code error;
|
||||
std::filesystem::create_directories(destination, error);
|
||||
if (error) {
|
||||
return Void::Result::fail(
|
||||
std::format("Archive::extract: cannot create destination: {}",
|
||||
error.message()));
|
||||
}
|
||||
#ifndef _WIN32
|
||||
auto root = open_destination(destination);
|
||||
if (!root) {
|
||||
return std::unexpected{root.error()};
|
||||
}
|
||||
#else
|
||||
const auto root = std::filesystem::canonical(destination, error);
|
||||
if (error || std::filesystem::is_symlink(
|
||||
std::filesystem::symlink_status(destination, error))) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: destination must be a real directory");
|
||||
}
|
||||
#endif
|
||||
|
||||
ArchiveHandle reader{archive_read_new(), &archive_read_free};
|
||||
if (!reader) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: cannot allocate archive reader");
|
||||
}
|
||||
archive_read_support_filter_zstd(reader.get());
|
||||
archive_read_support_filter_none(reader.get());
|
||||
archive_read_support_format_tar(reader.get());
|
||||
#ifdef _WIN32
|
||||
const int opened = archive_read_open_filename_w(
|
||||
reader.get(), archivePath.c_str(), 64 * 1024);
|
||||
#else
|
||||
const int opened = archive_read_open_filename(
|
||||
reader.get(), archivePath.c_str(), 64 * 1024);
|
||||
#endif
|
||||
if (opened != ARCHIVE_OK) {
|
||||
return std::unexpected{archive_error(reader.get(), "open archive")};
|
||||
}
|
||||
|
||||
ExtractionResult result;
|
||||
std::set<std::filesystem::path> seen;
|
||||
archive_entry *entry = nullptr;
|
||||
for (;;) {
|
||||
const int status = archive_read_next_header(reader.get(), &entry);
|
||||
if (status == ARCHIVE_EOF) {
|
||||
break;
|
||||
}
|
||||
if (status != ARCHIVE_OK) {
|
||||
return std::unexpected{
|
||||
archive_error(reader.get(), "read header")};
|
||||
}
|
||||
if (++result.entries > options.maxEntries) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: entry count exceeds policy");
|
||||
}
|
||||
|
||||
const char *rawPath = archive_entry_pathname(entry);
|
||||
if (rawPath == nullptr) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: entry has no path");
|
||||
}
|
||||
if (archive_entry_hardlink(entry) != nullptr ||
|
||||
archive_entry_symlink(entry) != nullptr) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: links are not allowed");
|
||||
}
|
||||
|
||||
const auto type = archive_entry_filetype(entry);
|
||||
if (type != AE_IFDIR && type != AE_IFREG) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: special files are not allowed");
|
||||
}
|
||||
auto relative = safe_relative_path(rawPath, type == AE_IFDIR);
|
||||
if (!relative || !seen.insert(*relative).second) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: unsafe or duplicate path '{}'",
|
||||
rawPath));
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
if (auto parents = safe_parents(root, relative->parent_path());
|
||||
!parents) {
|
||||
return std::unexpected{parents.error()};
|
||||
}
|
||||
const auto output = root / *relative;
|
||||
#endif
|
||||
if (type == AE_IFDIR) {
|
||||
#ifndef _WIN32
|
||||
auto created =
|
||||
create_directory_entry(root->get(), *relative, destination,
|
||||
options.overwriteExisting);
|
||||
#else
|
||||
auto created =
|
||||
create_directory_entry(output, options.overwriteExisting);
|
||||
#endif
|
||||
if (!created) {
|
||||
return std::unexpected{created.error()};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto declared = archive_entry_size(entry);
|
||||
if (declared < 0 ||
|
||||
static_cast<std::uint64_t>(declared) > options.maxFileBytes ||
|
||||
static_cast<std::uint64_t>(declared) >
|
||||
options.maxTotalBytes - result.bytes) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: declared entry size exceeds policy");
|
||||
}
|
||||
#ifndef _WIN32
|
||||
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
|
||||
auto extracted =
|
||||
extract_regular(reader.get(), root->get(), *relative,
|
||||
destination, options, result.bytes, executable);
|
||||
#else
|
||||
auto extracted =
|
||||
extract_regular(reader.get(), output, options, result.bytes);
|
||||
#endif
|
||||
if (!extracted) {
|
||||
return std::unexpected{extracted.error()};
|
||||
}
|
||||
result.bytes += *extracted;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
} // namespace Void::Archive
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Archive
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS LibArchive::LibArchive
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Binary
|
||||
INTERNAL_DEPS Functional
|
||||
)
|
||||
@@ -0,0 +1,257 @@
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <utility>
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
|
||||
namespace Void::Crypto
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] const EVP_MD*
|
||||
algorithm_impl(HashAlgorithm algorithm) noexcept
|
||||
{
|
||||
switch (algorithm) {
|
||||
case HashAlgorithm::Sha1:
|
||||
return EVP_sha1();
|
||||
case HashAlgorithm::Sha256:
|
||||
return EVP_sha256();
|
||||
case HashAlgorithm::Sha512:
|
||||
return EVP_sha512();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string openssl_error(std::string_view operation)
|
||||
{
|
||||
const unsigned long code = ERR_get_error();
|
||||
if (code == 0) {
|
||||
return std::string{operation};
|
||||
}
|
||||
std::array<char, 256> buffer{};
|
||||
ERR_error_string_n(code, buffer.data(), buffer.size());
|
||||
return std::format("{}: {}", operation, buffer.data());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
struct Hasher::Impl {
|
||||
EVP_MD_CTX* context{nullptr};
|
||||
const EVP_MD* algorithm{nullptr};
|
||||
bool finalized{false};
|
||||
~Impl() { EVP_MD_CTX_free(context); }
|
||||
};
|
||||
|
||||
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
|
||||
: m_impl(std::move(impl))
|
||||
{
|
||||
}
|
||||
Hasher::~Hasher() = default;
|
||||
Hasher::Hasher(Hasher&&) noexcept = default;
|
||||
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
|
||||
|
||||
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
|
||||
{
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->algorithm = algorithm_impl(algorithm);
|
||||
if (impl->algorithm == nullptr) {
|
||||
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
|
||||
}
|
||||
impl->context = EVP_MD_CTX_new();
|
||||
if (impl->context == nullptr) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed"));
|
||||
}
|
||||
if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::Hasher: digest initialization failed"));
|
||||
}
|
||||
return Hasher{std::move(impl)};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
|
||||
{
|
||||
if (!m_impl || m_impl->finalized) {
|
||||
return Void::Result::fail(
|
||||
"Crypto::Hasher::update: hasher is finalized or moved-from");
|
||||
}
|
||||
if (!data.empty() &&
|
||||
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::Hasher::update failed"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> Hasher::update(std::string_view data)
|
||||
{
|
||||
return update(std::as_bytes(std::span{data.data(), data.size()}));
|
||||
}
|
||||
|
||||
Void::Result::Result<Digest> Hasher::finalize()
|
||||
{
|
||||
if (!m_impl || m_impl->finalized) {
|
||||
return Void::Result::fail(
|
||||
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
|
||||
}
|
||||
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
|
||||
if (digest_size <= 0) {
|
||||
return Void::Result::fail(
|
||||
"Crypto::Hasher::finalize: invalid digest size");
|
||||
}
|
||||
Digest digest(static_cast<std::size_t>(digest_size));
|
||||
unsigned int written = 0;
|
||||
if (EVP_DigestFinal_ex(m_impl->context,
|
||||
reinterpret_cast<unsigned char*>(digest.data()),
|
||||
&written) != 1) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::Hasher::finalize failed"));
|
||||
}
|
||||
m_impl->finalized = true;
|
||||
digest.resize(written);
|
||||
return digest;
|
||||
}
|
||||
|
||||
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
auto hasher = Hasher::create(algorithm);
|
||||
if (!hasher) {
|
||||
return std::unexpected{hasher.error()};
|
||||
}
|
||||
if (auto updated = hasher->update(data); !updated) {
|
||||
return std::unexpected{updated.error()};
|
||||
}
|
||||
return hasher->finalize();
|
||||
}
|
||||
|
||||
auto hash(HashAlgorithm algorithm, std::string_view data)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
return hash(algorithm,
|
||||
std::as_bytes(std::span{data.data(), data.size()}));
|
||||
}
|
||||
|
||||
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
std::ifstream input{path, std::ios::binary};
|
||||
if (!input.is_open()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Crypto::hashFile: cannot open '{}'", path.string()));
|
||||
}
|
||||
auto hasher = Hasher::create(algorithm);
|
||||
if (!hasher) {
|
||||
return std::unexpected{hasher.error()};
|
||||
}
|
||||
std::array<char, 64 * 1024> buffer{};
|
||||
while (input) {
|
||||
input.read(buffer.data(),
|
||||
static_cast<std::streamsize>(buffer.size()));
|
||||
const auto count = input.gcount();
|
||||
if (count > 0) {
|
||||
const auto bytes = std::as_bytes(
|
||||
std::span{buffer.data(), static_cast<std::size_t>(count)});
|
||||
if (auto updated = hasher->update(bytes); !updated) {
|
||||
return std::unexpected{updated.error()};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (input.bad()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Crypto::hashFile: I/O error reading '{}'", path.string()));
|
||||
}
|
||||
return hasher->finalize();
|
||||
}
|
||||
|
||||
Void::Result::Result<Digest> sha1(std::span<const std::byte> data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha1, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha1(std::string_view data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha1, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha256(std::span<const std::byte> data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha256, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha256(std::string_view data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha256, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha512(std::span<const std::byte> data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha512, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha512(std::string_view data)
|
||||
{
|
||||
return hash(HashAlgorithm::Sha512, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha1, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha256, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha512, path);
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
|
||||
std::span<const std::byte>
|
||||
signature,
|
||||
std::span<const std::byte>
|
||||
publicKey)
|
||||
{
|
||||
if (signature.size() != Ed25519SignatureSize) {
|
||||
return Void::Result::fail(
|
||||
std::format("Crypto::verifyEd25519: signature must be {} bytes",
|
||||
Ed25519SignatureSize));
|
||||
}
|
||||
if (publicKey.size() != Ed25519PublicKeySize) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Crypto::verifyEd25519: public key must be {} bytes",
|
||||
Ed25519PublicKeySize));
|
||||
}
|
||||
|
||||
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
|
||||
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||
Key key{EVP_PKEY_new_raw_public_key(
|
||||
EVP_PKEY_ED25519, nullptr,
|
||||
reinterpret_cast<const unsigned char*>(publicKey.data()),
|
||||
publicKey.size()),
|
||||
&EVP_PKEY_free};
|
||||
if (!key) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::verifyEd25519: invalid public key"));
|
||||
}
|
||||
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
|
||||
if (!context) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
|
||||
}
|
||||
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
|
||||
key.get()) != 1) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::verifyEd25519: initialization failed"));
|
||||
}
|
||||
const int result = EVP_DigestVerify(
|
||||
context.get(),
|
||||
reinterpret_cast<const unsigned char*>(signature.data()),
|
||||
signature.size(),
|
||||
reinterpret_cast<const unsigned char*>(message.data()),
|
||||
message.size());
|
||||
if (result < 0) {
|
||||
return Void::Result::fail(
|
||||
openssl_error("Crypto::verifyEd25519 failed"));
|
||||
}
|
||||
return result == 1;
|
||||
}
|
||||
} // namespace Void::Crypto
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Crypto
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS OpenSSL::Crypto
|
||||
)
|
||||
+247
-224
@@ -1,9 +1,9 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
# include <dlfcn.h>
|
||||
# define VOID_HAS_DLOPEN 1
|
||||
#include <dlfcn.h>
|
||||
#define VOID_HAS_DLOPEN 1
|
||||
#endif
|
||||
|
||||
#include <filesystem>
|
||||
@@ -13,258 +13,281 @@
|
||||
namespace Void::Plugin
|
||||
{
|
||||
|
||||
std::string_view to_string(LoadError e) noexcept
|
||||
{
|
||||
switch (e) {
|
||||
case LoadError::FileNotFound: return "file not found";
|
||||
case LoadError::DlopenFailed: return "dlopen failed";
|
||||
case LoadError::SymbolMissing: return "required symbol missing";
|
||||
case LoadError::AbiMismatch: return "ABI version mismatch";
|
||||
case LoadError::CreateFailed: return "plugin create() returned null";
|
||||
case LoadError::NotSupported: return "platform does not support dlopen";
|
||||
case LoadError::StateRejected: return "new instance rejected state";
|
||||
case LoadError::ActivationFailed: return "plugin activation failed";
|
||||
case LoadError::UnknownPlugin: return "no plugin registered under name";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
std::string_view to_string(LoadError e) noexcept
|
||||
{
|
||||
switch (e) {
|
||||
case LoadError::FileNotFound:
|
||||
return "file not found";
|
||||
case LoadError::DlopenFailed:
|
||||
return "dlopen failed";
|
||||
case LoadError::SymbolMissing:
|
||||
return "required symbol missing";
|
||||
case LoadError::AbiMismatch:
|
||||
return "ABI version mismatch";
|
||||
case LoadError::CreateFailed:
|
||||
return "plugin create() returned null";
|
||||
case LoadError::NotSupported:
|
||||
return "platform does not support dlopen";
|
||||
case LoadError::StateRejected:
|
||||
return "new instance rejected state";
|
||||
case LoadError::ActivationFailed:
|
||||
return "plugin activation failed";
|
||||
case LoadError::UnknownPlugin:
|
||||
return "no plugin registered under name";
|
||||
case LoadError::NameMismatch:
|
||||
return "replacement plugin name mismatch";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
// ── internal helpers ──────────────────────────────────────────────────────────
|
||||
// ── internal helpers
|
||||
// ──────────────────────────────────────────────────────────
|
||||
|
||||
void PluginLoader::destroy_current() noexcept
|
||||
{
|
||||
void PluginLoader::destroy_current() noexcept
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
if (plugin_) {
|
||||
plugin_->on_unload();
|
||||
if (destroy_) destroy_(plugin_);
|
||||
plugin_ = nullptr;
|
||||
}
|
||||
if (handle_) {
|
||||
dlclose(handle_);
|
||||
handle_ = nullptr;
|
||||
}
|
||||
destroy_ = nullptr;
|
||||
transfer_ = nullptr;
|
||||
ready_ = nullptr;
|
||||
state_version_ = nullptr;
|
||||
serialize_ = nullptr;
|
||||
free_string_ = nullptr;
|
||||
deserialize_ = nullptr;
|
||||
if (plugin_) {
|
||||
plugin_->on_unload();
|
||||
if (destroy_) {
|
||||
destroy_(plugin_);
|
||||
}
|
||||
plugin_ = nullptr;
|
||||
}
|
||||
if (handle_) {
|
||||
dlclose(handle_);
|
||||
handle_ = nullptr;
|
||||
}
|
||||
destroy_ = nullptr;
|
||||
transfer_ = nullptr;
|
||||
ready_ = nullptr;
|
||||
state_version_ = nullptr;
|
||||
serialize_ = nullptr;
|
||||
free_string_ = nullptr;
|
||||
deserialize_ = nullptr;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// Move plugin state old -> new across a reload. Prefers the v2
|
||||
// serialize/deserialize protocol (survives layout changes between
|
||||
// versions); falls back to the raw transfer_state hook; else no-op.
|
||||
// Returns false only when the new instance actively rejects the state.
|
||||
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
|
||||
{
|
||||
if (!from.plugin_ || !to.plugin_) {
|
||||
return true;
|
||||
}
|
||||
if (from.serialize_ && to.deserialize_) {
|
||||
const std::uint32_t from_version =
|
||||
from.state_version_ ? from.state_version_() : 0;
|
||||
const char* json = from.serialize_(from.plugin_);
|
||||
if (json != nullptr) {
|
||||
const int rc = to.deserialize_(to.plugin_, json, from_version);
|
||||
if (from.free_string_) {
|
||||
from.free_string_(json);
|
||||
}
|
||||
if (rc != 0) {
|
||||
Void::Log::warn("Plugin",
|
||||
"deserialize_state rejected state "
|
||||
"(from v{}, rc={})",
|
||||
from_version, rc);
|
||||
return false;
|
||||
}
|
||||
Void::Log::debug("Plugin",
|
||||
"state transferred via v2 protocol (v{})",
|
||||
from_version);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (to.transfer_) {
|
||||
to.transfer_(from.plugin_, to.plugin_);
|
||||
Void::Log::debug("Plugin", "state transferred via transfer_state");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Move plugin state old -> new across a reload. Prefers the v2
|
||||
// serialize/deserialize protocol (survives layout changes between
|
||||
// versions); falls back to the raw transfer_state hook; else no-op.
|
||||
// Returns false only when the new instance actively rejects the state.
|
||||
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
|
||||
{
|
||||
if (!from.plugin_ || !to.plugin_) {
|
||||
return true;
|
||||
}
|
||||
if (from.serialize_ && to.deserialize_) {
|
||||
const std::uint32_t from_version =
|
||||
from.state_version_ ? from.state_version_() : 0;
|
||||
const char* json = from.serialize_(from.plugin_);
|
||||
if (json != nullptr) {
|
||||
const int rc = to.deserialize_(to.plugin_, json, from_version);
|
||||
if (from.free_string_) {
|
||||
from.free_string_(json);
|
||||
}
|
||||
if (rc != 0) {
|
||||
Void::Log::warn("Plugin",
|
||||
"deserialize_state rejected state "
|
||||
"(from v{}, rc={})",
|
||||
from_version, rc);
|
||||
return false;
|
||||
}
|
||||
Void::Log::debug("Plugin",
|
||||
"state transferred via v2 protocol (v{})",
|
||||
from_version);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (to.transfer_) {
|
||||
to.transfer_(from.plugin_, to.plugin_);
|
||||
Void::Log::debug("Plugin", "state transferred via transfer_state");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::expected<void, LoadError>
|
||||
PluginLoader::load_from(const std::filesystem::path& path)
|
||||
{
|
||||
std::expected<void, LoadError>
|
||||
PluginLoader::load_from(const std::filesystem::path& path)
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) return std::unexpected{LoadError::DlopenFailed};
|
||||
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) {
|
||||
return std::unexpected{LoadError::DlopenFailed};
|
||||
}
|
||||
|
||||
const auto sym_info = reinterpret_cast<info_fn> (dlsym(h, kInfoSymbol));
|
||||
const auto sym_create = reinterpret_cast<create_fn> (dlsym(h, kCreateSymbol));
|
||||
const auto sym_destroy = reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
|
||||
const auto sym_info = reinterpret_cast<info_fn>(dlsym(h, kInfoSymbol));
|
||||
const auto sym_create =
|
||||
reinterpret_cast<create_fn>(dlsym(h, kCreateSymbol));
|
||||
const auto sym_destroy =
|
||||
reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
|
||||
|
||||
if (!sym_info || !sym_create || !sym_destroy) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::SymbolMissing};
|
||||
}
|
||||
if (!sym_info || !sym_create || !sym_destroy) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::SymbolMissing};
|
||||
}
|
||||
|
||||
const PluginInfo info = sym_info();
|
||||
if (info.abi_version != ABI_VERSION) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::AbiMismatch};
|
||||
}
|
||||
const PluginInfo info = sym_info();
|
||||
if (info.abi_version != ABI_VERSION) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::AbiMismatch};
|
||||
}
|
||||
|
||||
void* raw = sym_create();
|
||||
if (!raw) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::CreateFailed};
|
||||
}
|
||||
void* raw = sym_create();
|
||||
if (!raw) {
|
||||
dlclose(h);
|
||||
return std::unexpected{LoadError::CreateFailed};
|
||||
}
|
||||
|
||||
handle_ = h;
|
||||
plugin_ = static_cast<IPlugin*>(raw);
|
||||
destroy_ = sym_destroy;
|
||||
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||
state_version_ = reinterpret_cast<state_version_fn>(
|
||||
dlsym(h, kStateVersionSymbol));
|
||||
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
||||
free_string_ = reinterpret_cast<free_string_fn>(
|
||||
dlsym(h, kFreeStringSymbol));
|
||||
deserialize_ = reinterpret_cast<deserialize_fn>(
|
||||
dlsym(h, kDeserializeSymbol));
|
||||
info_ = info;
|
||||
return {};
|
||||
handle_ = h;
|
||||
plugin_ = static_cast<IPlugin*>(raw);
|
||||
destroy_ = sym_destroy;
|
||||
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||
state_version_ =
|
||||
reinterpret_cast<state_version_fn>(dlsym(h, kStateVersionSymbol));
|
||||
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
|
||||
free_string_ =
|
||||
reinterpret_cast<free_string_fn>(dlsym(h, kFreeStringSymbol));
|
||||
deserialize_ =
|
||||
reinterpret_cast<deserialize_fn>(dlsym(h, kDeserializeSymbol));
|
||||
info_ = info;
|
||||
return {};
|
||||
#else
|
||||
(void)path;
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
(void)path;
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// ── public API ────────────────────────────────────────────────────────────────
|
||||
// ── public API
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
|
||||
std::expected<PluginLoader, LoadError>
|
||||
PluginLoader::load(std::filesystem::path path)
|
||||
{
|
||||
if (!std::filesystem::exists(path))
|
||||
return std::unexpected{LoadError::FileNotFound};
|
||||
std::expected<PluginLoader, LoadError>
|
||||
PluginLoader::load(std::filesystem::path path)
|
||||
{
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return std::unexpected{LoadError::FileNotFound};
|
||||
}
|
||||
|
||||
PluginLoader ldr;
|
||||
ldr.path_ = path;
|
||||
PluginLoader ldr;
|
||||
ldr.path_ = path;
|
||||
|
||||
if (auto r = ldr.load_from(path); !r) {
|
||||
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
|
||||
to_string(r.error()));
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
if (auto r = ldr.load_from(path); !r) {
|
||||
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
|
||||
to_string(r.error()));
|
||||
return std::unexpected{r.error()};
|
||||
}
|
||||
|
||||
try {
|
||||
ldr.plugin_->on_load();
|
||||
} catch (...) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
||||
ldr.info_.name, ldr.info_.plugin_version);
|
||||
return ldr;
|
||||
}
|
||||
try {
|
||||
ldr.plugin_->on_load();
|
||||
} catch (...) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
|
||||
ldr.info_.name, ldr.info_.plugin_version);
|
||||
return ldr;
|
||||
}
|
||||
|
||||
PluginLoader::~PluginLoader() { destroy_current(); }
|
||||
PluginLoader::~PluginLoader() { destroy_current(); }
|
||||
|
||||
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
||||
: handle_ {std::exchange(o.handle_, nullptr)}
|
||||
, plugin_ {std::exchange(o.plugin_, nullptr)}
|
||||
, destroy_ {std::exchange(o.destroy_, nullptr)}
|
||||
, transfer_ {std::exchange(o.transfer_, nullptr)}
|
||||
, ready_ {std::exchange(o.ready_, nullptr)}
|
||||
, state_version_{std::exchange(o.state_version_, nullptr)}
|
||||
, serialize_ {std::exchange(o.serialize_, nullptr)}
|
||||
, free_string_ {std::exchange(o.free_string_, nullptr)}
|
||||
, deserialize_ {std::exchange(o.deserialize_, nullptr)}
|
||||
, info_ {o.info_}
|
||||
, path_ {std::move(o.path_)}
|
||||
{}
|
||||
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
|
||||
: handle_{std::exchange(o.handle_, nullptr)},
|
||||
plugin_{std::exchange(o.plugin_, nullptr)},
|
||||
destroy_{std::exchange(o.destroy_, nullptr)},
|
||||
transfer_{std::exchange(o.transfer_, nullptr)},
|
||||
ready_{std::exchange(o.ready_, nullptr)},
|
||||
state_version_{std::exchange(o.state_version_, nullptr)},
|
||||
serialize_{std::exchange(o.serialize_, nullptr)},
|
||||
free_string_{std::exchange(o.free_string_, nullptr)},
|
||||
deserialize_{std::exchange(o.deserialize_, nullptr)}, info_{o.info_},
|
||||
path_{std::move(o.path_)}
|
||||
{
|
||||
}
|
||||
|
||||
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
||||
{
|
||||
if (this != &o) {
|
||||
destroy_current();
|
||||
handle_ = std::exchange(o.handle_, nullptr);
|
||||
plugin_ = std::exchange(o.plugin_, nullptr);
|
||||
destroy_ = std::exchange(o.destroy_, nullptr);
|
||||
transfer_ = std::exchange(o.transfer_, nullptr);
|
||||
ready_ = std::exchange(o.ready_, nullptr);
|
||||
state_version_ = std::exchange(o.state_version_, nullptr);
|
||||
serialize_ = std::exchange(o.serialize_, nullptr);
|
||||
free_string_ = std::exchange(o.free_string_, nullptr);
|
||||
deserialize_ = std::exchange(o.deserialize_, nullptr);
|
||||
info_ = o.info_;
|
||||
path_ = std::move(o.path_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
|
||||
{
|
||||
if (this != &o) {
|
||||
destroy_current();
|
||||
handle_ = std::exchange(o.handle_, nullptr);
|
||||
plugin_ = std::exchange(o.plugin_, nullptr);
|
||||
destroy_ = std::exchange(o.destroy_, nullptr);
|
||||
transfer_ = std::exchange(o.transfer_, nullptr);
|
||||
ready_ = std::exchange(o.ready_, nullptr);
|
||||
state_version_ = std::exchange(o.state_version_, nullptr);
|
||||
serialize_ = std::exchange(o.serialize_, nullptr);
|
||||
free_string_ = std::exchange(o.free_string_, nullptr);
|
||||
deserialize_ = std::exchange(o.deserialize_, nullptr);
|
||||
info_ = o.info_;
|
||||
path_ = std::move(o.path_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::expected<void, LoadError> PluginLoader::reload()
|
||||
{
|
||||
std::expected<void, LoadError> PluginLoader::reload()
|
||||
{
|
||||
#ifdef VOID_HAS_DLOPEN
|
||||
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
|
||||
// path-based cache) even if the file was replaced in-place.
|
||||
const auto tmp = path_.parent_path()
|
||||
/ (path_.filename().string() + ".void_hotswap");
|
||||
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
|
||||
// path-based cache) even if the file was replaced in-place.
|
||||
const auto tmp =
|
||||
path_.parent_path() / (path_.filename().string() + ".void_hotswap");
|
||||
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::copy_file(path_, tmp,
|
||||
std::filesystem::copy_options::overwrite_existing, ec);
|
||||
if (ec) return std::unexpected{LoadError::FileNotFound};
|
||||
}
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::copy_file(
|
||||
path_, tmp, std::filesystem::copy_options::overwrite_existing,
|
||||
ec);
|
||||
if (ec) {
|
||||
return std::unexpected{LoadError::FileNotFound};
|
||||
}
|
||||
}
|
||||
|
||||
// Load new instance while old is still alive (for state transfer).
|
||||
PluginLoader next;
|
||||
next.path_ = path_;
|
||||
if (auto r = next.load_from(tmp); !r) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
|
||||
path_.string(), to_string(r.error()));
|
||||
return r;
|
||||
}
|
||||
// Load new instance while old is still alive (for state transfer).
|
||||
PluginLoader next;
|
||||
next.path_ = path_;
|
||||
if (auto r = next.load_from(tmp); !r) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
|
||||
path_.string(), to_string(r.error()));
|
||||
return r;
|
||||
}
|
||||
|
||||
// Transfer state with both instances alive. A rejection aborts the
|
||||
// reload and keeps the old instance.
|
||||
if (!transfer_plugin_state(*this, next)) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
|
||||
path_.string());
|
||||
return std::unexpected{LoadError::StateRejected};
|
||||
}
|
||||
// Transfer state with both instances alive. A rejection aborts the
|
||||
// reload and keeps the old instance.
|
||||
if (!transfer_plugin_state(*this, next)) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
|
||||
path_.string());
|
||||
return std::unexpected{LoadError::StateRejected};
|
||||
}
|
||||
|
||||
try {
|
||||
next.plugin_->on_load();
|
||||
} catch (...) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (next.ready_ && next.ready_(next.plugin_) != 0) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
try {
|
||||
next.plugin_->on_load();
|
||||
} catch (...) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (next.ready_ && next.ready_(next.plugin_) != 0) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
|
||||
// Activation succeeded; only now destroy old and install new.
|
||||
destroy_current();
|
||||
*this = std::move(next);
|
||||
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
||||
info_.name, info_.plugin_version);
|
||||
// Activation succeeded; only now destroy old and install new.
|
||||
destroy_current();
|
||||
*this = std::move(next);
|
||||
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
|
||||
info_.name, info_.plugin_version);
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return {};
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tmp, ec);
|
||||
return {};
|
||||
#else
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
return std::unexpected{LoadError::NotSupported};
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Plugin
|
||||
+76
-33
@@ -122,8 +122,7 @@ namespace Void::Plugin
|
||||
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
|
||||
inst->configure =
|
||||
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
|
||||
inst->ready =
|
||||
reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||
inst->ready = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
|
||||
inst->state_version = reinterpret_cast<state_version_fn>(
|
||||
dlsym(h, kStateVersionSymbol));
|
||||
inst->serialize =
|
||||
@@ -183,10 +182,10 @@ namespace Void::Plugin
|
||||
hotswap_copy(const std::filesystem::path& path)
|
||||
{
|
||||
static std::atomic<std::uint64_t> counter{0};
|
||||
const auto tmp =
|
||||
path.parent_path() /
|
||||
(path.filename().string() + ".void_hotswap." +
|
||||
std::to_string(counter.fetch_add(1, std::memory_order_relaxed)));
|
||||
const auto tmp = path.parent_path() /
|
||||
(path.filename().string() + ".void_hotswap." +
|
||||
std::to_string(counter.fetch_add(
|
||||
1, std::memory_order_relaxed)));
|
||||
std::error_code ec;
|
||||
std::filesystem::copy_file(
|
||||
path, tmp, std::filesystem::copy_options::overwrite_existing,
|
||||
@@ -251,8 +250,7 @@ namespace Void::Plugin
|
||||
} catch (...) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if ((*inst)->ready != nullptr &&
|
||||
(*inst)->ready((*inst)->plugin) != 0) {
|
||||
if ((*inst)->ready != nullptr && (*inst)->ready((*inst)->plugin) != 0) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (m_options.instance_validator &&
|
||||
@@ -338,7 +336,7 @@ namespace Void::Plugin
|
||||
if (entry == nullptr) {
|
||||
return std::unexpected{LoadError::UnknownPlugin};
|
||||
}
|
||||
auto result = reload_locked(*entry, name);
|
||||
auto result = reload_locked(*entry, name, entry->path);
|
||||
if (!result.has_value()) {
|
||||
return result;
|
||||
}
|
||||
@@ -351,14 +349,51 @@ namespace Void::Plugin
|
||||
}
|
||||
|
||||
std::expected<void, LoadError>
|
||||
PluginManager::reload_locked(Entry& entry, std::string_view name)
|
||||
PluginManager::replace(std::string_view name,
|
||||
const std::filesystem::path& newPath)
|
||||
{
|
||||
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||
bool restartWatcher = false;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
auto* entry = find(name);
|
||||
if (entry == nullptr) {
|
||||
return std::unexpected{LoadError::UnknownPlugin};
|
||||
}
|
||||
std::error_code error;
|
||||
if (!std::filesystem::is_regular_file(newPath, error)) {
|
||||
return std::unexpected{LoadError::FileNotFound};
|
||||
}
|
||||
auto result = reload_locked(*entry, name, newPath);
|
||||
if (!result) {
|
||||
return result;
|
||||
}
|
||||
restartWatcher = entry->watched;
|
||||
if (restartWatcher) {
|
||||
m_watcher.unwatch(entry->path);
|
||||
}
|
||||
entry->path = newPath;
|
||||
callbacks = reload_callbacks_locked();
|
||||
}
|
||||
if (restartWatcher) {
|
||||
watch(name);
|
||||
}
|
||||
for (const auto& callback : callbacks) {
|
||||
callback(name);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, LoadError>
|
||||
PluginManager::reload_locked(Entry& entry, std::string_view name,
|
||||
const std::filesystem::path& sourcePath)
|
||||
{
|
||||
// Copy to a fresh inode so dlopen loads the new bytes instead of
|
||||
// returning the still-open handle for this path. The caller must
|
||||
// have installed the new file via atomic rename (a fresh inode of
|
||||
// its own) — overwriting the mapped file in place corrupts the
|
||||
// running instance's mapping (SIGBUS).
|
||||
auto tmp = hotswap_copy(entry.path);
|
||||
auto tmp = hotswap_copy(sourcePath);
|
||||
if (!tmp.has_value()) {
|
||||
return std::unexpected{tmp.error()};
|
||||
}
|
||||
@@ -371,6 +406,12 @@ namespace Void::Plugin
|
||||
to_string(next.error()));
|
||||
return std::unexpected{next.error()};
|
||||
}
|
||||
if ((*next)->plugin->name() != name) {
|
||||
Void::Log::warn("Plugin.Manager",
|
||||
"replace '{}' rejected: candidate reports '{}'",
|
||||
name, (*next)->plugin->name());
|
||||
return std::unexpected{LoadError::NameMismatch};
|
||||
}
|
||||
|
||||
if (m_options.config_provider && (*next)->configure != nullptr) {
|
||||
const std::string config = m_options.config_provider(name);
|
||||
@@ -392,16 +433,16 @@ namespace Void::Plugin
|
||||
} catch (...) {
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if ((*next)->ready != nullptr &&
|
||||
(*next)->ready((*next)->plugin) != 0) {
|
||||
if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) {
|
||||
Void::Log::warn("Plugin.Manager",
|
||||
"reload '{}' aborted: activation failed", name);
|
||||
"reload '{}' aborted: activation failed", name);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
if (m_options.instance_validator &&
|
||||
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
|
||||
Void::Log::warn("Plugin.Manager",
|
||||
"reload '{}' aborted: host validation failed", name);
|
||||
"reload '{}' aborted: host validation failed",
|
||||
name);
|
||||
return std::unexpected{LoadError::ActivationFailed};
|
||||
}
|
||||
// Atomic swap. The old instance keeps living while any acquired
|
||||
@@ -421,29 +462,30 @@ namespace Void::Plugin
|
||||
return;
|
||||
}
|
||||
path = entry->path;
|
||||
entry->watched = true;
|
||||
}
|
||||
const std::string name_str{name};
|
||||
m_watcher.watch(
|
||||
path, [this, name_str](const FileSystem::FileWatcher::Event& e) {
|
||||
if (!e.exists) {
|
||||
m_watcher.watch(path, [this, name_str](
|
||||
const FileSystem::FileWatcher::Event& e) {
|
||||
if (!e.exists) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
auto* entry = find(name_str);
|
||||
if (entry == nullptr) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::function<void(std::string_view)>> callbacks;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
auto* entry = find(name_str);
|
||||
if (entry == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (!reload_locked(*entry, name_str).has_value()) {
|
||||
return;
|
||||
}
|
||||
callbacks = reload_callbacks_locked();
|
||||
if (!reload_locked(*entry, name_str, entry->path).has_value()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& cb : callbacks) {
|
||||
cb(name_str);
|
||||
}
|
||||
});
|
||||
callbacks = reload_callbacks_locked();
|
||||
}
|
||||
for (const auto& cb : callbacks) {
|
||||
cb(name_str);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void PluginManager::unwatch(std::string_view name)
|
||||
@@ -452,6 +494,7 @@ namespace Void::Plugin
|
||||
auto* entry = find(name);
|
||||
if (entry != nullptr) {
|
||||
m_watcher.unwatch(entry->path);
|
||||
entry->watched = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <csignal>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <utility>
|
||||
|
||||
#ifdef __linux__
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <sys/signalfd.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Void::Process
|
||||
{
|
||||
struct SignalWatcher::Impl {
|
||||
#ifdef __linux__
|
||||
int descriptor{-1};
|
||||
sigset_t previousMask{};
|
||||
bool maskInstalled{false};
|
||||
pthread_t owner{};
|
||||
|
||||
~Impl()
|
||||
{
|
||||
if (descriptor >= 0) {
|
||||
::close(descriptor);
|
||||
}
|
||||
if (maskInstalled &&
|
||||
pthread_equal(owner, pthread_self()) != 0) {
|
||||
(void)::pthread_sigmask(
|
||||
SIG_SETMASK, &previousMask, nullptr);
|
||||
}
|
||||
}
|
||||
#else
|
||||
~Impl() = default;
|
||||
#endif
|
||||
};
|
||||
|
||||
SignalWatcher::SignalWatcher(std::unique_ptr<Impl> impl) noexcept
|
||||
: m_impl(std::move(impl))
|
||||
{
|
||||
}
|
||||
|
||||
SignalWatcher::~SignalWatcher() = default;
|
||||
SignalWatcher::SignalWatcher(SignalWatcher&&) noexcept = default;
|
||||
SignalWatcher& SignalWatcher::operator=(SignalWatcher&&) noexcept = default;
|
||||
|
||||
Void::Result::Result<SignalWatcher>
|
||||
SignalWatcher::create(std::vector<int> signals)
|
||||
{
|
||||
#ifdef __linux__
|
||||
if (signals.empty()) {
|
||||
signals = {SIGINT, SIGTERM};
|
||||
}
|
||||
sigset_t mask{};
|
||||
if (::sigemptyset(&mask) != 0) {
|
||||
return Void::Result::fail(
|
||||
std::format("Process::SignalWatcher: sigemptyset failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
for (const int signal : signals) {
|
||||
if (signal <= 0 || signal == SIGKILL || signal == SIGSTOP ||
|
||||
::sigaddset(&mask, signal) != 0) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Process::SignalWatcher: signal {} cannot be watched",
|
||||
signal));
|
||||
}
|
||||
}
|
||||
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->owner = ::pthread_self();
|
||||
const int maskResult =
|
||||
::pthread_sigmask(SIG_BLOCK, &mask, &impl->previousMask);
|
||||
if (maskResult != 0) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Process::SignalWatcher: pthread_sigmask failed: {}",
|
||||
std::strerror(maskResult)));
|
||||
}
|
||||
impl->maskInstalled = true;
|
||||
impl->descriptor = ::signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
|
||||
if (impl->descriptor < 0) {
|
||||
return Void::Result::fail(
|
||||
std::format("Process::SignalWatcher: signalfd failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
return SignalWatcher{std::move(impl)};
|
||||
#else
|
||||
(void)signals;
|
||||
return Void::Result::fail(
|
||||
"Process::SignalWatcher is currently supported only on Linux");
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<int>>
|
||||
SignalWatcher::wait(std::chrono::milliseconds timeout)
|
||||
{
|
||||
#ifdef __linux__
|
||||
if (!m_impl || m_impl->descriptor < 0) {
|
||||
return Void::Result::fail(
|
||||
"Process::SignalWatcher::wait: watcher is moved-from");
|
||||
}
|
||||
const int timeoutMs = timeout == std::chrono::milliseconds::max()
|
||||
? -1
|
||||
: static_cast<int>(std::clamp<std::int64_t>(
|
||||
timeout.count(), 0, INT_MAX));
|
||||
pollfd descriptor{m_impl->descriptor, POLLIN, 0};
|
||||
int pollResult = 0;
|
||||
do {
|
||||
pollResult = ::poll(&descriptor, 1, timeoutMs);
|
||||
} while (pollResult < 0 && errno == EINTR);
|
||||
if (pollResult == 0) {
|
||||
return std::optional<int>{};
|
||||
}
|
||||
if (pollResult < 0) {
|
||||
return Void::Result::fail(
|
||||
std::format("Process::SignalWatcher::wait: poll failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
if ((descriptor.revents & POLLIN) == 0) {
|
||||
return Void::Result::fail(
|
||||
"Process::SignalWatcher::wait: signal descriptor closed");
|
||||
}
|
||||
signalfd_siginfo info{};
|
||||
const auto readCount = ::read(m_impl->descriptor, &info, sizeof(info));
|
||||
if (readCount != static_cast<ssize_t>(sizeof(info))) {
|
||||
return Void::Result::fail(
|
||||
std::format("Process::SignalWatcher::wait: read failed: {}",
|
||||
std::strerror(errno)));
|
||||
}
|
||||
return std::optional<int>{static_cast<int>(info.ssi_signo)};
|
||||
#else
|
||||
(void)timeout;
|
||||
return Void::Result::fail(
|
||||
"Process::SignalWatcher is currently supported only on Linux");
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<int>> SignalWatcher::poll()
|
||||
{
|
||||
return wait(std::chrono::milliseconds{0});
|
||||
}
|
||||
} // namespace Void::Process
|
||||
@@ -1,3 +1,4 @@
|
||||
void_add_module(System
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS Threads::Threads
|
||||
)
|
||||
@@ -0,0 +1,488 @@
|
||||
#include <Void/Update/Feed.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Text/Base64.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <tuple>
|
||||
|
||||
namespace Void::Update
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using JsonResult = Void::Result::Result<const Json::Value*>;
|
||||
|
||||
[[nodiscard]] JsonResult member(const Json::Value& object,
|
||||
std::string_view name,
|
||||
bool (*predicate)(const Json::Value&),
|
||||
std::string_view expected)
|
||||
{
|
||||
const auto* value = object.find(name);
|
||||
if (value == nullptr || !predicate(*value)) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Update feed: '{}' must be {}", name, expected));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_array(const Json::Value& value) noexcept
|
||||
{
|
||||
return value.is_array();
|
||||
}
|
||||
[[nodiscard]] bool is_string(const Json::Value& value) noexcept
|
||||
{
|
||||
return value.is_string();
|
||||
}
|
||||
[[nodiscard]] bool is_number(const Json::Value& value) noexcept
|
||||
{
|
||||
return value.is_number();
|
||||
}
|
||||
|
||||
template <std::unsigned_integral T>
|
||||
[[nodiscard]] Void::Result::Result<T>
|
||||
unsigned_number(const Json::Value& object, std::string_view name)
|
||||
{
|
||||
auto value = member(object, name, is_number, "an unsigned integer");
|
||||
if (!value) {
|
||||
return std::unexpected{value.error()};
|
||||
}
|
||||
const double number = (*value)->as_number();
|
||||
constexpr double maxSafeInteger = 9'007'199'254'740'991.0;
|
||||
if (!std::isfinite(number) || number < 0 ||
|
||||
std::floor(number) != number || number > maxSafeInteger ||
|
||||
number > static_cast<double>(std::numeric_limits<T>::max())) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Update feed: '{}' is outside its integer range", name));
|
||||
}
|
||||
return static_cast<T>(number);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
string_member(const Json::Value& object, std::string_view name)
|
||||
{
|
||||
auto value = member(object, name, is_string, "a string");
|
||||
if (!value) {
|
||||
return std::unexpected{value.error()};
|
||||
}
|
||||
return (*value)->as_string();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid_token(std::string_view value,
|
||||
std::size_t maximum = 128) noexcept
|
||||
{
|
||||
if (value.empty() || value.size() > maximum) {
|
||||
return false;
|
||||
}
|
||||
for (const char character : value) {
|
||||
if (!((character >= 'a' && character <= 'z') ||
|
||||
(character >= 'A' && character <= 'Z') ||
|
||||
(character >= '0' && character <= '9') ||
|
||||
character == '.' || character == '_' ||
|
||||
character == '-')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid_sha256(std::string_view value) noexcept
|
||||
{
|
||||
if (value.size() != 64) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(value, [](const char character) {
|
||||
return (character >= '0' && character <= '9') ||
|
||||
(character >= 'a' && character <= 'f');
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid_package_type(std::string_view value) noexcept
|
||||
{
|
||||
return !value.empty() && value.size() <= 128 &&
|
||||
std::ranges::all_of(value, [](const char character) {
|
||||
return (character >= 'a' && character <= 'z') ||
|
||||
(character >= '0' && character <= '9') ||
|
||||
character == '.' || character == '-' ||
|
||||
character == '_';
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<int>
|
||||
decimal(std::string_view value) noexcept
|
||||
{
|
||||
int result = 0;
|
||||
for (const char character : value) {
|
||||
if (character < '0' || character > '9') {
|
||||
return std::nullopt;
|
||||
}
|
||||
result = result * 10 + (character - '0');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::chrono::system_clock::time_point>
|
||||
parse_timestamp(std::string_view value) noexcept
|
||||
{
|
||||
if (value.size() < 20 || value[4] != '-' || value[7] != '-' ||
|
||||
value[10] != 'T' || value[13] != ':' || value[16] != ':' ||
|
||||
value.back() != 'Z') {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto year = decimal(value.substr(0, 4));
|
||||
const auto month = decimal(value.substr(5, 2));
|
||||
const auto day = decimal(value.substr(8, 2));
|
||||
const auto hour = decimal(value.substr(11, 2));
|
||||
const auto minute = decimal(value.substr(14, 2));
|
||||
const auto second = decimal(value.substr(17, 2));
|
||||
if (!year || !month || !day || !hour || !minute || !second ||
|
||||
*hour > 23 || *minute > 59 || *second > 59) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (value.size() > 20) {
|
||||
if (value.size() == 21 || value[19] != '.') {
|
||||
return std::nullopt;
|
||||
}
|
||||
for (std::size_t index = 20; index + 1 < value.size();
|
||||
++index) {
|
||||
if (value[index] < '0' || value[index] > '9') {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
}
|
||||
const std::chrono::year_month_day date{
|
||||
std::chrono::year{*year},
|
||||
std::chrono::month{static_cast<unsigned>(*month)},
|
||||
std::chrono::day{static_cast<unsigned>(*day)}};
|
||||
if (!date.ok()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::chrono::sys_days{date} + std::chrono::hours{*hour} +
|
||||
std::chrono::minutes{*minute} +
|
||||
std::chrono::seconds{*second};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Compatibility>
|
||||
parse_compatibility(const Json::Value& value)
|
||||
{
|
||||
if (!value.is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: compatibility must be an object");
|
||||
}
|
||||
Compatibility result;
|
||||
if (const auto* contracts = value.find("versionContracts")) {
|
||||
if (!contracts->is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: compatibility.versionContracts must be "
|
||||
"an object");
|
||||
}
|
||||
for (const auto& [name, rangeValue] : contracts->as_object()) {
|
||||
if (!valid_token(name, 256) || !rangeValue.is_string()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: invalid version contract");
|
||||
}
|
||||
auto range = Semver::parse_range(rangeValue.as_string());
|
||||
if (!range) {
|
||||
return Void::Result::fail(
|
||||
std::format("Update feed: version contract '{}' "
|
||||
"has an invalid range",
|
||||
name));
|
||||
}
|
||||
result.versionContracts.emplace(name, std::move(*range));
|
||||
}
|
||||
}
|
||||
if (const auto* contracts = value.find("exactContracts")) {
|
||||
if (!contracts->is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: compatibility.exactContracts must be an "
|
||||
"object");
|
||||
}
|
||||
for (const auto& [name, contractValue] :
|
||||
contracts->as_object()) {
|
||||
if (!valid_token(name, 256) || !contractValue.is_string() ||
|
||||
contractValue.as_string().empty() ||
|
||||
contractValue.as_string().size() > 512) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: invalid exact contract");
|
||||
}
|
||||
result.exactContracts.emplace(name,
|
||||
contractValue.as_string());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Release>
|
||||
parse_release(const Json::Value& value)
|
||||
{
|
||||
if (!value.is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: release must be an object");
|
||||
}
|
||||
Release release;
|
||||
auto component = string_member(value, "component");
|
||||
if (!component || !valid_token(*component, 256)) {
|
||||
return Void::Result::fail("Update feed: component is invalid");
|
||||
}
|
||||
release.component = std::move(*component);
|
||||
release.artifactId = value.get_str("artifactId");
|
||||
if (!release.artifactId.empty() &&
|
||||
!valid_token(release.artifactId, 256)) {
|
||||
return Void::Result::fail("Update feed: artifactId is invalid");
|
||||
}
|
||||
|
||||
auto channel = string_member(value, "channel");
|
||||
auto versionText = string_member(value, "version");
|
||||
auto platform = string_member(value, "platform");
|
||||
auto architecture = string_member(value, "arch");
|
||||
auto url = string_member(value, "url");
|
||||
auto size = unsigned_number<std::uint64_t>(value, "size");
|
||||
auto sha256 = string_member(value, "sha256");
|
||||
auto packageType = string_member(value, "packageType");
|
||||
if (!channel || !versionText || !platform || !architecture ||
|
||||
!url || !size || !sha256 || !packageType) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: release has invalid required fields");
|
||||
}
|
||||
const auto cohort = value.get_str("cohort");
|
||||
const auto manifestHash = value.get_str("releaseManifestSha256");
|
||||
const bool urlIsBounded =
|
||||
!url->empty() && url->size() <= 8192 &&
|
||||
std::ranges::none_of(*url, [](const unsigned char character) {
|
||||
return character < 0x20 || character == 0x7f;
|
||||
});
|
||||
if (!valid_token(*channel) ||
|
||||
(!cohort.empty() && !valid_token(cohort, 256)) ||
|
||||
!valid_token(*platform) || !valid_token(*architecture) ||
|
||||
!urlIsBounded || *size == 0 || !valid_sha256(*sha256) ||
|
||||
!valid_package_type(*packageType) ||
|
||||
(!manifestHash.empty() && !valid_sha256(manifestHash))) {
|
||||
return Void::Result::fail("Update feed: release contains an "
|
||||
"unsafe or unsupported field");
|
||||
}
|
||||
auto version = Semver::parse_strict(*versionText);
|
||||
if (!version) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: release version is invalid SemVer");
|
||||
}
|
||||
release.channel = std::move(*channel);
|
||||
release.version = std::move(*version);
|
||||
release.cohort = cohort;
|
||||
release.platform = std::move(*platform);
|
||||
release.architecture = std::move(*architecture);
|
||||
release.url = std::move(*url);
|
||||
release.size = *size;
|
||||
release.sha256 = std::move(*sha256);
|
||||
release.packageType = std::move(*packageType);
|
||||
release.releaseManifestSha256 = manifestHash;
|
||||
const auto* compatibility = value.find("compatibility");
|
||||
if (compatibility) {
|
||||
auto parsedCompatibility = parse_compatibility(*compatibility);
|
||||
if (!parsedCompatibility) {
|
||||
return std::unexpected{parsedCompatibility.error()};
|
||||
}
|
||||
release.compatibility = std::move(*parsedCompatibility);
|
||||
}
|
||||
return release;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Feed>
|
||||
parse_feed(std::string_view payload,
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
auto document = Json::parse(payload);
|
||||
if (!document || !document->is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: signed payload is not a JSON object");
|
||||
}
|
||||
auto schema =
|
||||
unsigned_number<std::uint32_t>(*document, "schemaVersion");
|
||||
auto feedId = string_member(*document, "feedId");
|
||||
auto sequence =
|
||||
unsigned_number<std::uint64_t>(*document, "sequence");
|
||||
auto generated = string_member(*document, "generatedAt");
|
||||
auto expires = string_member(*document, "expiresAt");
|
||||
auto releasesValue =
|
||||
member(*document, "releases", is_array, "an array");
|
||||
if (!schema || !feedId || !sequence || !generated || !expires ||
|
||||
!releasesValue) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: invalid top-level fields");
|
||||
}
|
||||
if (*schema != 1 || !valid_token(*feedId, 256)) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: unsupported schema or invalid feedId");
|
||||
}
|
||||
if (policy.minimumSequence &&
|
||||
*sequence <= *policy.minimumSequence) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: sequence is not newer than the replay floor");
|
||||
}
|
||||
const auto generatedAt = parse_timestamp(*generated);
|
||||
const auto expiresAt = parse_timestamp(*expires);
|
||||
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: timestamps are invalid");
|
||||
}
|
||||
if (policy.requireUnexpired && policy.now >= *expiresAt) {
|
||||
return Void::Result::fail("Update feed: feed has expired");
|
||||
}
|
||||
const auto& values = (*releasesValue)->as_array();
|
||||
if (values.size() > policy.maxReleases) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: release count exceeds policy");
|
||||
}
|
||||
Feed feed{.schemaVersion = *schema,
|
||||
.feedId = std::move(*feedId),
|
||||
.sequence = *sequence,
|
||||
.generatedAt = *generatedAt,
|
||||
.expiresAt = *expiresAt};
|
||||
std::set<std::tuple<std::string, std::string, std::string,
|
||||
std::string, std::string, std::string>>
|
||||
identities;
|
||||
feed.releases.reserve(values.size());
|
||||
for (const auto& value : values) {
|
||||
auto release = parse_release(value);
|
||||
if (!release) {
|
||||
return std::unexpected{release.error()};
|
||||
}
|
||||
auto identity =
|
||||
std::tuple{release->component, release->artifactId,
|
||||
release->channel, release->version.to_string(),
|
||||
release->platform, release->architecture};
|
||||
if (!identities.insert(std::move(identity)).second) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: ambiguous duplicate release identity");
|
||||
}
|
||||
feed.releases.push_back(std::move(*release));
|
||||
}
|
||||
return feed;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool compatible(const Compatibility& compatibility,
|
||||
const Environment& environment) noexcept
|
||||
{
|
||||
for (const auto& [name, range] : compatibility.versionContracts) {
|
||||
const auto installed = environment.versionContracts.find(name);
|
||||
if (installed == environment.versionContracts.end() ||
|
||||
!range.contains(installed->second)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (const auto& [name, value] : compatibility.exactContracts) {
|
||||
const auto installed = environment.exactContracts.find(name);
|
||||
if (installed == environment.exactContracts.end() ||
|
||||
installed->second != value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<Feed>
|
||||
parseFeedPayload(std::string_view payload,
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
if (payload.size() > policy.maxPayloadBytes) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: payload exceeds policy size");
|
||||
}
|
||||
return parse_feed(payload, policy);
|
||||
}
|
||||
|
||||
Void::Result::Result<VerifiedFeed>
|
||||
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
if (envelopeJson.size() > policy.maxEnvelopeBytes) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: envelope exceeds policy size");
|
||||
}
|
||||
auto envelope = Json::parse(envelopeJson);
|
||||
if (!envelope || !envelope->is_object()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: envelope is not a JSON object");
|
||||
}
|
||||
auto schema =
|
||||
unsigned_number<std::uint32_t>(*envelope, "schemaVersion");
|
||||
auto keyId = string_member(*envelope, "keyId");
|
||||
auto payloadText = string_member(*envelope, "payload");
|
||||
auto signatureText = string_member(*envelope, "signature");
|
||||
if (!schema || !keyId || !payloadText || !signatureText ||
|
||||
*schema != 1 || !valid_token(*keyId, 256)) {
|
||||
return Void::Result::fail("Update feed: invalid envelope fields");
|
||||
}
|
||||
const auto key = keys.find(*keyId);
|
||||
if (key == keys.end()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: envelope key is not trusted");
|
||||
}
|
||||
auto payload = Encoding::Base64::decode_url(*payloadText);
|
||||
auto signature = Encoding::Base64::decode_url(*signatureText);
|
||||
if (!payload || !signature ||
|
||||
payload->size() > policy.maxPayloadBytes) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: invalid or oversized envelope encoding");
|
||||
}
|
||||
const auto signatureBytes =
|
||||
std::as_bytes(std::span{signature->data(), signature->size()});
|
||||
const auto payloadBytes =
|
||||
std::as_bytes(std::span{payload->data(), payload->size()});
|
||||
auto valid =
|
||||
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
|
||||
if (!valid) {
|
||||
return std::unexpected{valid.error()};
|
||||
}
|
||||
if (!*valid) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: signature verification failed");
|
||||
}
|
||||
auto feed = parseFeedPayload(*payload, policy);
|
||||
if (!feed) {
|
||||
return std::unexpected{feed.error()};
|
||||
}
|
||||
return VerifiedFeed{.feed = std::move(*feed),
|
||||
.keyId = std::move(*keyId),
|
||||
.signedPayload = std::move(*payload)};
|
||||
}
|
||||
|
||||
std::optional<Release> selectRelease(const Feed& feed,
|
||||
const SelectionRequest& request)
|
||||
{
|
||||
const Release* selected = nullptr;
|
||||
for (const auto& release : feed.releases) {
|
||||
if (release.component != request.component ||
|
||||
release.artifactId != request.artifactId ||
|
||||
release.channel != request.channel ||
|
||||
release.platform != request.environment.platform ||
|
||||
release.architecture != request.environment.architecture ||
|
||||
(request.requiredCohort &&
|
||||
release.cohort != *request.requiredCohort) ||
|
||||
!compatible(release.compatibility, request.environment)) {
|
||||
continue;
|
||||
}
|
||||
if (request.currentVersion) {
|
||||
const auto comparison =
|
||||
release.version <=> *request.currentVersion;
|
||||
if (comparison == 0 && !request.includeCurrent) {
|
||||
continue;
|
||||
}
|
||||
if (comparison < 0 && !request.allowDowngrade) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (selected == nullptr || release.version > selected->version) {
|
||||
selected = &release;
|
||||
}
|
||||
}
|
||||
if (selected == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return *selected;
|
||||
}
|
||||
} // namespace Void::Update
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Update
|
||||
INTERNAL_DEPS Crypto Data Functional System Text
|
||||
)
|
||||
Reference in new issue
Block a user