#include "ReleaseTree.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { namespace fs = std::filesystem; constexpr std::string_view kProgramName{"echoion-updater"}; constexpr std::uintmax_t kMaximumRequestBytes{64U * 1024U}; constexpr std::uint32_t kDefaultRetainedVersions{2U}; constexpr auto kRuntimeHealthGrace = std::chrono::seconds{60}; class UpdateError final : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class FileDescriptor final { public: explicit FileDescriptor(const int descriptor = -1) noexcept : descriptor_{descriptor} { } ~FileDescriptor() { if (descriptor_ >= 0) { ::close(descriptor_); } } FileDescriptor(const FileDescriptor&) = delete; FileDescriptor& operator=(const FileDescriptor&) = delete; FileDescriptor(FileDescriptor&& other) noexcept : descriptor_{std::exchange(other.descriptor_, -1)} { } FileDescriptor& operator=(FileDescriptor&& other) noexcept { if (this != &other) { if (descriptor_ >= 0) { ::close(descriptor_); } descriptor_ = std::exchange(other.descriptor_, -1); } return *this; } [[nodiscard]] int get() const noexcept { return descriptor_; } private: int descriptor_{-1}; }; struct DirectoryCloser { void operator()(DIR* directory) const noexcept { if (directory != nullptr) { ::closedir(directory); } } }; using Directory = std::unique_ptr; [[nodiscard]] std::string systemError(const std::string_view operation) { return std::string{operation} + ": " + std::strerror(errno); } [[nodiscard]] bool safeIdentifier(const std::string_view value) { static const std::regex pattern{R"(^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$)"}; return std::regex_match(value.begin(), value.end(), pattern) && value != "." && value != ".."; } [[nodiscard]] bool safeDigest(const std::string_view value) { static const std::regex pattern{R"(^[0-9a-f]{64}$)"}; return std::regex_match(value.begin(), value.end(), pattern); } [[nodiscard]] std::string jsonEscape(const std::string_view value) { std::ostringstream output; for (const char rawCharacter : value) { const auto character = static_cast(rawCharacter); switch (character) { case '\\': output << "\\\\"; break; case '"': output << "\\\""; break; case '\b': output << "\\b"; break; case '\f': output << "\\f"; break; case '\n': output << "\\n"; break; case '\r': output << "\\r"; break; case '\t': output << "\\t"; break; default: if (character < 0x20U) { output << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast(character) << std::dec; } else { output << static_cast(character); } } } return output.str(); } [[nodiscard]] std::string nowUtc() { const auto now = std::chrono::system_clock::now(); const std::time_t value = std::chrono::system_clock::to_time_t(now); std::tm utc{}; if (::gmtime_r(&value, &utc) == nullptr) { throw UpdateError{"cannot format the current time"}; } std::ostringstream output; output << std::put_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); return output.str(); } [[nodiscard]] std::string requestId() { std::random_device random; std::array words{}; std::generate(words.begin(), words.end(), [&random] { return random(); }); std::ostringstream output; output << std::hex << std::setfill('0'); for (const auto word : words) { output << std::setw(8) << word; } return output.str(); } [[nodiscard]] fs::path canonicalDirectory(const fs::path& path, const std::string_view description) { std::error_code error; const auto status = fs::symlink_status(path, error); if (error || !fs::is_directory(status) || fs::is_symlink(status)) { throw UpdateError{std::string{description} + " is not a real directory: " + path.string()}; } const auto canonical = fs::canonical(path, error); if (error) { throw UpdateError{"cannot resolve " + std::string{description} + ": " + error.message()}; } return canonical; } void requireRegularFile(const fs::path& path, const std::string_view description, const bool executable = false) { std::error_code error; const auto status = fs::symlink_status(path, error); if (error || !fs::is_regular_file(status) || fs::is_symlink(status)) { throw UpdateError{std::string{description} + " is not a regular file: " + path.string()}; } if (executable && (::access(path.c_str(), X_OK) != 0)) { throw UpdateError{std::string{description} + " is not executable: " + path.string()}; } } class PrefixLock final { public: explicit PrefixLock(const fs::path& root) : descriptor_{ ::open(root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)} { if (descriptor_.get() < 0) { throw UpdateError{ systemError("cannot open installation root")}; } if (::flock(descriptor_.get(), LOCK_EX | LOCK_NB) != 0) { throw UpdateError{ errno == EWOULDBLOCK ? "another install, uninstall, or update is active" : systemError("cannot lock installation root")}; } } private: FileDescriptor descriptor_; }; [[nodiscard]] std::map loadInstallRecord(const fs::path& root) { const fs::path path = root / ".echoion-install"; requireRegularFile(path, "install record"); std::ifstream input{path}; if (!input) { throw UpdateError{"cannot open install record: " + path.string()}; } std::map values; std::string line; while (std::getline(input, line)) { const auto separator = line.find('='); if (separator == std::string::npos || separator == 0U) { throw UpdateError{"install record contains an invalid line"}; } values.emplace(line.substr(0, separator), line.substr(separator + 1U)); } if (values["format"] != "1") { throw UpdateError{"unsupported install record format"}; } return values; } [[nodiscard]] fs::path resolveRecordedPath(const fs::path& root, const std::map& record, const std::string_view key) { const auto iterator = record.find(std::string{key}); if (iterator == record.end() || iterator->second.empty()) { throw UpdateError{"install record has no " + std::string{key}}; } fs::path path{iterator->second}; if (path.is_relative()) { path = root / path; } return fs::weakly_canonical(path); } [[nodiscard]] std::string currentVersion(const fs::path& root) { const fs::path current = root / "current"; std::error_code error; const auto status = fs::symlink_status(current, error); if (error || !fs::is_symlink(status)) { throw UpdateError{"current release link is missing"}; } const fs::path target = fs::read_symlink(current, error); if (error || target.is_absolute() || target.parent_path() != "versions" || !safeIdentifier(target.filename().string())) { throw UpdateError{"current release link has an unsafe target"}; } return target.filename().string(); } [[nodiscard]] fs::path validateRelease(const fs::path& root, const std::string_view version) { if (!safeIdentifier(version)) { throw UpdateError{"unsafe release version"}; } const fs::path versions = canonicalDirectory(root / "versions", "versions directory"); const fs::path release = canonicalDirectory(versions / version, "release directory"); if (release.parent_path() != versions) { throw UpdateError{"release directory escapes versions"}; } requireRegularFile(release / "manifest.json", "release manifest"); requireRegularFile(release / "bin/echoiond", "Echoion daemon", true); requireRegularFile(release / "bin/echoion-updater", "Echoion updater", true); requireRegularFile(release / "lib/Echoion.ts", "Echoion Core"); return release; } [[nodiscard]] std::vector installedVersions(const fs::path& root) { const fs::path versions = canonicalDirectory(root / "versions", "versions directory"); std::vector> candidates; for (const auto& entry : fs::directory_iterator{versions}) { const std::string name = entry.path().filename().string(); std::error_code error; const auto status = entry.symlink_status(error); if (error || !fs::is_directory(status) || fs::is_symlink(status) || !safeIdentifier(name)) { continue; } try { static_cast(validateRelease(root, name)); candidates.emplace_back(entry.last_write_time(), name); } catch (const UpdateError&) { // An incomplete staging directory is not an installed version. } } std::ranges::sort(candidates, std::greater{}); std::vector result; result.reserve(candidates.size()); std::ranges::transform(candidates, std::back_inserter(result), [](const auto& item) { return item.second; }); return result; } void syncDirectory(const fs::path& directory) { const FileDescriptor descriptor{ ::open(directory.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)}; if (descriptor.get() < 0 || ::fsync(descriptor.get()) != 0) { throw UpdateError{systemError("cannot sync directory")}; } } void atomicWrite(const fs::path& destination, const std::string_view bytes, const mode_t mode = 0600) { fs::create_directories(destination.parent_path()); const fs::path temporary = destination.parent_path() / ("." + destination.filename().string() + "." + std::to_string(::getpid()) + "." + requestId()); const FileDescriptor descriptor{::open( temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode)}; if (descriptor.get() < 0) { throw UpdateError{ systemError("cannot create temporary updater file")}; } if (::fchmod(descriptor.get(), mode) != 0) { fs::remove(temporary); throw UpdateError{systemError("cannot set updater file mode")}; } std::size_t offset{}; while (offset < bytes.size()) { const auto written = ::write( descriptor.get(), bytes.data() + offset, bytes.size() - offset); if (written < 0) { if (errno == EINTR) { continue; } fs::remove(temporary); throw UpdateError{systemError("cannot write updater file")}; } if (written == 0) { fs::remove(temporary); throw UpdateError{"short write while publishing updater file"}; } offset += static_cast(written); } if (::fsync(descriptor.get()) != 0) { fs::remove(temporary); throw UpdateError{systemError("cannot sync updater file")}; } std::error_code error; fs::rename(temporary, destination, error); if (error) { fs::remove(temporary); throw UpdateError{"cannot publish updater file: " + error.message()}; } syncDirectory(destination.parent_path()); } [[nodiscard]] std::string readRegularFileNoFollow(const fs::path& path, const std::size_t maximumBytes) { const FileDescriptor descriptor{ ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; if (descriptor.get() < 0) { throw UpdateError{systemError("cannot open updater request")}; } struct stat metadata{}; if (::fstat(descriptor.get(), &metadata) != 0 || !S_ISREG(metadata.st_mode) || metadata.st_size < 0 || static_cast(metadata.st_size) > maximumBytes) { throw UpdateError{"updater request is not a bounded regular file"}; } std::string result(static_cast(metadata.st_size), '\0'); std::size_t offset{}; while (offset < result.size()) { const auto count = ::read(descriptor.get(), result.data() + offset, result.size() - offset); if (count < 0) { if (errno == EINTR) { continue; } throw UpdateError{systemError("cannot read updater request")}; } if (count == 0) { throw UpdateError{ "updater request ended before its recorded size"}; } offset += static_cast(count); } char extra{}; if (::read(descriptor.get(), &extra, 1U) != 0) { throw UpdateError{"updater request changed while it was read"}; } return result; } void requireLeafName(const std::string_view name) { if (name.empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0')) { throw UpdateError{"unsafe updater state entry name"}; } } void syncDirectoryDescriptor(const int descriptor, const std::string_view description) { if (::fsync(descriptor) != 0) { throw UpdateError{systemError(description)}; } } [[nodiscard]] FileDescriptor openRealDirectory(const fs::path& path, const std::string_view description) { FileDescriptor descriptor{::open( path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; struct stat metadata{}; if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || !S_ISDIR(metadata.st_mode)) { throw UpdateError{"cannot pin " + std::string{description} + ": " + (descriptor.get() < 0 ? std::strerror(errno) : "not a directory")}; } return descriptor; } [[nodiscard]] FileDescriptor openDirectoryAt(const int parent, const std::string_view name, const mode_t mode = 0750) { requireLeafName(name); const std::string ownedName{name}; bool created{false}; if (::mkdirat(parent, ownedName.c_str(), mode) == 0) { created = true; } else if (errno != EEXIST) { throw UpdateError{ systemError("cannot create updater state directory")}; } FileDescriptor descriptor{ ::openat(parent, ownedName.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; struct stat metadata{}; if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || !S_ISDIR(metadata.st_mode)) { throw UpdateError{"updater state entry is not a real directory: " + ownedName}; } if (created) { struct stat parentMetadata{}; if (::fstat(parent, &parentMetadata) != 0 || ::fchown(descriptor.get(), parentMetadata.st_uid, parentMetadata.st_gid) != 0 || ::fchmod(descriptor.get(), mode) != 0) { throw UpdateError{ systemError("cannot initialize updater state directory")}; } syncDirectoryDescriptor(parent, "cannot sync updater state parent"); } return descriptor; } class UpdateDirectories final { public: explicit UpdateDirectories(const fs::path& root) { const auto record = loadInstallRecord(root); const fs::path statePath = resolveRecordedPath(root, record, "state_dir"); state_ = openRealDirectory(statePath, "state directory"); updates_ = openDirectoryAt(state_.get(), "updates"); privilegedRequests_ = openDirectoryAt(updates_.get(), "privileged-requests"); processed_ = openDirectoryAt(updates_.get(), "processed"); rejected_ = openDirectoryAt(updates_.get(), "rejected"); staged_ = openDirectoryAt(updates_.get(), "staged"); path_ = statePath / "updates"; } [[nodiscard]] int updates() const noexcept { return updates_.get(); } [[nodiscard]] int privilegedRequests() const noexcept { return privilegedRequests_.get(); } [[nodiscard]] int processed() const noexcept { return processed_.get(); } [[nodiscard]] int rejected() const noexcept { return rejected_.get(); } [[nodiscard]] int staged() const noexcept { return staged_.get(); } [[nodiscard]] const fs::path& path() const noexcept { return path_; } private: fs::path path_; FileDescriptor state_; FileDescriptor updates_; FileDescriptor privilegedRequests_; FileDescriptor processed_; FileDescriptor rejected_; FileDescriptor staged_; }; void writeAll(const int descriptor, const std::string_view bytes) { std::size_t offset{}; while (offset < bytes.size()) { const auto written = ::write(descriptor, bytes.data() + offset, bytes.size() - offset); if (written < 0) { if (errno == EINTR) { continue; } throw UpdateError{systemError("cannot write updater state")}; } if (written == 0) { throw UpdateError{"short write while publishing updater state"}; } offset += static_cast(written); } } void atomicWriteAt(const int directory, const std::string_view name, const std::string_view bytes, const mode_t mode = 0600) { requireLeafName(name); const std::string ownedName{name}; const std::string temporary = "." + ownedName + "." + std::to_string(::getpid()) + "." + requestId(); FileDescriptor descriptor{::openat( directory, temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, mode)}; if (descriptor.get() < 0) { throw UpdateError{ systemError("cannot create temporary updater state")}; } try { if (::fchmod(descriptor.get(), mode) != 0) { throw UpdateError{ systemError("cannot set updater state file mode")}; } writeAll(descriptor.get(), bytes); if (::fsync(descriptor.get()) != 0) { throw UpdateError{ systemError("cannot sync updater state file")}; } if (::renameat(directory, temporary.c_str(), directory, ownedName.c_str()) != 0) { throw UpdateError{systemError("cannot publish updater state")}; } } catch (...) { static_cast(::unlinkat(directory, temporary.c_str(), 0)); throw; } syncDirectoryDescriptor(directory, "cannot sync updater state directory"); } [[nodiscard]] bool fileExistsAt(const int directory, const std::string_view name) { requireLeafName(name); const std::string ownedName{name}; struct stat metadata{}; if (::fstatat(directory, ownedName.c_str(), &metadata, AT_SYMLINK_NOFOLLOW) == 0) { if (!S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { throw UpdateError{ "updater state entry is not a singly linked regular file"}; } return true; } if (errno == ENOENT) { return false; } throw UpdateError{systemError("cannot inspect updater state entry")}; } [[nodiscard]] std::string readRegularFileAt(const int directory, const std::string_view name, const std::size_t maximumBytes) { requireLeafName(name); const std::string ownedName{name}; const FileDescriptor descriptor{ ::openat(directory, ownedName.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; if (descriptor.get() < 0) { throw UpdateError{systemError("cannot open updater state entry")}; } struct stat before{}; if (::fstat(descriptor.get(), &before) != 0 || !S_ISREG(before.st_mode) || before.st_nlink != 1 || before.st_size < 0 || static_cast(before.st_size) > maximumBytes) { throw UpdateError{ "updater state entry is not a bounded regular file"}; } std::string result(static_cast(before.st_size), '\0'); std::size_t offset{}; while (offset < result.size()) { const auto count = ::read(descriptor.get(), result.data() + offset, result.size() - offset); if (count < 0) { if (errno == EINTR) { continue; } throw UpdateError{ systemError("cannot read updater state entry")}; } if (count == 0) { throw UpdateError{ "updater state entry ended before its recorded size"}; } offset += static_cast(count); } char extra{}; ssize_t extraCount{}; do { extraCount = ::read(descriptor.get(), &extra, 1U); } while (extraCount < 0 && errno == EINTR); struct stat after{}; if (extraCount != 0 || ::fstat(descriptor.get(), &after) != 0 || before.st_dev != after.st_dev || before.st_ino != after.st_ino || before.st_size != after.st_size || before.st_mtim.tv_sec != after.st_mtim.tv_sec || before.st_mtim.tv_nsec != after.st_mtim.tv_nsec || before.st_ctim.tv_sec != after.st_ctim.tv_sec || before.st_ctim.tv_nsec != after.st_ctim.tv_nsec) { throw UpdateError{"updater state entry changed while it was read"}; } return result; } void unlinkFileAt(const int directory, const std::string_view name) { requireLeafName(name); const std::string ownedName{name}; if (::unlinkat(directory, ownedName.c_str(), 0) != 0) { throw UpdateError{systemError("cannot remove updater state entry")}; } syncDirectoryDescriptor(directory, "cannot sync updater state directory"); } void moveFileAt(const int sourceDirectory, const std::string_view sourceName, const int destinationDirectory, const std::string_view destinationName) { requireLeafName(sourceName); requireLeafName(destinationName); const std::string ownedSource{sourceName}; const std::string ownedDestination{destinationName}; if (::renameat(sourceDirectory, ownedSource.c_str(), destinationDirectory, ownedDestination.c_str()) != 0) { throw UpdateError{systemError("cannot move updater state entry")}; } syncDirectoryDescriptor(sourceDirectory, "cannot sync updater source directory"); if (sourceDirectory != destinationDirectory) { syncDirectoryDescriptor( destinationDirectory, "cannot sync updater destination directory"); } } [[nodiscard]] std::vector directoryEntries(const int descriptor, const std::size_t maximumEntries) { const int duplicate = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); if (duplicate < 0) { throw UpdateError{ systemError("cannot duplicate updater directory")}; } Directory directory{::fdopendir(duplicate)}; if (!directory) { ::close(duplicate); throw UpdateError{ systemError("cannot enumerate updater directory")}; } std::vector result; errno = 0; while (const dirent* entry = ::readdir(directory.get())) { const std::string_view name{entry->d_name}; if (name != "." && name != "..") { if (result.size() >= maximumEntries) { throw UpdateError{ "updater directory contains too many entries"}; } result.emplace_back(name); } errno = 0; } if (errno != 0) { throw UpdateError{ systemError("cannot enumerate updater directory")}; } return result; } void appendHistory(const UpdateDirectories& directories, const std::string_view operation, const std::string_view result, const std::string_view detail) { const FileDescriptor descriptor{::openat( directories.updates(), "history.jsonl", O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0640)}; if (descriptor.get() < 0) { throw UpdateError{systemError("cannot open update history")}; } struct stat metadata{}; if (::fstat(descriptor.get(), &metadata) != 0 || !S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { throw UpdateError{ "update history is not a singly linked regular file"}; } if (::fchmod(descriptor.get(), 0640) != 0) { throw UpdateError{systemError("cannot set update history mode")}; } const std::string record = "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"operation\":\"" + jsonEscape(operation) + "\",\"result\":\"" + jsonEscape(result) + "\",\"detail\":\"" + jsonEscape(detail) + "\"}\n"; std::size_t offset{}; while (offset < record.size()) { const auto written = ::write(descriptor.get(), record.data() + offset, record.size() - offset); if (written < 0) { if (errno == EINTR) { continue; } throw UpdateError{systemError("cannot write update history")}; } if (written == 0) { throw UpdateError{"short write while appending update history"}; } offset += static_cast(written); } if (::fsync(descriptor.get()) != 0) { throw UpdateError{systemError("cannot sync update history")}; } } struct ParsedArguments { fs::path root; std::string command; std::vector values; }; [[nodiscard]] fs::path inferredRoot(const char* executable) { std::error_code error; const fs::path resolved = fs::canonical(executable, error); if (error || resolved.parent_path().filename() != "bin") { throw UpdateError{"--root is required when the updater is not " "installed under bin/"}; } const fs::path release = resolved.parent_path().parent_path(); if (release.parent_path().filename() != "versions") { throw UpdateError{ "--root is required outside a versioned Echoion installation"}; } return release.parent_path().parent_path(); } [[nodiscard]] ParsedArguments parseArguments(const int argc, char** argv) { ParsedArguments result; int index{1}; if (index + 1 < argc && std::string_view{argv[index]} == "--root") { result.root = argv[index + 1]; index += 2; } else { result.root = inferredRoot(argv[0]); } if (index >= argc) { throw UpdateError{"a command is required"}; } result.command = argv[index++]; for (; index < argc; ++index) { result.values.emplace_back(argv[index]); } result.root = canonicalDirectory(result.root, "installation root"); return result; } [[nodiscard]] std::optional optionValue(const std::vector& values, const std::string_view option) { std::optional result; for (std::size_t index{}; index < values.size(); ++index) { if (values[index] != option) { continue; } if (index + 1U >= values.size() || result.has_value()) { throw UpdateError{"option requires one value: " + std::string{option}}; } result = values[index + 1U]; ++index; } return result; } void ensureOnlyOptions(const std::vector& values, const std::vector& allowed) { for (std::size_t index{}; index < values.size();) { const auto iterator = std::ranges::find(allowed, values[index]); if (iterator == allowed.end()) { throw UpdateError{"unknown argument: " + values[index]}; } if (index + 1U >= values.size()) { throw UpdateError{"missing value for argument: " + values[index]}; } index += 2U; } } void status(const fs::path& root, const bool json) { const std::string current = currentVersion(root); static_cast(validateRelease(root, current)); const auto versions = installedVersions(root); if (json) { std::cout << "{\"schemaVersion\":1,\"root\":\"" << jsonEscape(root.string()) << "\",\"current\":\"" << jsonEscape(current) << "\",\"versions\":["; for (std::size_t index{}; index < versions.size(); ++index) { if (index != 0U) { std::cout << ','; } std::cout << '"' << jsonEscape(versions[index]) << '"'; } std::cout << "]}\n"; return; } std::cout << "Root: " << root << "\nCurrent: " << current << "\nInstalled:"; for (const auto& version : versions) { std::cout << "\n " << version; } std::cout << '\n'; } void activateCurrent(const fs::path& root, const std::string_view selected) { const fs::path temporary = root / (".current." + std::to_string(::getpid()) + "." + requestId()); std::error_code error; fs::create_symlink(fs::path{"versions"} / selected, temporary, error); if (error) { throw UpdateError{"cannot create replacement current link: " + error.message()}; } fs::rename(temporary, root / "current", error); if (error) { fs::remove(temporary); throw UpdateError{"cannot publish replacement current link: " + error.message()}; } syncDirectory(root); } void updateInstallRecords(const fs::path& root, const std::string_view version) { const fs::path legacyPath = root / ".echoion-install"; const std::string oldLegacy = readRegularFileNoFollow(legacyPath, 1024U * 1024U); std::istringstream input{oldLegacy}; std::ostringstream legacyOutput; std::string line; std::size_t replacements{}; while (std::getline(input, line)) { if (line.starts_with("version=")) { legacyOutput << "version=" << version << '\n'; ++replacements; } else { legacyOutput << line << '\n'; } } if (replacements != 1U) { throw UpdateError{"install record has no unique version field"}; } const fs::path jsonPath = root / "install.json"; std::optional oldJson; std::optional newJson; if (fs::exists(jsonPath)) { oldJson = readRegularFileNoFollow(jsonPath, 1024U * 1024U); static const std::regex versionPattern{ R"(("version"[[:space:]]*:[[:space:]]*")[A-Za-z0-9._-]+("))"}; const auto begin = std::sregex_iterator{ oldJson->begin(), oldJson->end(), versionPattern}; const auto end = std::sregex_iterator{}; if (std::distance(begin, end) != 1) { throw UpdateError{ "public install record has no unique version field"}; } std::smatch match; if (!std::regex_search(*oldJson, match, versionPattern)) { throw UpdateError{ "cannot locate public install record version"}; } newJson = match.prefix().str() + match.str(1) + std::string{version} + match.str(2) + match.suffix().str(); } atomicWrite(legacyPath, legacyOutput.str()); try { if (newJson.has_value()) { atomicWrite(jsonPath, *newJson); } } catch (...) { atomicWrite(legacyPath, oldLegacy); throw; } } [[nodiscard]] Void::Semver::Version parseRuntimeVersion(const std::string_view version) { auto parsed = Void::Semver::parse_strict(version); if (!parsed.has_value() || parsed->to_string() != version) { throw UpdateError{"runtime version is not canonical SemVer: " + std::string{version}}; } return std::move(*parsed); } void recordRuntimeHealthy(const fs::path& root, const std::string_view version) { Void::Update::VersionStore store{root}; if (auto recorded = store.recordHealthy(parseRuntimeVersion(version)); !recorded) { throw UpdateError{"cannot record healthy runtime version: " + recorded.error().message()}; } } void recordRuntimeFailed(const fs::path& root, const std::string_view version) { Void::Update::VersionStore store{root}; if (auto recorded = store.recordFailed(parseRuntimeVersion(version)); !recorded) { throw UpdateError{"cannot record failed runtime version: " + recorded.error().message()}; } } [[nodiscard]] std::vector healthyRuntimeVersions(const fs::path& root) { Void::Update::VersionStore store{root}; auto healthy = store.healthyPublishedVersions(); if (!healthy) { throw UpdateError{"cannot read healthy runtime versions: " + healthy.error().message()}; } std::vector result; result.reserve(healthy->size()); std::ranges::transform(*healthy, std::back_inserter(result), [](const Void::Semver::Version& version) { return version.to_string(); }); return result; } void requireHealthyRuntime(const fs::path& root, const std::string_view version) { const auto healthy = healthyRuntimeVersions(root); if (std::ranges::find(healthy, version) == healthy.end()) { throw UpdateError{"requested runtime is not recorded healthy: " + std::string{version}}; } } void pruneRuntimeVersions(const fs::path& root, const std::uint32_t retainHealthyVersions) { Void::Update::VersionStore store{root}; if (auto pruned = store.prune(retainHealthyVersions); !pruned) { throw UpdateError{"cannot prune retained runtime versions: " + pruned.error().message()}; } } void writeActivationHandoff(const fs::path& root, UpdateDirectories& directories, const std::string_view version, const std::string_view previousVersion, const std::string_view state, const std::uint32_t retainHealthyVersions, const std::string_view failedVersion = {}) { const std::string body = "{\n \"schemaVersion\": 1,\n \"state\": \"" + jsonEscape(state) + "\",\n \"version\": \"" + jsonEscape(version) + "\",\n \"previousVersion\": \"" + jsonEscape(previousVersion) + "\",\n \"retainHealthyVersions\": " + std::to_string(retainHealthyVersions) + ",\n \"manifestPath\": \"versions/" + jsonEscape(version) + "/manifest.json\",\n \"currentRoot\": \"" + jsonEscape(root.string()) + "\",\n \"updatedAt\": \"" + jsonEscape(nowUtc()) + "\"" + (failedVersion.empty() ? std::string{} : ",\n \"failedVersion\": \"" + jsonEscape(failedVersion) + "\"") + "\n}\n"; atomicWriteAt(directories.updates(), "activated-runtime.json", body, 0640); } [[nodiscard]] std::optional pendingRuntime(const UpdateDirectories& directories) { if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { return std::nullopt; } return Echoion::Updater::parsePendingRuntime( readRegularFileAt(directories.updates(), "pending-runtime.json", kMaximumRequestBytes)); } [[nodiscard]] std::chrono::system_clock::time_point parseUtcTimestamp(const std::string_view value) { if (value.size() != 20U || value.back() != 'Z') { throw UpdateError{"pending runtime activation time is invalid"}; } std::tm utc{}; std::istringstream input{std::string{value}}; input >> std::get_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); if (!input || input.peek() != std::char_traits::eof()) { throw UpdateError{"pending runtime activation time is invalid"}; } const std::time_t timestamp = ::timegm(&utc); if (timestamp < 0) { throw UpdateError{ "pending runtime activation time is out of range"}; } return std::chrono::system_clock::from_time_t(timestamp); } [[nodiscard]] bool healthGraceExpired(const Echoion::Updater::PendingRuntime& pending) { return std::chrono::system_clock::now() >= parseUtcTimestamp(pending.activatedAt) + kRuntimeHealthGrace; } void writePendingRuntime( UpdateDirectories& directories, const Echoion::Updater::RuntimeActivation& activation, const std::string_view previousVersion) { const std::string body = "{\n \"schemaVersion\": 1,\n \"state\": \"pending\",\n" " \"candidateId\": \"" + jsonEscape(activation.stagingId) + "\",\n \"version\": \"" + jsonEscape(activation.version) + "\",\n \"previousVersion\": \"" + jsonEscape(previousVersion) + "\",\n \"manifestSha256\": \"" + jsonEscape(activation.manifestSha256) + "\",\n \"retainHealthyVersions\": " + std::to_string(activation.retainHealthyVersions) + ",\n \"manifestPath\": \"versions/" + jsonEscape(activation.version) + "/manifest.json\",\n \"activatedAt\": \"" + jsonEscape(nowUtc()) + "\"\n}\n"; atomicWriteAt(directories.updates(), "pending-runtime.json", body, 0640); } [[nodiscard]] std::optional archivePendingRuntime(UpdateDirectories& directories, const std::string_view archiveName) { if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { throw UpdateError{"pending runtime journal disappeared"}; } requireLeafName(archiveName); const std::string ownedArchive{archiveName}; if (::renameat(directories.updates(), "pending-runtime.json", directories.updates(), ownedArchive.c_str()) != 0) { throw UpdateError{ systemError("cannot archive pending runtime journal")}; } if (::fsync(directories.updates()) != 0) { return systemError("cannot sync archived runtime journal"); } return std::nullopt; } void writeRuntimeStatus(UpdateDirectories& directories, const std::string_view version, const std::string_view state, const std::string_view detail = {}) { const std::string body = "{\n \"schemaVersion\": 1,\n \"checkedAt\": \"" + jsonEscape(nowUtc()) + "\",\n \"current\": \"" + jsonEscape(version) + "\",\n \"state\": \"" + jsonEscape(state) + "\"" + (detail.empty() ? std::string{} : ",\n \"detail\": \"" + jsonEscape(detail) + "\"") + "\n}\n"; atomicWriteAt(directories.updates(), "status.json", body, 0640); } [[nodiscard]] std::optional existingActivationHandoff(const UpdateDirectories& directories) { if (!fileExistsAt(directories.updates(), "activated-runtime.json")) { return std::nullopt; } return readRegularFileAt(directories.updates(), "activated-runtime.json", kMaximumRequestBytes); } void restoreActivationHandoff(UpdateDirectories& directories, const std::optional& previous) { if (previous.has_value()) { atomicWriteAt(directories.updates(), "activated-runtime.json", *previous, 0640); } else if (fileExistsAt(directories.updates(), "activated-runtime.json")) { unlinkFileAt(directories.updates(), "activated-runtime.json"); } } void selectRuntime(const fs::path& root, UpdateDirectories& directories, const std::string& selected, const std::string_view operation, const std::uint32_t retainHealthyVersions) { const std::string oldVersion = currentVersion(root); if (selected == oldVersion) { throw UpdateError{"requested runtime is already current"}; } requireHealthyRuntime(root, selected); const fs::path release = validateRelease(root, selected); Echoion::Updater::validateRelease(release, selected); const auto oldHandoff = existingActivationHandoff(directories); recordRuntimeHealthy(root, oldVersion); activateCurrent(root, selected); try { updateInstallRecords(root, selected); writeActivationHandoff(root, directories, selected, oldVersion, "rolled-back", retainHealthyVersions); } catch (...) { activateCurrent(root, oldVersion); updateInstallRecords(root, oldVersion); restoreActivationHandoff(directories, oldHandoff); throw; } std::vector warnings; try { appendHistory(directories, operation, "activated", oldVersion + " -> " + selected); } catch (const std::exception& error) { warnings.emplace_back(std::string{"update history: "} + error.what()); } try { recordRuntimeHealthy(root, selected); } catch (const std::exception& error) { warnings.emplace_back(std::string{"healthy runtime history: "} + error.what()); } try { pruneRuntimeVersions(root, retainHealthyVersions); } catch (const std::exception& error) { warnings.emplace_back(std::string{"version retention: "} + error.what()); } std::cout << "Activated " << selected << ". The service was not started or restarted.\n"; for (const auto& warning : warnings) { std::cerr << kProgramName << ": warning: runtime " << selected << " was selected, but " << warning << '\n'; } } void rollback(const fs::path& root, const std::optional& requested, const std::uint32_t retainHealthyVersions, const std::string_view operation = "rollback") { UpdateDirectories directories{root}; PrefixLock lock{root}; if (pendingRuntime(directories).has_value()) { throw UpdateError{"a runtime activation is awaiting health " "confirmation; run reconcile first"}; } const std::string oldVersion = currentVersion(root); std::string selected; if (requested.has_value()) { selected = *requested; } else { for (const auto& version : healthyRuntimeVersions(root)) { if (version != oldVersion) { selected = version; break; } } } if (selected.empty()) { throw UpdateError{ "no different healthy installed version is available"}; } selectRuntime(root, directories, selected, operation, retainHealthyVersions); } [[nodiscard]] std::uint32_t retainedVersions(const std::vector& values) { const auto retainValue = optionValue(values, "--retain"); if (!retainValue.has_value()) { return kDefaultRetainedVersions; } std::uint32_t retain{}; const auto parsed = std::from_chars(retainValue->data(), retainValue->data() + retainValue->size(), retain); if (parsed.ec != std::errc{} || parsed.ptr != retainValue->data() + retainValue->size() || retain < 1U || retain > 10U) { throw UpdateError{"--retain must be an integer from 1 to 10"}; } return retain; } void queueRequest(const fs::path& root, const std::string_view operation, const std::vector& values) { static const std::vector operations{ "activate-runtime", "rollback-runtime", "commit-runtime"}; if (std::ranges::find(operations, operation) == operations.end()) { throw UpdateError{"unsupported request operation"}; } const std::vector allowed{ "--version", "--origin", "--staging", "--manifest-sha256", "--retain"}; ensureOnlyOptions(values, allowed); const auto version = optionValue(values, "--version"); const auto origin = optionValue(values, "--origin"); const auto staging = optionValue(values, "--staging"); const auto manifestDigest = optionValue(values, "--manifest-sha256"); const std::uint32_t retain = retainedVersions(values); if (operation == "activate-runtime" && (!staging.has_value() || !version.has_value() || !manifestDigest.has_value())) { throw UpdateError{"activate-runtime requires --staging, --version, " "and --manifest-sha256"}; } if ((operation == "rollback-runtime" || operation == "commit-runtime") && !version.has_value()) { throw UpdateError{std::string{operation} + " requires --version"}; } for (const auto* value : {&version, &origin, &staging}) { if (value->has_value() && !safeIdentifier(**value)) { throw UpdateError{"request contains an unsafe identifier"}; } } if (manifestDigest.has_value() && !safeDigest(*manifestDigest)) { throw UpdateError{"manifest digest must be lowercase SHA-256"}; } if ((operation == "rollback-runtime" || operation == "commit-runtime") && (staging.has_value() || manifestDigest.has_value())) { throw UpdateError{std::string{operation} + " has activation-only fields"}; } if (operation != "activate-runtime" && (staging.has_value() || manifestDigest.has_value())) { throw UpdateError{"request has activation-only fields"}; } const std::string id = requestId(); std::ostringstream output; output << "{\n \"schemaVersion\": 1,\n \"id\": \"" << id << "\",\n \"createdAt\": \"" << jsonEscape(nowUtc()) << "\",\n \"operation\": \"" << operation << '"'; const auto emit = [&output](const std::string_view key, const std::optional& value) { if (value.has_value()) { output << ",\n \"" << key << "\": \"" << jsonEscape(*value) << '"'; } }; emit("version", version); emit("origin", origin); emit("stagingId", staging); emit("manifestSha256", manifestDigest); output << ",\n \"retainHealthyVersions\": " << retain; output << "\n}\n"; if (output.str().size() > kMaximumRequestBytes) { throw UpdateError{"update request is too large"}; } UpdateDirectories directories{root}; const std::string filename = id + ".json"; atomicWriteAt(directories.privilegedRequests(), filename, output.str(), 0640); appendHistory(directories, operation, "queued", id); std::cout << (directories.path() / "privileged-requests" / filename).string() << '\n'; } [[nodiscard]] Echoion::Updater::RuntimeActivation activationOptions(const std::vector& values) { ensureOnlyOptions( values, {"--staging", "--version", "--manifest-sha256", "--retain"}); const auto staging = optionValue(values, "--staging"); const auto version = optionValue(values, "--version"); const auto digest = optionValue(values, "--manifest-sha256"); if (!staging.has_value() || !version.has_value() || !digest.has_value() || !safeIdentifier(*staging) || !safeIdentifier(*version) || !safeDigest(*digest)) { throw UpdateError{ "activate-runtime requires safe --staging, --version, and " "--manifest-sha256 values"}; } return { .stagingId = *staging, .version = *version, .manifestSha256 = *digest, .retainHealthyVersions = retainedVersions(values), }; } void activateRuntime(const fs::path& root, UpdateDirectories& directories, const Echoion::Updater::RuntimeActivation& activation) { PrefixLock lock{root}; if (pendingRuntime(directories).has_value()) { throw UpdateError{ "a runtime activation is already awaiting health confirmation"}; } const FileDescriptor source{ ::openat(directories.staged(), activation.stagingId.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; struct stat stagedMetadata{}; struct stat sourceMetadata{}; if (source.get() < 0 || ::fstat(directories.staged(), &stagedMetadata) != 0 || ::fstat(source.get(), &sourceMetadata) != 0 || !S_ISDIR(sourceMetadata.st_mode) || sourceMetadata.st_uid != stagedMetadata.st_uid) { throw UpdateError{ "staged runtime is not a pinned, correctly owned directory"}; } const fs::path versions = canonicalDirectory(root / "versions", "versions directory"); const fs::path destination = versions / activation.version; if (fs::exists(destination) || fs::is_symlink(fs::symlink_status(destination))) { throw UpdateError{"requested runtime version is already installed"}; } const fs::path incoming = versions / (".incoming-" + activation.version + "-" + requestId()); const std::string oldVersion = currentVersion(root); const auto oldHandoff = existingActivationHandoff(directories); recordRuntimeHealthy(root, oldVersion); bool published{false}; bool currentChanged{false}; bool pendingWritten{false}; try { Echoion::Updater::copyAndValidateRelease(source.get(), incoming, activation); std::error_code error; fs::rename(incoming, destination, error); if (error) { throw UpdateError{"cannot publish runtime version: " + error.message()}; } published = true; syncDirectory(versions); writePendingRuntime(directories, activation, oldVersion); pendingWritten = true; activateCurrent(root, activation.version); currentChanged = true; updateInstallRecords(root, activation.version); writeActivationHandoff(root, directories, activation.version, oldVersion, "pending", activation.retainHealthyVersions); writeRuntimeStatus(directories, activation.version, "pending-health", "awaiting daemon health confirmation"); } catch (...) { std::error_code ignored; bool mayRemovePublished = !currentChanged; if (currentChanged) { try { activateCurrent(root, oldVersion); updateInstallRecords(root, oldVersion); restoreActivationHandoff(directories, oldHandoff); mayRemovePublished = true; } catch (...) { // Preserve the original failure. Reconcile repairs record // drift. } } if (pendingWritten && mayRemovePublished) { try { unlinkFileAt(directories.updates(), "pending-runtime.json"); } catch (const std::exception&) { // Preserve the activation error. Reconciliation will // process any journal that could not be removed. } } if (published && mayRemovePublished) { fs::remove_all(destination, ignored); syncDirectory(versions); } else if (!published) { fs::remove_all(incoming, ignored); } throw; } std::vector warnings; try { Echoion::Updater::removeReleaseTreeAt(directories.staged(), activation.stagingId); } catch (const std::exception& error) { warnings.emplace_back(std::string{"staged cleanup: "} + error.what()); } try { appendHistory(directories, "activate-runtime", "activated", oldVersion + " -> " + activation.version); } catch (const std::exception& error) { warnings.emplace_back(std::string{"update history: "} + error.what()); } std::cout << "Activated " << activation.version << " pending health confirmation. The service was not started or " "restarted.\n"; for (const auto& warning : warnings) { std::cerr << kProgramName << ": warning: runtime " << activation.version << " was activated, but " << warning << '\n'; } } void commitRuntime(const fs::path& root, UpdateDirectories& directories, const std::string& version) { if (!safeIdentifier(version)) { throw UpdateError{"unsafe runtime commit version"}; } PrefixLock lock{root}; const auto pending = pendingRuntime(directories); if (!pending.has_value()) { throw UpdateError{ "no runtime activation is awaiting health confirmation"}; } if (pending->version != version) { throw UpdateError{ "runtime health confirmation does not match the pending " "version"}; } if (currentVersion(root) != version) { throw UpdateError{ "current runtime does not match the pending activation"}; } const fs::path release = validateRelease(root, version); Echoion::Updater::validateRelease(release, version, pending->manifestSha256); updateInstallRecords(root, version); // Renaming the pending journal is the durable commit point. A later // status write failure must never make a health-confirmed runtime roll // back. std::vector warnings; if (auto warning = archivePendingRuntime(directories, "committed-runtime.json")) { warnings.push_back(std::move(*warning)); } const auto metadata = [&warnings](const std::string_view operation, auto&& function) { try { std::invoke(std::forward(function)); } catch (const std::exception& error) { warnings.emplace_back(std::string{operation} + ": " + error.what()); } }; metadata("activation handoff", [&] { writeActivationHandoff(root, directories, version, pending->previousVersion, "committed", pending->retainHealthyVersions); }); metadata("runtime status", [&] { writeRuntimeStatus(directories, version, "healthy", "daemon health confirmed"); }); metadata("update history", [&] { appendHistory(directories, "commit-runtime", "committed", version); }); metadata("healthy runtime history", [&] { recordRuntimeHealthy(root, version); }); metadata("version retention", [&] { pruneRuntimeVersions(root, pending->retainHealthyVersions); }); std::cout << "Committed healthy runtime " << version << ".\n"; for (const auto& warning : warnings) { std::cerr << kProgramName << ": warning: runtime " << version << " was committed, but " << warning << '\n'; } } void rollbackPendingRuntime(const fs::path& root, UpdateDirectories& directories, const std::string_view reason) { PrefixLock lock{root}; const auto pending = pendingRuntime(directories); if (!pending.has_value()) { return; } const fs::path previousRelease = validateRelease(root, pending->previousVersion); Echoion::Updater::validateRelease(previousRelease, pending->previousVersion); const std::string selected = currentVersion(root); if (selected != pending->version && selected != pending->previousVersion) { throw UpdateError{ "current runtime diverged from the pending activation journal"}; } const auto oldHandoff = existingActivationHandoff(directories); const bool currentChanged = selected == pending->version; std::vector warnings; try { if (currentChanged) { activateCurrent(root, pending->previousVersion); } updateInstallRecords(root, pending->previousVersion); const std::string failure = "{\n \"schemaVersion\": 1,\n \"candidateId\": \"" + jsonEscape(pending->candidateId) + "\",\n \"version\": \"" + jsonEscape(pending->version) + "\",\n \"previousVersion\": \"" + jsonEscape(pending->previousVersion) + "\",\n \"manifestPath\": \"versions/" + jsonEscape(pending->version) + "/manifest.json\",\n \"failedAt\": \"" + jsonEscape(nowUtc()) + "\",\n \"reason\": \"" + jsonEscape(reason) + "\"\n}\n"; atomicWriteAt(directories.updates(), "failed-runtime.json", failure, 0640); writeActivationHandoff(root, directories, pending->previousVersion, pending->version, "rolled-back", pending->retainHealthyVersions, pending->version); writeRuntimeStatus(directories, pending->previousVersion, "rolled-back", reason); if (auto warning = archivePendingRuntime( directories, "failed-pending-runtime.json")) { warnings.push_back(std::move(*warning)); } } catch (...) { if (currentChanged) { try { activateCurrent(root, pending->version); updateInstallRecords(root, pending->version); restoreActivationHandoff(directories, oldHandoff); } catch (...) { // Keep the pending journal for the next reconciliation // attempt. } } else { try { restoreActivationHandoff(directories, oldHandoff); } catch (...) { // Keep the pending journal for the next reconciliation // attempt. } } throw; } try { appendHistory(directories, "activate-runtime", "rolled-back", pending->version + " -> " + pending->previousVersion + ": " + std::string{reason}); } catch (const std::exception& error) { warnings.emplace_back(std::string{"update history: "} + error.what()); } try { recordRuntimeFailed(root, pending->version); } catch (const std::exception& error) { warnings.emplace_back(std::string{"failed runtime history: "} + error.what()); } try { recordRuntimeHealthy(root, pending->previousVersion); } catch (const std::exception& error) { warnings.emplace_back(std::string{"healthy runtime history: "} + error.what()); } try { pruneRuntimeVersions(root, pending->retainHealthyVersions); } catch (const std::exception& error) { warnings.emplace_back(std::string{"version retention: "} + error.what()); } std::cout << "Rolled back unconfirmed runtime " << pending->version << " to " << pending->previousVersion << ".\n"; for (const auto& warning : warnings) { std::cerr << kProgramName << ": warning: runtime rollback committed, but " << warning << '\n'; } } void rollbackRuntime(const fs::path& root, UpdateDirectories& directories, const std::string& version, const std::uint32_t retainHealthyVersions) { if (!safeIdentifier(version)) { throw UpdateError{"unsafe rollback version"}; } PrefixLock lock{root}; if (pendingRuntime(directories).has_value()) { throw UpdateError{"a runtime activation is awaiting health " "confirmation; run reconcile first"}; } if (currentVersion(root) == version) { requireHealthyRuntime(root, version); const fs::path release = validateRelease(root, version); Echoion::Updater::validateRelease(release, version); recordRuntimeHealthy(root, version); pruneRuntimeVersions(root, retainHealthyVersions); return; } selectRuntime(root, directories, version, "rollback-runtime", retainHealthyVersions); } [[nodiscard]] bool safeRequestName(const std::string_view name) { const fs::path path{name}; return path.extension() == ".json" && safeIdentifier(path.stem().string()) && path.filename() == path && name.size() <= 70U; } void consumeRequests(const fs::path& root) { constexpr std::size_t kMaximumRequestsPerRun{32U}; constexpr std::size_t kMaximumQueuedEntries{1024U}; UpdateDirectories directories{root}; std::vector requests; for (const auto& name : directoryEntries( directories.privilegedRequests(), kMaximumQueuedEntries)) { if (requests.size() >= kMaximumRequestsPerRun) { break; } struct stat metadata{}; if (safeRequestName(name) && ::fstatat(directories.privilegedRequests(), name.c_str(), &metadata, AT_SYMLINK_NOFOLLOW) == 0 && S_ISREG(metadata.st_mode) && metadata.st_nlink == 1) { requests.push_back(name); } } std::ranges::sort(requests); if (const auto pending = pendingRuntime(directories); pending.has_value()) { const auto matchingCommit = std::ranges::find_if( requests, [&pending, &directories](const std::string& request) { try { const auto parsed = Echoion::Updater::parsePrivilegedRequest( readRegularFileAt( directories.privilegedRequests(), request, kMaximumRequestBytes)); const auto* commit = std::get_if( &parsed); return commit != nullptr && commit->version == pending->version; } catch (const std::exception&) { return false; } }); if (matchingCommit == requests.end() && healthGraceExpired(*pending)) { rollbackPendingRuntime( root, directories, "daemon health confirmation was not received before the " "durable grace deadline"); } else { if (matchingCommit != requests.end()) { std::rotate(requests.begin(), matchingCommit, std::next(matchingCommit)); } } } std::size_t failures{}; for (const std::string& request : requests) { std::string bytes; bool claimed{false}; try { moveFileAt(directories.privilegedRequests(), request, directories.processed(), request); claimed = true; bytes = readRegularFileAt(directories.processed(), request, kMaximumRequestBytes); const auto operation = Echoion::Updater::parsePrivilegedRequest(bytes); std::visit( [&root, &directories](const auto& value) { using Request = std::decay_t; if constexpr (std::same_as) { activateRuntime(root, directories, value); } else if constexpr ( std::same_as) { rollbackRuntime(root, directories, value.version, value.retainHealthyVersions); } else { commitRuntime(root, directories, value.version); } }, operation); } catch (const std::exception& error) { ++failures; std::cerr << kProgramName << ": rejected privileged request " << request << ": " << error.what() << '\n'; if (claimed && fileExistsAt(directories.processed(), request)) { moveFileAt(directories.processed(), request, directories.rejected(), request); } const std::string errorRecord = "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"error\":\"" + jsonEscape(error.what()) + "\"}\n"; atomicWriteAt(directories.rejected(), request + ".error.json", errorRecord, 0640); appendHistory(directories, "consume", "rejected", request); } } if (failures != 0U) { throw UpdateError{std::to_string(failures) + " privileged update request(s) were rejected"}; } std::cout << "Consumed " << requests.size() << " privileged request(s).\n"; } void reconcile(const fs::path& root) { UpdateDirectories directories{root}; const auto unconfirmed = pendingRuntime(directories); if (unconfirmed.has_value()) { rollbackPendingRuntime( root, directories, "reconciliation found an unconfirmed runtime"); } PrefixLock lock{root}; const std::string version = currentVersion(root); const fs::path release = validateRelease(root, version); Echoion::Updater::validateRelease(release, version); updateInstallRecords(root, version); const std::string_view state = unconfirmed.has_value() ? "rolled-back" : "ready"; writeRuntimeStatus( directories, version, state, unconfirmed.has_value() ? "unconfirmed runtime was restored to the previous version" : std::string_view{}); appendHistory(directories, "reconcile", state, version); std::cout << "Installation is consistent at " << version << ".\n"; } void printUsage() { std::cout << "Usage: echoion-updater [--root PATH] COMMAND [OPTIONS]\n\n" "Commands:\n" " status [--json] inspect installed releases\n" " request OPERATION [...] queue a privileged runtime " "request\n" " activate-runtime --staging ID --version V --manifest-sha256 " "HEX [--retain N]\n" " publish a local staged " "runtime\n" " commit-runtime --version V [--retain N]\n" " confirm a healthy " "activated " "runtime\n" " rollback-runtime --version V [--retain N]\n" " select a validated local " "runtime\n" " consume consume bounded privileged " " rollback [--to VERSION] [--retain N]\n" " atomically select a local " "release\n" " reconcile validate and journal current " "state\n\n" "The helper never downloads artifacts and never starts Echoion. " "Network and\n" "feed work is handed to the daemon through typed request " "files.\n"; } } // namespace int main(const int argc, char** argv) { try { if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) { printUsage(); return 0; } const ParsedArguments arguments = parseArguments(argc, argv); if (arguments.command == "status") { if (arguments.values.empty()) { status(arguments.root, false); } else if (arguments.values == std::vector{"--json"}) { status(arguments.root, true); } else { throw UpdateError{"status accepts only --json"}; } } else if (arguments.command == "rollback") { ensureOnlyOptions(arguments.values, {"--to", "--retain"}); rollback(arguments.root, optionValue(arguments.values, "--to"), retainedVersions(arguments.values)); } else if (arguments.command == "activate-runtime") { UpdateDirectories directories{arguments.root}; activateRuntime(arguments.root, directories, activationOptions(arguments.values)); } else if (arguments.command == "rollback-runtime") { ensureOnlyOptions(arguments.values, {"--version", "--retain"}); const auto version = optionValue(arguments.values, "--version"); if (!version.has_value()) { throw UpdateError{"rollback-runtime requires --version"}; } const auto retain = retainedVersions(arguments.values); UpdateDirectories directories{arguments.root}; rollbackRuntime(arguments.root, directories, *version, retain); } else if (arguments.command == "commit-runtime") { ensureOnlyOptions(arguments.values, {"--version", "--retain"}); const auto version = optionValue(arguments.values, "--version"); if (!version.has_value()) { throw UpdateError{"commit-runtime requires --version"}; } static_cast(retainedVersions(arguments.values)); UpdateDirectories directories{arguments.root}; commitRuntime(arguments.root, directories, *version); } else if (arguments.command == "consume") { if (!arguments.values.empty()) { throw UpdateError{"consume accepts no arguments"}; } consumeRequests(arguments.root); } else if (arguments.command == "reconcile") { if (!arguments.values.empty()) { throw UpdateError{"reconcile accepts no arguments"}; } reconcile(arguments.root); } else if (arguments.command == "request") { if (arguments.values.empty()) { throw UpdateError{"request requires an operation"}; } queueRequest( arguments.root, arguments.values.front(), {arguments.values.begin() + 1, arguments.values.end()}); } else { throw UpdateError{"unknown command: " + arguments.command}; } return 0; } catch (const UpdateError& error) { std::cerr << kProgramName << ": " << error.what() << '\n'; return 2; } catch (const std::exception& error) { std::cerr << kProgramName << ": unexpected error: " << error.what() << '\n'; return 1; } }