176 lines
6.2 KiB
C++
176 lines
6.2 KiB
C++
#include "evo/network/grant_ledger.hpp"
|
|
#include <cerrno>
|
|
#include <charconv>
|
|
#include <fstream>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
|
|
#ifdef _WIN32
|
|
#include <io.h>
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
#else
|
|
#include <fcntl.h>
|
|
#include <sys/file.h>
|
|
#include <unistd.h>
|
|
#endif
|
|
|
|
namespace evo::network {
|
|
namespace {
|
|
std::FILE* open_file(const std::filesystem::path& path, const char* mode) {
|
|
#ifdef _WIN32
|
|
std::FILE* file = nullptr;
|
|
return _wfopen_s(&file, path.c_str(), mode[0] == 'w' ? L"wb" : L"ab") == 0 ? file : nullptr;
|
|
#else
|
|
return std::fopen(path.c_str(), mode);
|
|
#endif
|
|
}
|
|
bool sync(std::FILE* file) {
|
|
if (std::fflush(file) != 0)
|
|
return false;
|
|
#ifdef _WIN32
|
|
return _commit(_fileno(file)) == 0;
|
|
#else
|
|
return ::fsync(::fileno(file)) == 0;
|
|
#endif
|
|
}
|
|
// Makes a rename durable on POSIX by syncing the containing directory.
|
|
bool sync_directory([[maybe_unused]] const std::filesystem::path& dir) {
|
|
#ifdef _WIN32
|
|
return true; // NTFS metadata journaling; MoveFileEx is used with replace semantics.
|
|
#else
|
|
const int fd = ::open(dir.empty() ? "." : dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
|
if (fd < 0)
|
|
return false;
|
|
const bool ok = ::fsync(fd) == 0;
|
|
return ::close(fd) == 0 && ok;
|
|
#endif
|
|
}
|
|
std::string line(ConsumedGrant g) {
|
|
constexpr char digits[] = "0123456789abcdef";
|
|
std::string out(16, '0');
|
|
for (int i = 15; i >= 0; --i, g.grant_id >>= 4U)
|
|
out[static_cast<std::size_t>(i)] = digits[g.grant_id & 0x0FU];
|
|
return out + ' ' + std::to_string(g.expires_at) + '\n';
|
|
}
|
|
bool parse(const std::string& text, ConsumedGrant& out) { // One complete bounded line.
|
|
if (text.size() < 18 || text[16] != ' ')
|
|
return false;
|
|
const auto [a, e1] = std::from_chars(text.data(), text.data() + 16, out.grant_id, 16);
|
|
const auto [b, e2] =
|
|
std::from_chars(text.data() + 17, text.data() + text.size(), out.expires_at);
|
|
return e1 == std::errc{} && a == text.data() + 16 && e2 == std::errc{} &&
|
|
b == text.data() + text.size() && out.grant_id != 0;
|
|
}
|
|
} // namespace
|
|
|
|
// A separate, stable file: locking the ledger inode would not survive compaction.
|
|
struct GrantLedger::Lock {
|
|
#ifdef _WIN32
|
|
HANDLE handle{INVALID_HANDLE_VALUE};
|
|
~Lock() {
|
|
if (handle != INVALID_HANDLE_VALUE)
|
|
CloseHandle(handle);
|
|
}
|
|
#else
|
|
int descriptor{-1};
|
|
~Lock() {
|
|
if (descriptor >= 0)
|
|
::close(descriptor);
|
|
}
|
|
#endif
|
|
};
|
|
|
|
GrantLedger::GrantLedger(std::FILE* file, std::vector<ConsumedGrant> loaded,
|
|
std::unique_ptr<Lock> lock)
|
|
: lock_{std::move(lock)}, file_{file}, loaded_{std::move(loaded)}, entries_{loaded_.size()} {}
|
|
|
|
std::expected<std::unique_ptr<GrantLedger>, LedgerError>
|
|
GrantLedger::open(const std::filesystem::path& path, std::uint64_t now_seconds) {
|
|
auto lock = std::make_unique<Lock>();
|
|
const auto lock_path = std::filesystem::path{path}.concat(".lock");
|
|
#ifdef _WIN32
|
|
lock->handle = CreateFileW(lock_path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr,
|
|
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (lock->handle == INVALID_HANDLE_VALUE)
|
|
return std::unexpected(GetLastError() == ERROR_SHARING_VIOLATION ? LedgerError::busy
|
|
: LedgerError::io);
|
|
#else
|
|
lock->descriptor = ::open(lock_path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
|
|
if (lock->descriptor < 0)
|
|
return std::unexpected(LedgerError::io);
|
|
if (::flock(lock->descriptor, LOCK_EX | LOCK_NB) != 0)
|
|
return std::unexpected(errno == EWOULDBLOCK ? LedgerError::busy : LedgerError::io);
|
|
#endif
|
|
std::vector<ConsumedGrant> live;
|
|
std::error_code error;
|
|
if (std::filesystem::exists(path, error)) {
|
|
std::ifstream in{path, std::ios::binary};
|
|
if (!in)
|
|
return std::unexpected(LedgerError::io);
|
|
std::string text;
|
|
std::size_t total = 0;
|
|
constexpr std::size_t max_line_bytes = 16 + 1 + 20; // hex id, space, u64 expiry.
|
|
char byte{};
|
|
while (in.get(byte)) {
|
|
if (byte != '\n') {
|
|
if (text.size() == max_line_bytes)
|
|
return std::unexpected(LedgerError::corrupt);
|
|
text.push_back(byte);
|
|
continue;
|
|
}
|
|
ConsumedGrant g;
|
|
if (!parse(text, g))
|
|
return std::unexpected(LedgerError::corrupt); // Never guess: fail closed.
|
|
if (++total > max_entries)
|
|
return std::unexpected(LedgerError::full);
|
|
if (g.expires_at > now_seconds)
|
|
live.push_back(g);
|
|
text.clear();
|
|
}
|
|
if (in.bad() || !in.eof())
|
|
return std::unexpected(LedgerError::io);
|
|
if (!text.empty())
|
|
return std::unexpected(LedgerError::corrupt); // Unterminated record: never compact.
|
|
} else if (error) {
|
|
return std::unexpected(LedgerError::io);
|
|
}
|
|
// Rewrite the unexpired entries atomically, then append to the result.
|
|
const auto temporary = std::filesystem::path{path}.concat(".tmp");
|
|
{
|
|
std::FILE* out = open_file(temporary, "wb");
|
|
if (out == nullptr)
|
|
return std::unexpected(LedgerError::io);
|
|
bool ok = true;
|
|
for (const auto& g : live)
|
|
ok = ok && std::fputs(line(g).c_str(), out) >= 0;
|
|
ok = sync(out) && ok;
|
|
if (std::fclose(out) != 0 || !ok)
|
|
return std::unexpected(LedgerError::io);
|
|
}
|
|
std::filesystem::rename(temporary, path, error);
|
|
if (error || !sync_directory(path.parent_path()))
|
|
return std::unexpected(LedgerError::io);
|
|
std::FILE* file = open_file(path, "ab");
|
|
if (file == nullptr)
|
|
return std::unexpected(LedgerError::io);
|
|
return std::unique_ptr<GrantLedger>(new GrantLedger(file, std::move(live), std::move(lock)));
|
|
}
|
|
|
|
GrantLedger::~GrantLedger() {
|
|
std::fclose(file_);
|
|
}
|
|
|
|
std::expected<void, LedgerError> GrantLedger::record(ConsumedGrant grant) {
|
|
if (entries_ >= max_entries)
|
|
return std::unexpected(LedgerError::full);
|
|
if (std::fputs(line(grant).c_str(), file_) < 0 || !sync(file_))
|
|
return std::unexpected(LedgerError::io);
|
|
++entries_;
|
|
return {};
|
|
}
|
|
} // namespace evo::network
|