Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-16 19:59:57 +03:00
1 parent 8aa968eb9f
commit 11850b1a8d
11 files changed
+1569 -160

No files matched your search

+580 -57
View File
@@ -5,123 +5,646 @@
#include <openssl/evp.h>
#include <array>
#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <memory>
#include <ranges>
#include <sstream>
#include <tuple>
#include <unordered_set>
namespace Echoion::Standalone
{
namespace
{
constexpr auto kExecutablePermissions =
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_exec;
constexpr auto kUnsafeWritablePermissions =
std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
constexpr std::array<std::string_view, 4> kImmutableRoots{
"bin", "lib", "service", "share"};
constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0;
Api::Result<std::string> sha256(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
if (!input) {
return Api::fail(Api::ErrorCode::NotFound,
"release artifact not found: " + path.string());
"release artifact not found: " +
path.string());
}
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
using Context =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Context context(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
if (!context || EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) {
if (!context ||
EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot initialize SHA-256");
"cannot initialize SHA-256");
}
std::array<char, 64 * 1024> buffer{};
while (input) {
input.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
if (const auto count = input.gcount(); count > 0 &&
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
if (const auto count = input.gcount();
count > 0 &&
EVP_DigestUpdate(context.get(), buffer.data(),
static_cast<std::size_t>(count)) != 1) {
static_cast<std::size_t>(count)) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot hash release artifact");
"cannot hash release artifact");
}
}
std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
unsigned int size = 0;
unsigned int size{};
if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot finalize release hash");
"cannot finalize release hash");
}
std::ostringstream output;
output << std::hex << std::setfill('0');
for (unsigned int index = 0; index < size; ++index) {
output << std::setw(2) << static_cast<unsigned int>(digest[index]);
output << std::setw(2)
<< static_cast<unsigned int>(digest[index]);
}
return output.str();
}
}
bool isSafeRelativePath(const std::filesystem::path& path)
{
if (path.empty() || path.is_absolute() || path.has_root_name() ||
path.filename().empty() ||
std::ranges::contains(path.native(), '\0')) {
return false;
}
if (path.generic_string() !=
path.lexically_normal().generic_string()) {
return false;
}
return std::ranges::none_of(path, [](const auto& component) {
return component == "." || component == "..";
});
}
bool isSha256(std::string_view value)
{
return value.size() == 64 &&
std::ranges::all_of(
value, [](const unsigned char character) {
return (character >= '0' && character <= '9') ||
(character >= 'a' && character <= 'f');
});
}
std::optional<std::filesystem::perms> parseMode(std::string_view value)
{
if (value.size() != 4 || value.front() != '0' ||
!std::ranges::all_of(value.substr(1), [](const char character) {
return character >= '0' && character <= '7';
})) {
return std::nullopt;
}
unsigned int result{};
for (const char character : value.substr(1)) {
result =
result * 8U + static_cast<unsigned int>(character - '0');
}
return static_cast<std::filesystem::perms>(result);
}
std::optional<std::uintmax_t> parseSize(const Void::Json::Value& entry)
{
const auto* value = entry.find("size");
if (!value || !value->is_number()) {
return std::nullopt;
}
const double number = value->as_number();
if (!std::isfinite(number) || number < 0.0 ||
number > kMaximumExactJsonInteger ||
std::trunc(number) != number) {
return std::nullopt;
}
return static_cast<std::uintmax_t>(number);
}
std::filesystem::path
normalizedAbsolute(const std::filesystem::path& path)
{
std::error_code error;
auto absolute = std::filesystem::absolute(path, error);
return (error ? path : absolute).lexically_normal();
}
bool isWithin(const std::filesystem::path& root,
const std::filesystem::path& candidate)
{
const auto relative = candidate.lexically_relative(root);
return !relative.empty() && !relative.is_absolute() &&
std::ranges::none_of(relative, [](const auto& component) {
return component == "..";
});
}
bool hasUnsafeWritablePermissions(
const std::filesystem::file_status& status)
{
return (status.permissions() & kUnsafeWritablePermissions) !=
std::filesystem::perms::none;
}
std::optional<std::filesystem::path>
relativeToPayload(const std::filesystem::path& path,
const std::filesystem::path& prefix)
{
if (prefix.empty()) {
return path;
}
const auto relative = path.lexically_relative(prefix);
if (!isSafeRelativePath(relative)) {
return std::nullopt;
}
return relative;
}
bool isImmutablePayloadPath(const std::filesystem::path& path,
const std::filesystem::path& prefix)
{
const auto relative = relativeToPayload(path, prefix);
if (!relative || relative->empty()) {
return false;
}
return std::ranges::contains(kImmutableRoots,
relative->begin()->generic_string());
}
Api::Result<std::filesystem::path>
payloadPrefix(const ReleaseManifest& manifest)
{
const auto executable =
manifest.executable.lexically_relative(manifest.root);
if (!isSafeRelativePath(executable) ||
executable.filename() != "echoiond" ||
executable.parent_path().filename() != "bin") {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"v2 release executable must use the payload "
"bin/echoiond layout");
}
const auto prefix = executable.parent_path().parent_path();
const auto expectedCore =
(manifest.root / prefix / "lib" / "Echoion.ts")
.lexically_normal();
if (manifest.core.lexically_normal() != expectedCore) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"v2 release Core must use the payload "
"lib/Echoion.ts layout");
}
return prefix;
}
Api::Result<void>
validateImmutableCoverage(const ReleaseManifest& manifest)
{
auto prefix = payloadPrefix(manifest);
if (!prefix) {
return std::unexpected(prefix.error());
}
std::unordered_set<std::string> declared;
declared.reserve(manifest.files.size());
for (const auto& entry : manifest.files) {
if (!isImmutablePayloadPath(entry.path, *prefix)) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"release manifest entry is outside the immutable "
"payload roots: " +
entry.path.string());
}
declared.insert(entry.path.generic_string());
}
const auto payloadRoot = manifest.root / *prefix;
std::error_code payloadError;
const auto payloadStatus =
std::filesystem::symlink_status(payloadRoot, payloadError);
if (payloadError ||
payloadStatus.type() != std::filesystem::file_type::directory) {
return Api::fail(Api::ErrorCode::NotFound,
"immutable payload root is missing or has an "
"unexpected type: " +
payloadRoot.string());
}
if (hasUnsafeWritablePermissions(payloadStatus)) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
payloadRoot.string());
}
for (const auto name : kImmutableRoots) {
const auto directory = manifest.root / *prefix / name;
std::error_code error;
const auto rootStatus =
std::filesystem::symlink_status(directory, error);
if (error || rootStatus.type() !=
std::filesystem::file_type::directory) {
return Api::fail(
Api::ErrorCode::NotFound,
"immutable payload directory is missing or has an "
"unexpected type: " +
directory.string());
}
if (hasUnsafeWritablePermissions(rootStatus)) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
directory.string());
}
std::filesystem::recursive_directory_iterator iterator{
directory, std::filesystem::directory_options::none, error};
const std::filesystem::recursive_directory_iterator end;
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot inspect immutable payload directory: " +
directory.string());
}
while (iterator != end) {
const auto status = iterator->symlink_status(error);
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot inspect immutable payload entry: " +
iterator->path().string());
}
if (status.type() ==
std::filesystem::file_type::directory) {
if (hasUnsafeWritablePermissions(status)) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"immutable payload directory is group- or "
"world-writable: " +
iterator->path().string());
}
} else {
const auto relative =
iterator->path().lexically_relative(manifest.root);
if (status.type() !=
std::filesystem::file_type::regular &&
status.type() !=
std::filesystem::file_type::symlink) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"special file is not allowed in "
"immutable payload: " +
relative.string());
}
if (!declared.contains(relative.generic_string())) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"undeclared immutable payload entry: " +
relative.string());
}
}
iterator.increment(error);
if (error) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"cannot traverse immutable payload directory: " +
directory.string());
}
}
}
return {};
}
Api::Result<ReleaseManifest>
loadVersionOne(const Void::Json::Value& json,
const std::filesystem::path& root)
{
ReleaseManifest manifest;
manifest.root = root;
manifest.version = json.get_str("version");
const auto executableEntry =
std::filesystem::path(json.get_str("executable"));
const auto coreEntry = std::filesystem::path(json.get_str("core"));
if (!isSafeRelativePath(executableEntry) ||
!isSafeRelativePath(coreEntry)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release artifact paths must stay within the "
"manifest directory");
}
manifest.executable = root / executableEntry;
manifest.core = root / coreEntry;
if (const auto* hashes = json.find("sha256");
hashes && hashes->is_object()) {
manifest.executableSha256 = hashes->get_str("executable");
manifest.coreSha256 = hashes->get_str("core");
}
if (manifest.version.empty() ||
!isSha256(manifest.executableSha256) ||
!isSha256(manifest.coreSha256)) {
return Api::fail(Api::ErrorCode::ParseError,
"release manifest is missing version, "
"artifacts, or hashes");
}
return manifest;
}
Api::Result<ReleaseManifest>
loadVersionTwo(const Void::Json::Value& json,
const std::filesystem::path& root)
{
ReleaseManifest manifest;
manifest.schemaVersion = 2;
manifest.root = root;
manifest.version = json.get_str("version");
const auto executableEntry =
std::filesystem::path(json.get_str("executable"));
const auto coreEntry = std::filesystem::path(json.get_str("core"));
const auto* files = json.child_array("files");
if (manifest.version.empty() ||
!isSafeRelativePath(executableEntry) ||
!isSafeRelativePath(coreEntry) || !files ||
files->as_array().empty()) {
return Api::fail(Api::ErrorCode::ParseError,
"v2 release manifest is missing version, "
"artifacts, or files");
}
std::unordered_set<std::string> paths;
manifest.files.reserve(files->as_array().size());
for (const auto& value : files->as_array()) {
if (!value.is_object()) {
return Api::fail(Api::ErrorCode::ParseError,
"release file entries must be objects");
}
ReleaseFileEntry entry;
entry.path = value.get_str("path");
if (!isSafeRelativePath(entry.path)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release file path is absolute, "
"traversing, or not normalized");
}
if (!paths.insert(entry.path.generic_string()).second) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"duplicate release file path: " +
entry.path.string());
}
const auto type = value.get_str("type");
if (type == "file") {
entry.type = ReleaseFileType::Regular;
const auto size = parseSize(value);
const auto mode = parseMode(value.get_str("mode"));
entry.sha256 = value.get_str("sha256");
if (!size || !mode || !isSha256(entry.sha256) ||
value.has("target")) {
return Api::fail(Api::ErrorCode::ParseError,
"regular release file entry has "
"invalid metadata: " +
entry.path.string());
}
entry.size = *size;
entry.mode = *mode;
if ((entry.mode & kUnsafeWritablePermissions) !=
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release file is group- or "
"world-writable: " +
entry.path.string());
}
} else if (type == "symlink") {
entry.type = ReleaseFileType::Symlink;
entry.target = value.get_str("target");
if (!isSafeRelativePath(entry.target) ||
value.has("size") || value.has("sha256") ||
value.has("mode")) {
return Api::fail(
Api::ErrorCode::ParseError,
"symbolic link entry has invalid metadata: " +
entry.path.string());
}
} else {
return Api::fail(Api::ErrorCode::ParseError,
"unknown release file type: " + type);
}
manifest.files.push_back(std::move(entry));
}
const auto executable = std::ranges::find(
manifest.files, executableEntry, &ReleaseFileEntry::path);
const auto core = std::ranges::find(manifest.files, coreEntry,
&ReleaseFileEntry::path);
if (executable == manifest.files.end() ||
core == manifest.files.end() ||
executable->type != ReleaseFileType::Regular ||
core->type != ReleaseFileType::Regular) {
return Api::fail(Api::ErrorCode::ParseError,
"release executable and Core must reference "
"regular file entries");
}
if ((executable->mode & kExecutablePermissions) ==
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release executable entry is not executable");
}
manifest.executable = root / executableEntry;
manifest.core = root / coreEntry;
manifest.executableSha256 = executable->sha256;
manifest.coreSha256 = core->sha256;
return manifest;
}
} // namespace
Api::Result<ReleaseManifest>
ReleaseManifest::load(const std::filesystem::path& manifestPath)
ReleaseManifest::load(const std::filesystem::path& manifestPath)
{
auto contents = Void::FileSystem::read_file(manifestPath);
if (!contents) {
return Api::fail(Api::ErrorCode::NotFound, contents.error().message());
return Api::fail(Api::ErrorCode::NotFound,
contents.error().message());
}
auto json = Void::Json::parse(*contents);
if (!json || !json->is_object()) {
return Api::fail(Api::ErrorCode::ParseError,
json ? "release manifest must be an object"
: "invalid release manifest: " + json.error().message);
json ? "release manifest must be an object"
: "invalid release manifest: " +
json.error().message);
}
ReleaseManifest manifest;
manifest.version = json->get_str("version");
const auto base = manifestPath.parent_path();
const auto executableEntry = std::filesystem::path(
json->get_str("executable"));
const auto coreEntry = std::filesystem::path(json->get_str("core"));
const auto unsafe = [](const std::filesystem::path& path) {
return path.empty() || path.is_absolute() ||
std::ranges::contains(path, std::filesystem::path{".."});
};
if (unsafe(executableEntry) || unsafe(coreEntry)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release artifact paths must stay within the manifest directory");
std::error_code error;
auto root = std::filesystem::weakly_canonical(
normalizedAbsolute(manifestPath).parent_path(), error);
if (error) {
return Api::fail(Api::ErrorCode::NotFound,
"cannot resolve release root: " + error.message());
}
manifest.executable = (base / executableEntry).lexically_normal();
manifest.core = (base / coreEntry).lexically_normal();
if (const auto* hashes = json->find("sha256")) {
manifest.executableSha256 = hashes->get_str("executable");
manifest.coreSha256 = hashes->get_str("core");
const auto* schema = json->find("schemaVersion");
if (!schema) {
return loadVersionOne(*json, root);
}
if (manifest.version.empty() || manifest.executable.filename().empty() ||
manifest.core.filename().empty() || manifest.executableSha256.empty() ||
manifest.coreSha256.empty()) {
return Api::fail(Api::ErrorCode::ParseError,
"release manifest is missing version, artifacts, or hashes");
if (!schema->is_number() || schema->as_number() != 2.0) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"unsupported release manifest schema version");
}
return manifest;
return loadVersionTwo(*json, root);
}
Api::Result<void> ReleaseManifest::validate() const
{
if (!std::filesystem::is_regular_file(executable) ||
!std::filesystem::is_regular_file(core)) {
if (schemaVersion == 1) {
std::error_code rootError;
const auto canonicalRoot =
std::filesystem::weakly_canonical(root, rootError);
if (rootError) {
return Api::fail(Api::ErrorCode::NotFound,
"cannot resolve release root: " +
rootError.message());
}
for (const auto& [path, expected, executableFile] :
{std::tuple{executable, executableSha256, true},
std::tuple{core, coreSha256, false}}) {
std::error_code error;
const auto status =
std::filesystem::symlink_status(path, error);
if (error ||
status.type() != std::filesystem::file_type::regular) {
return Api::fail(
Api::ErrorCode::NotFound,
"release executable and Core must be regular files");
}
const auto resolved = std::filesystem::canonical(path, error);
if (error || !isWithin(canonicalRoot, resolved)) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"release artifact resolves outside the release root: " +
path.string());
}
if (executableFile &&
(status.permissions() & kExecutablePermissions) ==
std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release executable is not executable");
}
auto actual = sha256(path);
if (!actual) {
return std::unexpected(actual.error());
}
if (*actual != expected) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"SHA-256 mismatch for " + path.string());
}
}
return {};
}
std::error_code rootError;
const auto canonicalRoot =
std::filesystem::weakly_canonical(root, rootError);
if (rootError) {
return Api::fail(Api::ErrorCode::NotFound,
"release executable and Core must be regular files");
"cannot resolve release root: " +
rootError.message());
}
const auto permissions = std::filesystem::status(executable).permissions();
if ((permissions & (std::filesystem::perms::owner_exec |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_exec)) == std::filesystem::perms::none) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"release executable is not executable");
}
for (const auto& [path, expected] :
{std::pair{executable, executableSha256},
std::pair{core, coreSha256}}) {
for (const auto& entry : files) {
const auto path = root / entry.path;
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (error ||
status.type() == std::filesystem::file_type::not_found) {
return Api::fail(Api::ErrorCode::NotFound,
"release payload entry is missing: " +
entry.path.string());
}
const auto expectedType = entry.type == ReleaseFileType::Regular
? std::filesystem::file_type::regular
: std::filesystem::file_type::symlink;
if (status.type() != expectedType) {
return Api::fail(
Api::ErrorCode::InvalidArgument,
"unexpected file type for release payload entry: " +
entry.path.string());
}
const auto resolved = std::filesystem::canonical(path, error);
if (error || !isWithin(canonicalRoot, resolved)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"release payload entry resolves outside the "
"release root: " +
entry.path.string());
}
if (entry.type == ReleaseFileType::Symlink) {
const auto actualTarget =
std::filesystem::read_symlink(path, error);
if (error || actualTarget.generic_string() !=
entry.target.generic_string()) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"symbolic link target mismatch for " +
entry.path.string());
}
continue;
}
const auto size = std::filesystem::file_size(path, error);
if (error || size != entry.size) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"file size mismatch for " +
entry.path.string());
}
if ((status.permissions() & std::filesystem::perms::mask) !=
entry.mode) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"file mode mismatch for " +
entry.path.string());
}
auto actual = sha256(path);
if (!actual) {
return std::unexpected(actual.error());
}
if (*actual != expected) {
if (*actual != entry.sha256) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"SHA-256 mismatch for " + path.string());
"SHA-256 mismatch for " + entry.path.string());
}
}
return validateImmutableCoverage(*this);
}
Api::Result<void> ReleaseManifest::validateInstallLayout() const
{
if (schemaVersion != 2) {
return Api::fail(
Api::ErrorCode::IncompatibleVersion,
"installation validation requires a v2 release manifest");
}
if (auto result = validate(); !result) {
return result;
}
const std::filesystem::path expectedExecutable{"bin/echoiond"};
const std::filesystem::path expectedCore{"lib/Echoion.ts"};
const std::filesystem::path expectedWeb{"share/echoion/web/index.html"};
if (executable.lexically_normal() != (root / expectedExecutable) ||
core.lexically_normal() != (root / expectedCore)) {
return Api::fail(Api::ErrorCode::IncompatibleVersion,
"installation manifest does not describe the "
"canonical runtime layout");
}
const auto web =
std::ranges::find(files, expectedWeb, &ReleaseFileEntry::path);
if (web == files.end() || web->type != ReleaseFileType::Regular) {
return Api::fail(Api::ErrorCode::NotFound,
"installation manifest is missing the web "
"dashboard entry point");
}
return {};
}
}
} // namespace Echoion::Standalone
+178
View File
@@ -0,0 +1,178 @@
#include "echoion/standalone/RuntimePaths.hpp"
#include <algorithm>
#include <array>
#include <ranges>
#include <system_error>
namespace Echoion::Standalone
{
namespace
{
std::filesystem::path absoluteNormalized(std::filesystem::path path)
{
std::error_code error;
auto absolute = std::filesystem::absolute(path, error);
if (error) {
return path.lexically_normal();
}
return absolute.lexically_normal();
}
bool isWithinOrEqual(const std::filesystem::path& root,
const std::filesystem::path& candidate)
{
const auto relative = candidate.lexically_relative(root);
return !relative.empty() && !relative.is_absolute() &&
std::ranges::none_of(relative, [](const auto& component) {
return component == "..";
});
}
} // namespace
std::expected<std::filesystem::path, std::string> runningExecutablePath()
{
std::error_code error;
auto executable =
std::filesystem::read_symlink("/proc/self/exe", error);
if (error || executable.empty()) {
return std::unexpected("cannot resolve /proc/self/exe: " +
error.message());
}
auto canonical = std::filesystem::weakly_canonical(executable, error);
if (error) {
return absoluteNormalized(std::move(executable));
}
return canonical;
}
std::filesystem::path deriveInstallRoot(
const std::filesystem::path& executablePath,
const std::optional<std::filesystem::path>& homeOverride)
{
if (homeOverride && !homeOverride->empty()) {
return absoluteNormalized(*homeOverride);
}
const auto executableDirectory =
absoluteNormalized(executablePath).parent_path();
if (executableDirectory.filename() == "bin") {
return executableDirectory.parent_path();
}
return executableDirectory;
}
std::filesystem::path resolveCorePath(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory,
const std::optional<std::filesystem::path>& coreOverride)
{
if (coreOverride && !coreOverride->empty()) {
return coreOverride->is_absolute()
? coreOverride->lexically_normal()
: (installRoot / *coreOverride).lexically_normal();
}
const std::array candidates{
installRoot / "lib" / "Echoion.ts",
executableDirectory / "Echoion.ts",
installRoot / "bin" / "Echoion.ts",
installRoot / "plugins" / "Echoion.ts",
};
for (const auto& candidate : candidates) {
std::error_code error;
if (std::filesystem::is_regular_file(candidate, error) && !error) {
return candidate.lexically_normal();
}
}
return candidates.front().lexically_normal();
}
std::filesystem::path resolveStateDirectory(
const std::optional<std::filesystem::path>& commandLineOverride,
const std::optional<std::filesystem::path>& environmentOverride,
const std::optional<std::filesystem::path>& xdgStateHome,
const std::optional<std::filesystem::path>& userHome,
const std::filesystem::path& fallback)
{
if (commandLineOverride && !commandLineOverride->empty()) {
return absoluteNormalized(*commandLineOverride);
}
if (environmentOverride && !environmentOverride->empty()) {
return absoluteNormalized(*environmentOverride);
}
if (xdgStateHome && !xdgStateHome->empty()) {
return absoluteNormalized(*xdgStateHome / "echoion");
}
if (userHome && !userHome->empty()) {
return absoluteNormalized(*userHome / ".local" / "state" /
"echoion");
}
return absoluteNormalized(fallback);
}
std::optional<std::filesystem::path> runtimeWorkingDirectory(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory)
{
const auto packagedDirectory = installRoot / "share" / "echoion";
std::error_code error;
if (std::filesystem::is_regular_file(
packagedDirectory / "web" / "index.html", error) &&
!error) {
return packagedDirectory;
}
error.clear();
if (std::filesystem::is_regular_file(
executableDirectory / "web" / "index.html", error) &&
!error) {
return executableDirectory;
}
return std::nullopt;
}
std::expected<std::filesystem::path, std::string>
resolveAvatarCacheDirectory(
const std::filesystem::path& configuredDirectory,
const std::filesystem::path& requestedDirectory)
{
if (configuredDirectory.empty()) {
return std::unexpected("avatar cache directory is not configured");
}
std::error_code error;
const auto configured = std::filesystem::weakly_canonical(
absoluteNormalized(configuredDirectory), error);
if (error) {
return std::unexpected("cannot resolve avatar cache directory: " +
error.message());
}
if (!requestedDirectory.empty() && !requestedDirectory.is_absolute() &&
(requestedDirectory != requestedDirectory.lexically_normal() ||
std::ranges::any_of(requestedDirectory, [](const auto& component) {
return component == "." || component == "..";
}))) {
return std::unexpected("avatar cache subdirectory must be "
"normalized and non-traversing");
}
const auto requested = requestedDirectory.empty() ? configured
: requestedDirectory.is_absolute()
? requestedDirectory
: configured / requestedDirectory;
const auto resolved = std::filesystem::weakly_canonical(
absoluteNormalized(requested), error);
if (error) {
return std::unexpected(
"cannot resolve requested avatar directory: " +
error.message());
}
if (!isWithinOrEqual(configured, resolved)) {
return std::unexpected("requested avatar directory is outside the "
"configured state cache");
}
return resolved;
}
} // namespace Echoion::Standalone
+9 -5
View File
@@ -1,5 +1,6 @@
#include "echoion/standalone/AudioEncoder.hpp"
#include "echoion/standalone/MessageChunker.hpp"
#include "echoion/standalone/RuntimePaths.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include <Void/Log/Log.hpp>
@@ -659,16 +660,19 @@ namespace Echoion::Standalone
return Api::fail(Api::ErrorCode::ParseError,
"server returned an unsafe avatar hash");
}
const auto directory =
destDir.empty() ? settings_.avatarCachePath : destDir;
const auto directory = resolveAvatarCacheDirectory(
settings_.avatarCachePath, std::filesystem::path{destDir});
if (!directory) {
return Api::fail(Api::ErrorCode::InvalidArgument,
directory.error());
}
std::error_code directoryError;
std::filesystem::create_directories(directory, directoryError);
std::filesystem::create_directories(*directory, directoryError);
if (directoryError) {
return Api::fail(Api::ErrorCode::PluginError,
"cannot create avatar cache directory");
}
const auto destination =
(std::filesystem::path(directory) / ("avatar_" + hash)).string();
const auto destination = (*directory / ("avatar_" + hash)).string();
if (!std::filesystem::exists(destination)) {
const auto result =
client_->download("/avatar_" + hash, destination);
+214 -49
View File
@@ -3,6 +3,7 @@
#include "echoion/host/CoreLoader.hpp"
#include "echoion/standalone/ReleaseManifest.hpp"
#include "echoion/standalone/RuntimePaths.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include <CoreInterface.hpp>
@@ -25,6 +26,8 @@
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace
{
@@ -56,6 +59,48 @@ namespace
return std::nullopt;
}
bool hasArgument(int argc, char** argv, std::string_view name)
{
for (int index = 1; index < argc; ++index) {
if (std::string_view{argv[index]} == name) {
return true;
}
}
return false;
}
std::optional<std::filesystem::path>
optionalArgumentPath(int argc, char** argv, std::string_view name)
{
for (int index = 1; index < argc; ++index) {
if (std::string_view{argv[index]} != name) {
continue;
}
if (index + 1 < argc &&
!std::string_view{argv[index + 1]}.starts_with("--")) {
return std::filesystem::path{argv[index + 1]};
}
return std::nullopt;
}
return std::nullopt;
}
std::optional<std::filesystem::path> environmentPath(const char* name)
{
const char* value = std::getenv(name);
if (!value || std::string_view{value}.empty()) {
return std::nullopt;
}
return std::filesystem::path{value};
}
std::filesystem::path absolutePath(const std::filesystem::path& path)
{
std::error_code error;
auto absolute = std::filesystem::absolute(path, error);
return (error ? path : absolute).lexically_normal();
}
std::filesystem::path configDir()
{
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
@@ -67,6 +112,60 @@ namespace
return std::filesystem::path(".") / "echoion";
}
bool prepareStateDirectory(const std::filesystem::path& stateDirectory,
bool explicitlySelected)
{
std::error_code error;
std::filesystem::create_directories(stateDirectory, error);
if (error) {
std::cerr << "Cannot create state directory " << stateDirectory
<< ": " << error.message() << '\n';
return false;
}
const auto setPath = [](const char* name,
const std::filesystem::path& path,
bool overwrite) {
const auto value = path.string();
return ::setenv(name, value.c_str(), overwrite ? 1 : 0) == 0;
};
const auto temporaryDirectory = stateDirectory / "tmp";
std::filesystem::create_directories(temporaryDirectory, error);
if (error) {
std::cerr << "Cannot create temporary directory "
<< temporaryDirectory << ": " << error.message() << '\n';
return false;
}
if (!setPath("ECHOION_STATE_DIR", stateDirectory, true) ||
!setPath("XDG_CACHE_HOME", stateDirectory / "cache",
explicitlySelected) ||
!setPath("XDG_STATE_HOME", stateDirectory / "state",
explicitlySelected) ||
!setPath("XDG_DATA_HOME", stateDirectory / "data",
explicitlySelected) ||
!setPath("TMPDIR", temporaryDirectory, explicitlySelected)) {
std::cerr << "Cannot export runtime state paths\n";
return false;
}
return true;
}
int validateInstall(const std::filesystem::path& installRoot)
{
auto manifest = Echoion::Standalone::ReleaseManifest::load(
installRoot / "manifest.json");
if (!manifest) {
std::cerr << manifest.error().message << '\n';
return 2;
}
if (auto result = manifest->validateInstallLayout(); !result) {
std::cerr << result.error().message << '\n';
return 2;
}
std::cout << "Echoion installation is valid: " << installRoot << '\n';
return 0;
}
void recordInterruptedRelease(const std::filesystem::path& directory)
{
const auto transaction = directory / "release-transaction";
@@ -105,21 +204,6 @@ namespace
}
}
// Locate the Core shared library ("Echoion.ts").
std::filesystem::path corePath()
{
if (const char* p = std::getenv("ECHOION_CORE_PATH")) {
return p;
}
for (const char* c :
{"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) {
if (std::filesystem::exists(c)) {
return c;
}
}
return "./Echoion.ts";
}
int importIdentity(int argc, char** argv,
const std::filesystem::path& defaultIdentityPath)
{
@@ -130,9 +214,11 @@ namespace
for (int i = 1; i < argc; ++i) {
const std::string_view argument{argv[i]};
if (argument == "--help") {
std::cout << "Usage: echoiond [--config PATH]\n"
" echoiond --import-identity EXPORT.ini "
"[--identity-path PATH] [--force]\n";
std::cout
<< "Usage: echoiond [--config PATH] [--state-dir PATH]\n"
" echoiond --import-identity EXPORT.ini "
"[--identity-path PATH] [--force]\n"
" echoiond --validate-install [ROOT]\n";
return 0;
}
if (argument == "--import-identity") {
@@ -184,8 +270,14 @@ int main(int argc, char** argv)
std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n';
std::abort();
});
if (const auto validationPath =
argumentValue(argc, argv, "--validate-release")) {
if (hasArgument(argc, argv, "--validate-release")) {
const auto validationPath =
argumentValue(argc, argv, "--validate-release");
if (!validationPath || validationPath->starts_with("--")) {
std::cerr << "--validate-release requires a manifest path\n";
return 2;
}
auto manifest =
Echoion::Standalone::ReleaseManifest::load(*validationPath);
if (!manifest) {
@@ -199,25 +291,70 @@ int main(int argc, char** argv)
return 0;
}
std::filesystem::path cfgDir = configDir();
recordInterruptedRelease(cfgDir);
const auto runningExecutable = Echoion::Standalone::runningExecutablePath();
if (!runningExecutable) {
std::cerr << runningExecutable.error() << '\n';
return 2;
}
const auto installRoot = Echoion::Standalone::deriveInstallRoot(
*runningExecutable, environmentPath("ECHOION_HOME"));
if (hasArgument(argc, argv, "--validate-install")) {
const auto requestedRoot =
optionalArgumentPath(argc, argv, "--validate-install");
return validateInstall(requestedRoot ? absolutePath(*requestedRoot)
: installRoot);
}
const auto installRootString = installRoot.string();
if (::setenv("ECHOION_HOME", installRootString.c_str(), 1) != 0) {
std::cerr << "Cannot export ECHOION_HOME\n";
return 2;
}
for (const std::string_view requiredValue : {"--config", "--state-dir"}) {
if (hasArgument(argc, argv, requiredValue) &&
!optionalArgumentPath(argc, argv, requiredValue)) {
std::cerr << requiredValue << " requires a path\n";
return 2;
}
}
const auto cfgDir = absolutePath(configDir());
std::filesystem::path cfgPath = cfgDir / "config.json";
const auto identityPath = std::filesystem::path(
envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()));
if (const auto requestedConfig =
optionalArgumentPath(argc, argv, "--config")) {
cfgPath = absolutePath(*requestedConfig);
}
const auto commandLineState =
optionalArgumentPath(argc, argv, "--state-dir");
const auto environmentState = environmentPath("ECHOION_STATE_DIR");
const auto stateDirectory = Echoion::Standalone::resolveStateDirectory(
commandLineState, environmentState, environmentPath("XDG_STATE_HOME"),
environmentPath("HOME"), cfgDir);
if (!prepareStateDirectory(stateDirectory,
commandLineState.has_value() ||
environmentState.has_value())) {
return 2;
}
recordInterruptedRelease(stateDirectory);
const auto identityPath = absolutePath(std::filesystem::path(envOr(
"ECHOION_IDENTITY_PATH", (stateDirectory / "identity.txt").string())));
if (const auto importResult = importIdentity(argc, argv, identityPath);
importResult >= 0) {
return importResult;
}
// Optional CLI: --config <path>
for (int i = 1; i + 1 < argc; ++i) {
if (std::string(argv[i]) == "--config") {
cfgPath = argv[i + 1];
}
}
const auto requestedRestore =
optionalArgumentPath(argc, argv, "--restore-state");
const std::optional<std::filesystem::path> restorePath =
requestedRestore ? std::optional{absolutePath(*requestedRestore)}
: std::nullopt;
const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST");
const std::optional<std::filesystem::path> releaseManifestPath =
requestedManifest ? std::optional{absolutePath(*requestedManifest)}
: std::nullopt;
Echoion::Standalone::StandaloneSettings settings;
settings.identityPath = identityPath.string();
settings.avatarCachePath = (cfgDir / "avatars").string();
settings.avatarCachePath = (stateDirectory / "avatars").string();
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
@@ -233,13 +370,27 @@ int main(int argc, char** argv)
Echoion::Host::CoreLoader loader;
loader.setConfigPath(cfgPath);
auto corePathResolved = corePath();
const auto executableDirectory = runningExecutable->parent_path();
const auto corePathResolved = Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory, environmentPath("ECHOION_CORE_PATH"));
if (const auto workingDirectory =
Echoion::Standalone::runtimeWorkingDirectory(installRoot,
executableDirectory)) {
std::error_code error;
std::filesystem::current_path(*workingDirectory, error);
if (error) {
Void::Log::error("main",
"cannot select runtime asset directory {}: {}",
workingDirectory->string(), error.message());
return 1;
}
}
Void::Log::info("main", "Loading Core from {}", corePathResolved.string());
if (auto r = loader.load(corePathResolved); !r) {
Void::Log::error("main", "failed to load Core: {}", r.error().message);
return 1;
}
if (const auto restorePath = argumentValue(argc, argv, "--restore-state")) {
if (restorePath) {
if (auto result = loader.restoreCheckpoint(*restorePath); !result) {
Void::Log::error("main", "failed to restore restart checkpoint: {}",
result.error().message);
@@ -274,9 +425,7 @@ int main(int argc, char** argv)
core->triggerAutoConnect();
std::unique_ptr<Void::FileSystem::FileWatcher> releaseWatcher;
std::optional<std::filesystem::path> releaseManifestPath;
if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) {
releaseManifestPath = manifest;
if (releaseManifestPath) {
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(
*releaseManifestPath,
@@ -287,21 +436,27 @@ int main(int argc, char** argv)
});
Void::Log::info("main", "Watching release manifest {}",
releaseManifestPath->string());
} else {
} else if (!std::filesystem::is_regular_file(installRoot /
"manifest.json")) {
// Compatibility mode for development. Production release bundles use
// transactional daemon re-exec instead of replacing Core in isolation.
loader.enableAutoReload();
} else {
Void::Log::info(
"main", "{}",
"Core auto-reload is disabled for an installed release payload");
}
std::signal(SIGINT, onSignal);
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
std::ignore = Void::FileSystem::atomic_write(
stateDirectory / "release-health", version);
std::ignore = Void::FileSystem::remove_path(stateDirectory /
"release-transaction");
std::ignore =
Void::FileSystem::atomic_write(cfgDir / "release-health", version);
std::ignore =
Void::FileSystem::remove_path(cfgDir / "release-transaction");
std::ignore = Void::FileSystem::remove_path(cfgDir / "failed-release");
Void::FileSystem::remove_path(stateDirectory / "failed-release");
::unsetenv("ECHOION_REEXEC_VERSION");
Void::Log::info("main", "Release {} passed startup health check",
version);
@@ -327,7 +482,7 @@ int main(int argc, char** argv)
continue;
}
if (auto failed =
Void::FileSystem::read_file(cfgDir / "failed-release");
Void::FileSystem::read_file(stateDirectory / "failed-release");
failed && *failed == manifest->version) {
Void::Log::error("main",
"Release {} was previously rolled back; publish a "
@@ -335,17 +490,17 @@ int main(int argc, char** argv)
manifest->version);
continue;
}
auto executable = std::filesystem::canonical("/proc/self/exe");
auto validation = Void::Process::run(
executable, {"--validate-release", releaseManifestPath->string()},
{}, std::chrono::seconds{30});
*runningExecutable,
{"--validate-release", releaseManifestPath->string()}, {},
std::chrono::seconds{30});
if (!validation || validation->exit_code != 0) {
Void::Log::error("main", "release validation failed: {}",
validation ? validation->err
: validation.error().message());
continue;
}
checkpointPath = configDir() / "restart-state.bin";
checkpointPath = stateDirectory / "restart-state.bin";
if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) {
Void::Log::error("main", "release checkpoint failed: {}",
checkpoint.error().message);
@@ -365,14 +520,24 @@ int main(int argc, char** argv)
(void)interface->shutdown();
if (pendingRelease) {
if (auto transaction = Void::FileSystem::atomic_write(
cfgDir / "release-transaction", pendingRelease->version);
stateDirectory / "release-transaction",
pendingRelease->version);
!transaction) {
Void::Log::error("main", "cannot record release transaction: {}",
transaction.error().message());
return 1;
}
::setenv("ECHOION_CORE_PATH", pendingRelease->core.c_str(), 1);
::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(), 1);
const auto pendingRoot =
Echoion::Standalone::deriveInstallRoot(pendingRelease->executable);
const auto pendingRootString = pendingRoot.string();
const auto pendingCoreString = pendingRelease->core.string();
if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 ||
::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 ||
::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(),
1) != 0) {
Void::Log::error("main", "cannot export pending release paths");
return 1;
}
std::vector<std::string> arguments;
arguments.reserve(static_cast<std::size_t>(argc) + 2);
for (int index = 1; index < argc; ++index) {