Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-16 19:59:57 +03:00
1 parent 818d391022
commit 639362fbf5
40 files changed
+6701 -429

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
.git
build*
dist
release
EchoionWeb/frontend/node_modules
EchoionWeb/frontend/web-dist
docs
+4 -1
View File
@@ -1,8 +1,11 @@
*build*
release
/dist/
__pycache__/
*.py[cod]
.claude
.cache
.idea
AGENTS.md
.vscode
.opencode/
.opencode/
+105 -30
View File
@@ -1,6 +1,8 @@
cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
include(GNUInstallDirs)
# Default to a Release build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
@@ -30,12 +32,12 @@ endif()
# must be part of the validated echoiond artifact in production, otherwise a
# release could pair a new daemon with an old/incompatible shared library.
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF)
if(ECHOION_STATIC_LINK)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
message(STATUS "Static linking enabled - building standalone distribution")
message(STATUS "Static GCC runtime linking enabled")
endif()
# Include CPM
@@ -63,7 +65,9 @@ CPMAddPackage(
CPMAddPackage(
NAME Void
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
GIT_TAG main
# Keep clean/container releases reproducible. CPM_Void_SOURCE still
# overrides this revision for local dependency development.
GIT_TAG 8583a479dda93be3394dfadefd7875ddd9e376dc
OPTIONS
"VOID_ENABLE_TESTING OFF"
)
@@ -74,7 +78,8 @@ CPMAddPackage(
CPMAddPackage(
NAME VoidTeamspeak
GIT_REPOSITORY http://git.faumaray.ru/void/voidteamspeak.git
GIT_TAG main
# This revision supplies the typed administration API used by Standalone.
GIT_TAG 89911ff107bc57347e3f91c9e0544265d64de5df
OPTIONS
"VOID_TEAMSPEAK_BUILD_TESTS OFF"
"VOID_ENABLE_TESTING OFF"
@@ -175,35 +180,58 @@ if(BUILD_DESKTOP)
add_subdirectory(EchoionDesktop)
endif()
# Packaging configuration
include(CPack)
set(CPACK_PACKAGE_NAME "Echoion")
set(CPACK_PACKAGE_VENDOR "Echoion")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
# The release install component is deliberately runtime-only. Nested projects
# keep their normal SDK/development install rules, while scripts/release.sh uses
# this component as the single input to dependency collection and packaging.
option(ECHOION_INSTALL_RUNTIME_BUNDLE
"Provide the relocatable Echoion Runtime install component" ON)
if(ECHOION_INSTALL_RUNTIME_BUNDLE)
if(TARGET EchoionStandalone)
if(UNIX AND NOT APPLE)
set_target_properties(EchoionStandalone PROPERTIES
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}"
INSTALL_RPATH_USE_LINK_PATH FALSE)
endif()
install(TARGETS EchoionStandalone
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT Runtime)
endif()
# Platform-specific packaging
if(WIN32)
set(CPACK_GENERATOR "ZIP;NSIS")
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion")
set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion")
elseif(APPLE)
set(CPACK_GENERATOR "DragNDMGZ")
set(CPACK_DMG_VOLUME_NAME "Echoion")
else()
set(CPACK_GENERATOR "TGZ;DEB;RPM")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0")
set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite")
if(TARGET EchoionCore)
if(UNIX AND NOT APPLE)
set_target_properties(EchoionCore PROPERTIES
INSTALL_RPATH "$ORIGIN"
INSTALL_RPATH_USE_LINK_PATH FALSE)
endif()
install(TARGETS EchoionCore
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT Runtime)
endif()
if(TARGET EchoionWeb)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
COMPONENT Runtime)
endif()
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
COMPONENT Runtime)
install(FILES
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in"
DESTINATION service
COMPONENT Runtime)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses"
RENAME Echoion-LICENSE
COMPONENT Runtime)
endif()
endif()
# Bundling and deployment helpers
include(GNUInstallDirs)
# Function to bundle Qt dependencies
function(bundle_qt_dependencies target)
if(NOT TARGET ${target})
@@ -277,6 +305,50 @@ if(BUILD_CORE AND TARGET EchoionCore)
install_with_dependencies(EchoionCore)
endif()
if(BUILD_TESTS AND UNIX)
add_test(NAME echoion_release_manifest_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_runtime_dependency_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_release_archive_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_frontend_license_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_installer_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh")
endif()
# The universal .tar.zst/.run workflow is the supported Linux distribution
# format. Keep legacy CPack available for local Windows/macOS experiments,
# without publishing inaccurate DEB/RPM host-dependency metadata.
option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF)
if(ECHOION_ENABLE_LEGACY_CPACK)
set(CPACK_PACKAGE_NAME "Echoion")
set(CPACK_PACKAGE_VENDOR "Echoion")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
if(WIN32)
set(CPACK_GENERATOR "ZIP;NSIS")
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
elseif(APPLE)
set(CPACK_GENERATOR "DragNDrop")
set(CPACK_DMG_VOLUME_NAME "Echoion")
else()
set(CPACK_GENERATOR "TGZ")
endif()
include(CPack)
endif()
# Print configuration summary
message(STATUS "")
message(STATUS "Echoion Configuration:")
@@ -285,11 +357,14 @@ message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS " Build API: ${BUILD_API}")
message(STATUS " Build Core: ${BUILD_CORE}")
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
message(STATUS " Build Web: ${BUILD_WEB}")
message(STATUS " Build Standalone: ${BUILD_STANDALONE}")
message(STATUS " Build Tests: ${BUILD_TESTS}")
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
message(STATUS "")
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
message(STATUS "To build: cmake --build build")
message(STATUS "To install: cmake --install build --prefix <install_dir>")
message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)")
message(STATUS "To release: scripts/release.sh --version <version>")
message(STATUS "")
+53
View File
@@ -0,0 +1,53 @@
{
"version": 9,
"cmakeMinimumRequired": {
"major": 4,
"minor": 0,
"patch": 0
},
"configurePresets": [
{
"name": "linux-release",
"displayName": "Linux dynamic runtime release",
"description": "Bot, Core, web dashboard, tests, and a runtime-only install component",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build-release",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build-release/stage",
"BUILD_SHARED_LIBS": "ON",
"ECHOION_STATIC_LINK": "OFF",
"ECHOION_INSTALL_RUNTIME_BUNDLE": "ON",
"ECHOION_ENABLE_LEGACY_CPACK": "OFF",
"ECHOION_ENABLE_LTO": "ON",
"BUILD_API": "ON",
"BUILD_CORE": "ON",
"BUILD_WEB": "ON",
"ECHOION_BUILD_WEB": "ON",
"BUILD_STANDALONE": "ON",
"BUILD_DESKTOP": "OFF",
"BUILD_TESTS": "ON"
}
}
],
"buildPresets": [
{
"name": "linux-release",
"configurePreset": "linux-release",
"configuration": "Release"
}
],
"testPresets": [
{
"name": "linux-release",
"configurePreset": "linux-release",
"configuration": "Release",
"output": {
"outputOnFailure": true
},
"execution": {
"noTestsAction": "error"
}
}
]
}
+156 -59
View File
@@ -1,43 +1,114 @@
#include "echoion/host/CoreLoader.hpp"
#include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/System/Path.hpp>
#include "echoion/host/CoreLoader.hpp"
#include <algorithm>
#include <chrono>
#include <format>
#include <fstream>
#include <iostream>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Host
{
namespace
{
bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath)
{
const auto directory = libraryPath.parent_path();
#ifdef _WIN32
std::error_code error;
const auto status = std::filesystem::status(directory, error);
if (error || !std::filesystem::is_directory(status)) {
return false;
}
constexpr auto writable = std::filesystem::perms::owner_write |
std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
return (status.permissions() & writable) !=
std::filesystem::perms::none;
#else
struct stat metadata{};
if (::stat(directory.c_str(), &metadata) != 0 ||
!S_ISDIR(metadata.st_mode)) {
return false;
}
const auto effectiveUser = ::geteuid();
const auto effectiveGroup = ::getegid();
bool usesDirectoryGroup = effectiveGroup == metadata.st_gid;
if (!usesDirectoryGroup) {
const int count = ::getgroups(0, nullptr);
if (count > 0) {
std::vector<gid_t> groups(static_cast<std::size_t>(count));
if (::getgroups(count, groups.data()) == count) {
usesDirectoryGroup =
std::ranges::contains(groups, metadata.st_gid);
}
}
}
mode_t required{};
if (effectiveUser == metadata.st_uid) {
required = S_IWUSR | S_IXUSR;
} else if (usesDirectoryGroup) {
required = S_IWGRP | S_IXGRP;
} else {
required = S_IWOTH | S_IXOTH;
}
return (metadata.st_mode & required) == required &&
::access(directory.c_str(), W_OK | X_OK) == 0;
#endif
}
} // namespace
CoreLoader::CoreLoader()
: pluginManager_(Void::Plugin::PluginManager::Options{
.dlclose_on_swap = false,
.copy_on_load = true,
.config_provider = [this](std::string_view) {
return configPath_.string();
},
.instance_validator = [](Void::Plugin::IPlugin& plugin,
const Void::Plugin::PluginInfo&) {
return dynamic_cast<Api::ICoreInterface*>(&plugin) != nullptr;
}})
// Packaged Core libraries live in an immutable, service-readable
// directory. Initial load must never create a hotswap sibling
// there.
.copy_on_load = false,
.config_provider =
[this](std::string_view) { return configPath_.string(); },
.instance_validator =
[](Void::Plugin::IPlugin& plugin,
const Void::Plugin::PluginInfo&) {
return dynamic_cast<Api::ICoreInterface*>(&plugin) !=
nullptr;
}})
{
}
void CoreLoader::enableAutoReload()
{
if (autoReloadEnabled_.exchange(true)) {
return; // Already enabled
}
std::lock_guard<std::mutex> lock(mutex_);
if (autoReloadEnabled_.load()) {
return;
}
if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) {
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
if (!canCreateHotReloadCopy(currentLibraryPath_)) {
Void::Log::info(
"CoreLoader", "{}",
std::format(
"Auto-reload disabled for read-only Core directory: {}",
currentLibraryPath_.parent_path().string()));
return;
}
autoReloadEnabled_ = true;
Void::Log::info("CoreLoader", "{}",
std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.watch(currentLibraryPath_,
fileWatcher_.watch(
currentLibraryPath_,
[this](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
onCoreFileChanged();
@@ -66,7 +137,8 @@ namespace Echoion::Host
return;
}
Void::Log::info("CoreLoader", "{}",
Void::Log::info(
"CoreLoader", "{}",
"Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete
@@ -88,7 +160,8 @@ namespace Echoion::Host
}
}
Void::Log::info("CoreLoader", "{}",
Void::Log::info(
"CoreLoader", "{}",
std::format("Playback active (track: {}), deferring reload "
"until track finishes",
currentTrackId));
@@ -104,10 +177,12 @@ namespace Echoion::Host
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}",
result.error().message));
Void::Log::error("CoreLoader", "{}",
std::format("Auto hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
Void::Log::info("CoreLoader", "{}",
"Auto hot-reload completed successfully");
}
}
}
@@ -144,8 +219,10 @@ namespace Echoion::Host
void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId)
{
Void::Log::info("CoreLoader", "{}", std::format(
"Waiting for track {} to finish before reload...", trackId));
Void::Log::info(
"CoreLoader", "{}",
std::format("Waiting for track {} to finish before reload...",
trackId));
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS
@@ -157,7 +234,8 @@ namespace Echoion::Host
if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) {
Void::Log::info("CoreLoader", "{}",
Void::Log::info(
"CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)");
return;
}
@@ -167,7 +245,8 @@ namespace Echoion::Host
return;
}
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
Void::Log::info("CoreLoader", "{}",
"Track finished, starting hot reload");
// Clear pending flag
{
@@ -179,10 +258,12 @@ namespace Echoion::Host
// Now do the reload
auto result = hotReload(targetPath);
if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}",
result.error().message));
Void::Log::error("CoreLoader", "{}",
std::format("Deferred hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload completed successfully");
}
}
@@ -211,7 +292,7 @@ namespace Echoion::Host
if (loaded_) {
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already loaded");
"Core already loaded");
}
if (!std::filesystem::exists(libraryPath)) {
@@ -236,13 +317,13 @@ namespace Echoion::Host
}
Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
{
std::unique_lock<std::mutex> lock(mutex_);
if (!loaded_) {
return Api::fail(Api::ErrorCode::NotFound,
"No core loaded to reload");
"No core loaded to reload");
}
auto targetPath =
@@ -254,13 +335,22 @@ namespace Echoion::Host
std::format("New library not found: {}", targetPath.string()));
}
if (targetPath != currentLibraryPath_) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"in-process Core reload must use the loaded path; release bundles "
return Api::fail(
Api::ErrorCode::InvalidArgument,
"in-process Core reload must use the loaded path; release "
"bundles "
"with a new path are applied through daemon re-exec");
}
if (!canCreateHotReloadCopy(targetPath)) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"in-process Core reload requires a writable library directory; "
"immutable releases are applied through daemon re-exec");
}
hotReloading_ = true;
Void::Log::info("CoreLoader", "{}", "Starting transactional hot reload...");
Void::Log::info("CoreLoader", "{}",
"Starting transactional hot reload...");
// No callback may execute code from the old shared object after this
// barrier returns. State capture and dlclose are safe only after event
@@ -289,13 +379,15 @@ namespace Echoion::Host
const auto reloadResult = pluginManager_.reload(pluginName_);
if (!reloadResult) {
hotReloading_ = false;
auto message = std::format(
"new Core rejected; running Core retained: {}",
Void::Plugin::to_string(reloadResult.error()));
auto message =
std::format("new Core rejected; running Core retained: {}",
Void::Plugin::to_string(reloadResult.error()));
if (core_) {
if (auto initialized = core_->initialize(configPath_); !initialized) {
message += std::format("; retained Core reactivation failed: {}",
initialized.error().message);
if (auto initialized = core_->initialize(configPath_);
!initialized) {
message +=
std::format("; retained Core reactivation failed: {}",
initialized.error().message);
} else if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) {
message += std::format(
@@ -320,8 +412,9 @@ namespace Echoion::Host
}
if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) {
Void::Log::warn("CoreLoader", "new Core state restore failed: {}",
restored.error().message);
Void::Log::warn("CoreLoader",
"new Core state restore failed: {}",
restored.error().message);
}
}
hotReloading_ = false;
@@ -360,12 +453,12 @@ namespace Echoion::Host
}
Api::Result<void>
CoreLoader::checkpoint(const std::filesystem::path& destination)
CoreLoader::checkpoint(const std::filesystem::path& destination)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized,
"cannot checkpoint without a loaded Core");
"cannot checkpoint without a loaded Core");
}
const auto state = core_->saveState();
std::string bytes;
@@ -379,37 +472,37 @@ namespace Echoion::Host
appendU32(static_cast<uint32_t>(state.timestamp.size()));
bytes.append(state.timestamp);
bytes.append(reinterpret_cast<const char*>(state.data.data()),
state.data.size());
state.data.size());
if (auto result = Void::FileSystem::atomic_write(destination, bytes);
!result) {
return Api::fail(Api::ErrorCode::PluginError,
result.error().message());
result.error().message());
}
return {};
}
Api::Result<void>
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized,
"cannot restore without a loaded Core");
"cannot restore without a loaded Core");
}
auto contents = Void::FileSystem::read_file(source);
if (!contents) {
return Api::fail(Api::ErrorCode::NotFound,
contents.error().message());
contents.error().message());
}
if (contents->size() < 8) {
return Api::fail(Api::ErrorCode::ParseError,
"checkpoint header is truncated");
"checkpoint header is truncated");
}
auto readU32 = [&contents](std::size_t offset) {
uint32_t value = 0;
for (std::size_t index = 0; index < 4; ++index) {
value = (value << 8U) |
static_cast<unsigned char>((*contents)[offset + index]);
static_cast<unsigned char>((*contents)[offset + index]);
}
return value;
};
@@ -418,12 +511,13 @@ namespace Echoion::Host
const auto timestampSize = readU32(4);
if (timestampSize > contents->size() - 8) {
return Api::fail(Api::ErrorCode::ParseError,
"checkpoint timestamp is truncated");
"checkpoint timestamp is truncated");
}
state.timestamp = contents->substr(8, timestampSize);
const auto dataOffset = 8 + timestampSize;
state.data.assign(contents->begin() +
static_cast<std::ptrdiff_t>(dataOffset), contents->end());
static_cast<std::ptrdiff_t>(dataOffset),
contents->end());
return core_->restoreState(state);
}
@@ -432,9 +526,10 @@ namespace Echoion::Host
{
auto result = pluginManager_.load(path);
if (!result) {
return Api::fail(Api::ErrorCode::PluginError,
return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to load Core plugin: {}",
Void::Plugin::to_string(result.error())));
Void::Plugin::to_string(result.error())));
}
pluginName_ = std::move(*result);
if (auto refreshed = refreshCoreHandle(); !refreshed) {
@@ -453,11 +548,12 @@ namespace Echoion::Host
pluginManager_.acquire(pluginName_));
if (!*pin) {
return Api::fail(Api::ErrorCode::PluginError,
"Core plugin disappeared from the registry");
"Core plugin disappeared from the registry");
}
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
if (interface == nullptr) {
return Api::fail(Api::ErrorCode::InvalidArgument,
return Api::fail(
Api::ErrorCode::InvalidArgument,
"Void plugin does not implement Echoion Core interface");
}
core_ = Api::CoreInterfacePtr{std::move(pin), interface};
@@ -475,9 +571,10 @@ namespace Echoion::Host
core_.reset();
if (!pluginName_.empty()) {
if (auto result = pluginManager_.unload(pluginName_); !result) {
return Api::fail(Api::ErrorCode::PluginError,
return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to unload Core plugin: {}",
Void::Plugin::to_string(result.error())));
Void::Plugin::to_string(result.error())));
}
pluginName_.clear();
}
+16 -1
View File
@@ -11,7 +11,10 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(PkgConfig REQUIRED)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET
libswresample>=4
libavutil>=57
)
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
@@ -22,6 +25,7 @@ add_executable(EchoionStandalone
src/AudioEncoder.cpp
src/MessageChunker.cpp
src/ReleaseManifest.cpp
src/RuntimePaths.cpp
src/EventCallbackGate.cpp
)
@@ -92,6 +96,17 @@ if(BUILD_TESTS)
add_test(NAME echoion_release_manifest_tests
COMMAND echoion_release_manifest_tests)
add_executable(echoion_runtime_paths_tests
tests/test_runtime_paths.cpp
src/RuntimePaths.cpp
)
target_include_directories(echoion_runtime_paths_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_runtime_paths_tests PRIVATE cxx_std_26)
add_test(NAME echoion_runtime_paths_tests
COMMAND echoion_runtime_paths_tests)
add_executable(echoion_event_callback_gate_tests
tests/test_event_callback_gate.cpp
src/EventCallbackGate.cpp
@@ -2,20 +2,40 @@
#include <Types.hpp>
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace Echoion::Standalone
{
struct ReleaseManifest {
std::string version;
std::filesystem::path executable;
std::filesystem::path core;
std::string executableSha256;
std::string coreSha256;
[[nodiscard]] static Api::Result<ReleaseManifest>
load(const std::filesystem::path& manifestPath);
[[nodiscard]] Api::Result<void> validate() const;
enum class ReleaseFileType : std::uint8_t {
Regular,
Symlink,
};
}
struct ReleaseFileEntry {
std::filesystem::path path;
ReleaseFileType type{ReleaseFileType::Regular};
std::uintmax_t size{};
std::filesystem::perms mode{std::filesystem::perms::unknown};
std::string sha256;
std::filesystem::path target;
};
struct ReleaseManifest {
std::uint32_t schemaVersion{1};
std::string version;
std::filesystem::path root;
std::filesystem::path executable;
std::filesystem::path core;
std::string executableSha256;
std::string coreSha256;
std::vector<ReleaseFileEntry> files;
[[nodiscard]] static Api::Result<ReleaseManifest>
load(const std::filesystem::path& manifestPath);
[[nodiscard]] Api::Result<void> validate() const;
[[nodiscard]] Api::Result<void> validateInstallLayout() const;
};
} // namespace Echoion::Standalone
@@ -0,0 +1,39 @@
#pragma once
#include <expected>
#include <filesystem>
#include <optional>
#include <string>
namespace Echoion::Standalone
{
[[nodiscard]] std::expected<std::filesystem::path, std::string>
runningExecutablePath();
[[nodiscard]] std::filesystem::path deriveInstallRoot(
const std::filesystem::path& executablePath,
const std::optional<std::filesystem::path>& homeOverride =
std::nullopt);
[[nodiscard]] std::filesystem::path resolveCorePath(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory,
const std::optional<std::filesystem::path>& coreOverride =
std::nullopt);
[[nodiscard]] 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);
[[nodiscard]] std::optional<std::filesystem::path> runtimeWorkingDirectory(
const std::filesystem::path& installRoot,
const std::filesystem::path& executableDirectory);
[[nodiscard]] std::expected<std::filesystem::path, std::string>
resolveAvatarCacheDirectory(
const std::filesystem::path& configuredDirectory,
const std::filesystem::path& requestedDirectory = {});
} // namespace Echoion::Standalone
+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
@@ -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) {
@@ -4,6 +4,7 @@
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include <unistd.h>
namespace
@@ -13,21 +14,26 @@ namespace
std::cerr << message << '\n';
return 1;
}
}
} // namespace
int main()
{
const auto root = std::filesystem::temp_directory_path() /
("echoion-core-reload-" + std::to_string(::getpid()));
("echoion-core-reload-" + std::to_string(::getpid()));
std::filesystem::create_directories(root);
const auto cleanup = [&root] {
std::error_code ec;
std::filesystem::permissions(root / "immutable-lib",
std::filesystem::perms::owner_all,
std::filesystem::perm_options::add, ec);
std::filesystem::remove_all(root, ec);
};
::setenv("XDG_CONFIG_HOME", root.c_str(), 1);
::setenv("XDG_CACHE_HOME", root.c_str(), 1);
::setenv("HOME", root.c_str(), 1);
const auto stateDirectory = root / "runtime-state";
::setenv("ECHOION_STATE_DIR", stateDirectory.c_str(), 1);
const auto ytDlp = root / ".local/share/echoion/yt-dlp/yt-dlp";
std::filesystem::create_directories(ytDlp.parent_path());
{
@@ -35,9 +41,9 @@ int main()
output << "#!/bin/sh\necho 2026.01.01\n";
}
std::filesystem::permissions(ytDlp,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::owner_exec);
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::owner_exec);
const auto config = root / "config.json";
{
std::ofstream output{config};
@@ -49,8 +55,27 @@ int main()
})";
}
const auto corePath = root / "Echoion.ts";
const auto coreDirectory = root / "immutable-lib";
std::filesystem::create_directories(coreDirectory);
const auto corePath = coreDirectory / "Echoion.ts";
std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath);
const auto directoryEntries = [&coreDirectory] {
std::set<std::filesystem::path> entries;
for (const auto& entry :
std::filesystem::directory_iterator{coreDirectory}) {
entries.insert(entry.path().filename());
}
return entries;
};
const auto entriesBeforeLoad = directoryEntries();
std::filesystem::permissions(coreDirectory,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace);
Echoion::Host::CoreLoader loader;
loader.setConfigPath(config);
@@ -58,11 +83,41 @@ int main()
cleanup();
return fail(result.error().message.c_str());
}
if (directoryEntries() != entriesBeforeLoad) {
cleanup();
return fail(
"initial Core load wrote into the immutable library directory");
}
loader.enableAutoReload();
if (loader.isAutoReloadEnabled()) {
cleanup();
return fail("auto-reload was enabled for a read-only Core directory");
}
std::filesystem::permissions(coreDirectory,
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace);
loader.enableAutoReload();
if (!loader.isAutoReloadEnabled()) {
cleanup();
return fail(
"auto-reload was not enabled for a writable development Core");
}
loader.disableAutoReload();
const auto before = loader.getCore();
if (!before) {
cleanup();
return fail("Core missing after initial load");
}
if (!std::filesystem::is_regular_file(stateDirectory / "echoion.db") ||
std::filesystem::exists(root / "echoion.db") ||
!std::filesystem::is_directory(stateDirectory / "logs")) {
cleanup();
return fail("Core mutable files did not use ECHOION_STATE_DIR");
}
if (auto result = loader.hotReload(corePath); !result) {
cleanup();
return fail(result.error().message.c_str());
@@ -84,7 +139,8 @@ int main()
return fail("invalid replacement unexpectedly activated");
}
const auto retained = loader.getCore();
if (!retained || retained.get() != after.get() || !retained->isInitialized()) {
if (!retained || retained.get() != after.get() ||
!retained->isInitialized()) {
cleanup();
return fail("running Core was not retained after failed activation");
}
+268 -17
View File
@@ -3,36 +3,287 @@
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <vector>
namespace
{
constexpr std::string_view kAbcSha256 =
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
std::string fileEntry(std::string_view path, std::uintmax_t size,
std::string_view mode,
std::string_view sha256 = kAbcSha256)
{
return "{\"path\":\"" + std::string(path) +
"\",\"type\":\"file\",\"size\":" + std::to_string(size) +
",\"mode\":\"" + std::string(mode) + "\",\"sha256\":\"" +
std::string(sha256) + "\"}";
}
std::string symlinkEntry(std::string_view path, std::string_view target)
{
return "{\"path\":\"" + std::string(path) +
"\",\"type\":\"symlink\",\"target\":\"" + std::string(target) +
"\"}";
}
std::string manifest(std::vector<std::string> entries,
std::string_view executable = "bin/echoiond",
std::string_view core = "lib/Echoion.ts")
{
std::string files;
for (const auto& entry : entries) {
if (!files.empty()) {
files += ',';
}
files += entry;
}
return "{\"schemaVersion\":2,\"version\":\"1.2.3\","
"\"executable\":\"" +
std::string(executable) + "\",\"core\":\"" + std::string(core) +
"\",\"files\":[" + files + "]}";
}
bool writeFile(const std::filesystem::path& path, std::string_view contents,
std::filesystem::perms permissions)
{
std::filesystem::create_directories(path.parent_path());
if (auto result = Void::FileSystem::atomic_write(path, contents);
!result) {
std::cerr << result.error().message() << '\n';
return false;
}
std::error_code error;
std::filesystem::permissions(
path, permissions, std::filesystem::perm_options::replace, error);
if (error) {
std::cerr << error.message() << '\n';
return false;
}
return true;
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, std::string_view message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
auto directory = Void::FileSystem::TempDir::open("echoion-manifest-test");
if (!directory) {
std::cerr << directory.error().message() << '\n';
return 1;
}
const auto manifestPath = directory->path() / "pending.json";
const std::string traversal = R"({
"version":"bad",
"executable":"../echoiond",
"core":"release/Echoion.ts",
"sha256":{"executable":"x","core":"y"}
})";
if (auto written = Void::FileSystem::atomic_write(manifestPath, traversal);
!written) {
std::cerr << written.error().message() << '\n';
const auto root = directory->path();
const auto manifestPath = root / "manifest.json";
const auto executablePath = root / "bin" / "echoiond";
const auto corePath = root / "lib" / "Echoion.ts";
const auto webPath = root / "share" / "echoion" / "web" / "index.html";
const auto servicePath = root / "service" / "echoion.service.in";
const auto aliasPath = root / "lib" / "libEchoionCore.so";
const auto otherPath = root / "lib" / "Other.so";
const auto executableMode = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec;
const auto regularMode = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
if (!writeFile(executablePath, "abc", executableMode) ||
!writeFile(corePath, "abc", regularMode) ||
!writeFile(webPath, "abc", regularMode) ||
!writeFile(servicePath, "abc", regularMode) ||
!writeFile(otherPath, "abc", regularMode)) {
return 1;
}
if (Echoion::Standalone::ReleaseManifest::load(manifestPath)) {
std::cerr << "path traversal manifest was accepted\n";
std::error_code error;
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
if (error) {
std::cerr << error.message() << '\n';
return 1;
}
if (auto written = Void::FileSystem::atomic_write(manifestPath, "{}");
!written) return 1;
if (Echoion::Standalone::ReleaseManifest::load(manifestPath)) {
std::cerr << "incomplete manifest was accepted\n";
const auto validManifest = manifest({
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
fileEntry("lib/Other.so", 3, "0644"),
fileEntry("service/echoion.service.in", 3, "0644"),
fileEntry("share/echoion/web/index.html", 3, "0644"),
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
});
check(
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
"failed to write valid manifest");
auto loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(loaded.has_value(), "valid v2 manifest was rejected while loading");
if (loaded) {
check(loaded->validate().has_value(),
"valid v2 manifest payload was rejected");
check(loaded->validateInstallLayout().has_value(),
"valid canonical install layout was rejected");
const auto undeclaredFile = root / "lib" / "undeclared.so";
check(writeFile(undeclaredFile, "abc", regularMode),
"failed to create undeclared regular-file fixture");
check(!loaded->validate(),
"undeclared regular file in immutable payload was accepted");
std::filesystem::remove(undeclaredFile, error);
const auto undeclaredLink = root / "lib" / "undeclared-link.so";
std::filesystem::create_symlink("Echoion.ts", undeclaredLink, error);
check(!error, "failed to create undeclared symbolic-link fixture");
check(!loaded->validate(),
"undeclared symbolic link in immutable payload was accepted");
std::filesystem::remove(undeclaredLink, error);
const auto specialFile = root / "lib" / "unexpected.fifo";
check(::mkfifo(specialFile.c_str(), 0600) == 0,
"failed to create special-file fixture");
check(!loaded->validate(),
"special file in immutable payload was accepted");
std::filesystem::remove(specialFile, error);
check(writeFile(root / "data" / "mutable-state", "abc", regularMode),
"failed to create mutable-root fixture");
check(loaded->validate().has_value(),
"mutable file outside immutable payload roots was rejected");
std::filesystem::permissions(root / "lib", std::filesystem::perms::all,
std::filesystem::perm_options::replace,
error);
check(!error, "failed to make immutable directory writable");
check(!loaded->validate(),
"world-writable immutable directory was accepted");
std::filesystem::permissions(root / "lib",
std::filesystem::perms::owner_all |
std::filesystem::perms::group_read |
std::filesystem::perms::group_exec |
std::filesystem::perms::others_read |
std::filesystem::perms::others_exec,
std::filesystem::perm_options::replace,
error);
check(!error, "failed to restore immutable directory mode");
}
const auto expectLoadFailure = [&](const std::string& contents,
std::string_view message) {
check(
Void::FileSystem::atomic_write(manifestPath, contents).has_value(),
"failed to write invalid manifest fixture");
check(!Echoion::Standalone::ReleaseManifest::load(manifestPath),
message);
};
expectLoadFailure(manifest({fileEntry("../echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644")},
"../echoiond"),
"path traversal manifest was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644")}),
"duplicate payload path was accepted");
expectLoadFailure(
manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
symlinkEntry("lib/escape.so", "../outside.so")}),
"traversing symbolic link target was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0777"),
fileEntry("lib/Echoion.ts", 3, "0644")}),
"world-writable executable metadata was accepted");
expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0666")}),
"world-writable non-executable metadata was accepted");
check(writeFile(root / "outside.dat", "abc", regularMode),
"failed to create outside-root manifest fixture");
const auto outsideManifest = manifest({
fileEntry("bin/echoiond", 3, "0755"),
fileEntry("lib/Echoion.ts", 3, "0644"),
fileEntry("lib/Other.so", 3, "0644"),
fileEntry("service/echoion.service.in", 3, "0644"),
fileEntry("share/echoion/web/index.html", 3, "0644"),
symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"),
fileEntry("outside.dat", 3, "0644"),
});
check(Void::FileSystem::atomic_write(manifestPath, outsideManifest)
.has_value(),
"failed to write outside-root manifest");
const auto outside =
Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(outside.has_value() && !outside->validate(),
"manifest entry outside immutable roots was accepted");
expectLoadFailure("{\"schemaVersion\":3,\"version\":\"future\"}",
"unsupported schema version was accepted");
check(
Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(),
"failed to restore valid manifest");
loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath);
if (!loaded) {
std::cerr << "could not reload valid manifest\n";
return 1;
}
return 0;
{
std::ofstream output(corePath, std::ios::trunc);
output << "xyz";
}
check(!loaded->validate(), "tampered payload hash was accepted");
check(writeFile(corePath, "abc", regularMode),
"failed to restore Core fixture");
std::filesystem::permissions(corePath, std::filesystem::perms::owner_read,
std::filesystem::perm_options::replace, error);
check(!error, "failed to modify Core permissions fixture");
check(!loaded->validate(), "payload mode mismatch was accepted");
std::filesystem::permissions(corePath, regularMode,
std::filesystem::perm_options::replace, error);
std::filesystem::remove(aliasPath, error);
std::filesystem::create_symlink("Other.so", aliasPath, error);
check(!error, "failed to replace symbolic link fixture");
check(!loaded->validate(), "symbolic link target mismatch was accepted");
std::filesystem::remove(aliasPath, error);
check(writeFile(aliasPath, "abc", regularMode),
"failed to create wrong-type fixture");
check(!loaded->validate(), "unexpected regular-file type was accepted");
std::filesystem::remove(aliasPath, error);
std::filesystem::create_symlink("Echoion.ts", aliasPath, error);
std::filesystem::remove(webPath, error);
check(!loaded->validate(), "missing payload entry was accepted");
check(writeFile(webPath, "abc", regularMode),
"failed to restore web fixture");
const std::string legacyManifest =
"{\"version\":\"legacy\",\"executable\":\"bin/echoiond\","
"\"core\":\"lib/Echoion.ts\",\"sha256\":{\"executable\":\"" +
std::string(kAbcSha256) + "\",\"core\":\"" + std::string(kAbcSha256) +
"\"}}";
check(Void::FileSystem::atomic_write(manifestPath, legacyManifest)
.has_value(),
"failed to write legacy manifest");
auto legacy = Echoion::Standalone::ReleaseManifest::load(manifestPath);
check(legacy.has_value(), "legacy release manifest was rejected");
if (legacy) {
check(legacy->validate().has_value(),
"legacy release payload was rejected");
check(!legacy->validateInstallLayout(),
"legacy manifest was accepted for full install validation");
}
return failures == 0 ? 0 : 1;
}
@@ -0,0 +1,144 @@
#include "echoion/standalone/RuntimePaths.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
namespace
{
class TemporaryTree
{
public:
TemporaryTree()
{
std::random_device random;
path_ =
std::filesystem::temp_directory_path() /
("echoion-runtime-paths-" +
std::to_string(static_cast<unsigned long long>(random())));
std::filesystem::create_directories(path_);
}
~TemporaryTree()
{
std::error_code error;
std::filesystem::remove_all(path_, error);
}
TemporaryTree(const TemporaryTree&) = delete;
TemporaryTree& operator=(const TemporaryTree&) = delete;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return path_;
}
private:
std::filesystem::path path_;
};
bool writeFile(const std::filesystem::path& path)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output(path);
output << "test\n";
return output.good();
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, const std::string& message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
TemporaryTree tree;
const auto installRoot = tree.path() / "echoion";
const auto executable = installRoot / "bin" / "echoiond";
const auto executableDirectory = executable.parent_path();
check(Echoion::Standalone::deriveInstallRoot(executable) == installRoot,
"bin/echoiond did not resolve to its installation root");
check(Echoion::Standalone::deriveInstallRoot(
executable, tree.path() / "override") == tree.path() / "override",
"ECHOION_HOME-style override was not preferred");
const auto state = Echoion::Standalone::resolveStateDirectory(
tree.path() / "cli-state", tree.path() / "environment-state",
tree.path() / "xdg-state", tree.path() / "home",
tree.path() / "fallback");
check(state == tree.path() / "cli-state",
"command-line state directory did not win precedence");
check(Echoion::Standalone::resolveStateDirectory(
std::nullopt, tree.path() / "environment-state",
tree.path() / "xdg-state", tree.path() / "home",
tree.path() / "fallback") == tree.path() / "environment-state",
"environment state directory did not win precedence");
check(Echoion::Standalone::resolveStateDirectory(
std::nullopt, std::nullopt, tree.path() / "xdg-state",
tree.path() / "home", tree.path() / "fallback") ==
tree.path() / "xdg-state" / "echoion",
"XDG state directory fallback is incorrect");
const auto packagedCore = installRoot / "lib" / "Echoion.ts";
check(writeFile(packagedCore), "failed to create packaged Core fixture");
check(Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory) == packagedCore,
"packaged Core was not resolved from install-root/lib");
check(Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory,
std::filesystem::path{"custom/Echoion.ts"}) ==
installRoot / "custom" / "Echoion.ts",
"relative Core override was not anchored at the install root");
const auto packagedIndex =
installRoot / "share" / "echoion" / "web" / "index.html";
check(writeFile(packagedIndex), "failed to create packaged web fixture");
check(
Echoion::Standalone::runtimeWorkingDirectory(installRoot,
executableDirectory) ==
installRoot / "share" / "echoion",
"packaged web root did not select share/echoion as working directory");
std::filesystem::remove_all(installRoot / "share");
const auto developmentIndex = executableDirectory / "web" / "index.html";
check(writeFile(developmentIndex),
"failed to create development web fixture");
check(Echoion::Standalone::runtimeWorkingDirectory(
installRoot, executableDirectory) == executableDirectory,
"development web root did not select the executable directory");
const auto avatarCache = tree.path() / "state" / "avatars";
std::filesystem::create_directories(avatarCache);
check(Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache) ==
avatarCache,
"empty avatar directory request did not select the state cache");
check(Echoion::Standalone::resolveAvatarCacheDirectory(
avatarCache, "legacy") == avatarCache / "legacy",
"relative avatar directory was not rooted below state");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
"../escape"),
"traversing avatar directory was accepted");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(
avatarCache, tree.path() / "outside"),
"absolute avatar directory outside state was accepted");
const auto avatarEscape = avatarCache / "escape";
std::error_code avatarError;
std::filesystem::create_symlink(tree.path(), avatarEscape, avatarError);
check(!avatarError, "failed to create avatar symlink escape fixture");
check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache,
"escape/cache"),
"avatar directory escaped state through a symbolic link");
const auto runningExecutable = Echoion::Standalone::runningExecutablePath();
check(runningExecutable.has_value() &&
std::filesystem::is_regular_file(*runningExecutable),
"running executable could not be resolved through /proc/self/exe");
return failures == 0 ? 0 : 1;
}
+27 -13
View File
@@ -3,32 +3,46 @@ set -euo pipefail
stage_script=$1
validator=$2
generator=$(dirname -- "$stage_script")/generate-release-manifest.py
root=$(mktemp -d)
trap 'rm -rf -- "$root"' EXIT
printf '#!/bin/sh\nexit 0\n' > "$root/source-echoiond"
chmod 0755 "$root/source-echoiond"
printf 'test core\n' > "$root/source-core.ts"
bundle=$root/bundle
mkdir -p -- \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
printf '#!/bin/sh\nexit 0\n' > "$bundle/bin/echoiond"
chmod 0755 "$bundle/bin/echoiond"
printf 'test core\n' > "$bundle/lib/Echoion.ts"
printf '[Service]\nExecStart=@ECHOION_EXECUTABLE@\n' \
> "$bundle/service/echoion.service.in"
printf '<!doctype html>\n' > "$bundle/share/echoion/web/index.html"
ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so"
"$stage_script" "$root/releases" 1.2.3 \
"$root/source-echoiond" "$root/source-core.ts"
python3 "$generator" --root "$bundle" --version 1.2.3
"$validator" --validate-install "$bundle"
manifest="$root/releases/pending-release.json"
test -x "$root/releases/1.2.3/echoiond"
test -f "$root/releases/1.2.3/Echoion.ts"
bash "$stage_script" "$root/releases" 1.2.3 "$bundle"
manifest=$root/releases/pending-release.json
test -x "$root/releases/1.2.3/bin/echoiond"
test -f "$root/releases/1.2.3/lib/Echoion.ts"
test -L "$root/releases/1.2.3/lib/libEchoionCore.so"
grep -q '"version": "1.2.3"' "$manifest"
grep -q '"executable": "1.2.3/echoiond"' "$manifest"
grep -q "$(sha256sum "$root/releases/1.2.3/echoiond" | cut -d' ' -f1)" "$manifest"
grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest"
grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest"
"$validator" --validate-release "$manifest"
printf 'tampered\n' >> "$root/releases/1.2.3/Echoion.ts"
printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts"
if "$validator" --validate-release "$manifest" >/dev/null 2>&1; then
echo "tampered Core artifact was accepted" >&2
exit 1
fi
if "$stage_script" "$root/releases" '../unsafe' \
"$root/source-echoiond" "$root/source-core.ts" >/dev/null 2>&1; then
if bash "$stage_script" "$root/releases" '../unsafe' "$bundle" \
>/dev/null 2>&1; then
echo "unsafe version was accepted" >&2
exit 1
fi
+8 -4
View File
@@ -71,9 +71,12 @@ if(ECHOION_BUILD_WEB)
# Rebuild web-dist whenever any source/config under frontend/ (excluding
# node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
# build time so new files are picked up without re-running CMake.
file(GLOB_RECURSE _web_srcs CONFIGURE_DEPENDS
file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS
LIST_DIRECTORIES FALSE
"${_web_frontend}/src/*"
"${_web_frontend}/public/*"
"${_web_frontend}/public/*")
set(_web_srcs
${_web_tree_srcs}
"${_web_frontend}/index.html"
"${_web_frontend}/package.json"
"${_web_frontend}/package-lock.json"
@@ -82,8 +85,9 @@ if(ECHOION_BUILD_WEB)
add_custom_command(
OUTPUT "${_web_dist}/index.html"
# `npm ci` when the lockfile is newer than node_modules keeps installs
# reproducible; the stamp check avoids reinstalling on every build.
# Release builds run `npm ci` before CMake. This lockfile-aware fallback
# keeps direct developer builds convenient without reinstalling on every
# incremental build.
COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
COMMAND ${NPM_EXECUTABLE} run build
WORKING_DIRECTORY "${_web_frontend}"
+126 -57
View File
@@ -27,32 +27,48 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
## Building
### Requirements
### Developer requirements
- C++26 compatible compiler with reflections (GCC 16+)
- CMake 4.0+
- Qt6 (for desktop client)
- FFmpeg (for audio decoding)
- Qt6 (only when building the desktop client)
- FFmpeg 5+ (for audio decoding and the modern channel-layout API)
- Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url)
- OpenSSL, libsodium, Opus, FFmpeg, and Boost development packages
### Build Instructions
### Local build
```bash
mkdir build && cd build
cmake ..
cmake --build .
cmake -S . -B build -DBUILD_TESTS=ON
cmake --build build -j2
ctest --test-dir build --output-on-failure
```
### Tests
The supported Linux release is dynamically linked. Static GCC runtime linking
is disabled by default; the release process collects the non-glibc shared
library closure into the bundle and assigns relocatable `$ORIGIN` RUNPATHs.
### Clean containerized Linux release
Docker is the only host requirement for the default release command:
```bash
cmake .. -DBUILD_TESTS=ON
cmake --build . && ctest
scripts/release.sh --version 1.2.3
```
The protocol suite covers command escaping/parsing, packet crypto, QuickLZ,
identity generation and persistence, and TeamSpeak identity-export import.
It builds with a version-pinned GCC 16/FFmpeg 8.0.3 toolchain on Ubuntu 22.04,
runs the C++ and frontend test suites, installs into a clean staging tree,
bundles dynamic dependencies, validates the ELF closure with `readelf`, and
produces both `.tar.zst` and self-extracting `.run` artifacts under `dist/`.
The bot is never initialized or started during release creation. Use `--host`
only on a Debian-family build host with `dpkg-query`, `ldconfig`, and a glibc
ABI no newer than the supported 2.35 floor; incompatible host artifacts are
rejected.
The Linux x86-64 bundle targets glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+,
and current Arch Linux). glibc and the ELF loader come from the target system;
libstdc++, libgcc, FFmpeg, OpenSSL, Opus, and the remaining runtime closure are
carried in `lib/`.
## Configuration
@@ -66,7 +82,7 @@ Edit the configuration file with your server details:
```json
{
"server": {
"teamspeak": {
"address": "your.server.com",
"port": 9987,
"nickname": "MusicBot",
@@ -77,20 +93,78 @@ Edit the configuration file with your server details:
## Installation
### Standalone daemon
The `.run` artifact is the recommended installer. It supports system, user,
and portable layouts and never starts the bot unless `--start` is explicitly
supplied.
1. Build the project and install `echoiond` together with `Echoion.ts`.
2. Copy `systemd/echoion-standalone.service` to your user systemd directory,
adjust its paths, and enable it.
3. On first start, Echoion generates `~/.config/echoion/identity.txt`.
```bash
# User install; registers a disabled/stopped user service.
./echoion-1.2.3-linux-x86_64.run \
--mode user --non-interactive
# System install and explicit activation.
sudo ./echoion-1.2.3-linux-x86_64.run \
--mode system --register-service system --start --non-interactive
# Fully self-contained portable install, without a service.
./echoion-1.2.3-linux-x86_64.run \
--mode portable --prefix /srv/echoion-portable \
--data-layout self-contained --register-service none --non-interactive
# A portable tree may also register a stable user service.
./echoion-1.2.3-linux-x86_64.run \
--mode portable --prefix "$HOME/echoion-portable" \
--data-layout self-contained --register-service user --non-interactive
```
Portable service registration rejects temporary, world-writable, or
service-inaccessible prefixes, including group/world-writable ancestors. Run
user-service registration as the intended non-root user; root user services are
rejected. Use `--register-service system` with root when a portable tree must
run as a system service. Its complete runtime path must be root-owned and not
writable by the service account. Registration alone performs a daemon reload
and leaves the unit disabled and stopped; add `--start` to enable and start it.
Every installation uses immutable `versions/<version>/` payloads and an atomic
`current` symlink. Configuration is created once and is not overwritten by an
upgrade. The standard mutable paths are:
| Mode | Configuration | State, database, logs, cache and temporary files |
|---|---|---|
| user/portable with no or user service | `$XDG_CONFIG_HOME/echoion` | `$XDG_STATE_HOME/echoion` |
| system/portable with system service | `/etc/echoion` | `/var/lib/echoion` |
| self-contained | `<prefix>/config` | `<prefix>/data` |
Override them with `--config-dir` and `--state-dir`. In a self-contained
portable install, runtime code, web assets, config, identity, database,
extensions, logs, downloaded helpers, cache, and temporary audio all remain
below the selected prefix.
A self-contained portable install also creates `<prefix>/echoion`; use that
launcher instead of invoking `current/bin/echoiond` directly. It derives the
config and state paths from its own location, so a stopped, service-free tree
can be moved as one folder and run from the new path. If a portable service was
registered, uninstall or re-register its unit before moving the tree because
systemd stores an absolute executable path.
The installer executes only the daemon's offline `--validate-install` mode to
verify every immutable file, symlink, mode, and SHA-256 before switching
`current`; it does not initialize the TeamSpeak client or load Core.
To remove an install, run `<prefix>/uninstall.sh`. Configuration and state are
preserved by default. Add `--purge` to remove directories that this installer
created and marked as dedicated Echoion data. Pre-existing override directories
are preserved and must be removed manually.
To preserve the permissions and UID of an existing TeamSpeak client identity,
export it from TeamSpeak's Identity Manager and import it before first start:
```bash
echoiond --import-identity identity.ini
<prefix>/current/bin/echoiond --import-identity identity.ini \
--state-dir <state-directory>
# Choose a non-default destination or replace an existing identity explicitly:
echoiond --import-identity identity.ini --identity-path /path/to/identity.txt --force
<prefix>/current/bin/echoiond --import-identity identity.ini \
--identity-path /path/to/identity.txt --force
```
The identity file contains a private key. Keep both the TeamSpeak export and
@@ -157,26 +231,35 @@ visible TeamSpeak identity.
## Development
### Hot Reload
### Development hot reload
The core library can be hot-reloaded without disconnecting from the server:
1. Build the new core: `cmake --build . --target EchoionCore`
2. Replace `Echoion.ts`; the daemon's host watcher reloads it automatically.
Protocol or host changes require a validated daemon re-exec rather than a Core
hot reload. Stage both artifacts and atomically publish the watched manifest:
This developer-only watcher is enabled for writable build trees. Installed
release payloads are immutable and use installer upgrades plus service restart
instead of writing temporary libraries beside Core.
Protocol or host changes can use the daemon's opt-in transactional re-exec API.
The process must be started with `ECHOION_RELEASE_MANIFEST` set to the absolute
manifest path before a release is staged:
```bash
export ECHOION_RELEASE_MANIFEST="$HOME/echoion/releases/pending-release.json"
# Start the development daemon with its normal --config/--state-dir arguments.
scripts/stage-release.sh "$HOME/echoion/releases" 1.2.3 \
build/bin/echoiond build/lib/Echoion.ts
build-release/runtime-stage
```
The staging command rejects unsafe version names and existing release
directories, copies complete artifacts first, calculates SHA-256 hashes, then
renames `pending-release.json` into place. The running daemon validates it in a
child process, checkpoints Core state, disconnects cleanly, and
re-execs the staged binary.
directories, verifies the bundle's v2 whole-payload manifest, copies the full
runtime tree, and then renames `pending-release.json` into place. The running
daemon validates every declared file in a child process, checkpoints Core
state, disconnects cleanly, and re-execs the staged binary. The installer does
not enable this development watcher; installed upgrades are performed by
running the new `.run` artifact against the same prefix.
### Adding Commands
@@ -204,40 +287,26 @@ instead of compiling commands into Core. See [Native plugins](docs/plugins.md).
## Packaging and Distribution
### Using CPack
The supported Linux distribution path is `scripts/release.sh`. Each release
contains:
The project includes CPack configuration for creating installers:
- `echoion-<version>-linux-x86_64.tar.zst` with one top-level directory;
- `echoion-<version>-linux-x86_64.run`, which accepts the installer flags above;
- the external v2 manifest and ELF dependency report;
- `SHA256SUMS` for all published artifacts.
The archive and installer contain the same relocatable dynamic payload. They do
not depend on DEB/RPM metadata or static linking, so one build can be installed
on the supported Ubuntu, Debian, and Arch targets.
When unpacking the `.tar.zst` form directly, preserve the release modes even
under a restrictive shell umask:
```bash
cd build
# Create tarball
cpack -G TGZ
# Create DEB package (Debian/Ubuntu)
cpack -G DEB
# Create RPM package (Fedora/RHEL)
cpack -G RPM
# Create ZIP (Windows)
cpack -G ZIP
# Create NSIS installer (Windows)
cpack -G NSIS
tar --same-permissions --no-same-owner --zstd \
-xf echoion-1.2.3-linux-x86_64.tar.zst
```
### Static Linking
For a standalone distribution without external dependencies:
```bash
cmake .. -DECHOION_STATIC_LINK=ON
cmake --build .
```
Note: Some dependencies (Qt6, FFmpeg) may still require bundling. See `packaging/README.md` for detailed instructions.
### CMake Package Support
The project uses [PackageProject.cmake](https://github.com/TheLartians/PackageProject.cmake) to export CMake targets:
+197
View File
@@ -0,0 +1,197 @@
cmake_minimum_required(VERSION 4.0)
if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
message(FATAL_ERROR "Echoion runtime dependency bundling currently supports Linux only")
endif()
if(NOT DEFINED BUNDLE_ROOT OR BUNDLE_ROOT STREQUAL "")
message(FATAL_ERROR "BUNDLE_ROOT must name the staged runtime tree")
endif()
if(NOT DEFINED PATCHELF_EXECUTABLE OR PATCHELF_EXECUTABLE STREQUAL "")
find_program(PATCHELF_EXECUTABLE NAMES patchelf REQUIRED)
endif()
if(NOT DEFINED BUNDLE_SEED_FILES OR BUNDLE_SEED_FILES STREQUAL "")
message(FATAL_ERROR
"BUNDLE_SEED_FILES must contain the exact compiler runtime libraries")
endif()
cmake_path(ABSOLUTE_PATH BUNDLE_ROOT NORMALIZE OUTPUT_VARIABLE _bundle_root)
set(_executable "${_bundle_root}/bin/echoiond")
set(_core "${_bundle_root}/lib/Echoion.ts")
set(_library_dir "${_bundle_root}/lib")
if(NOT DEFINED BUNDLE_RESOLVER_EXECUTABLE OR
BUNDLE_RESOLVER_EXECUTABLE STREQUAL "")
set(BUNDLE_RESOLVER_EXECUTABLE "${_executable}")
endif()
if(NOT DEFINED BUNDLE_RESOLVER_LIBRARIES OR
BUNDLE_RESOLVER_LIBRARIES STREQUAL "")
set(BUNDLE_RESOLVER_LIBRARIES "${_core}")
endif()
if(NOT EXISTS "${_executable}")
message(FATAL_ERROR "Missing staged daemon: ${_executable}")
endif()
if(NOT EXISTS "${_core}")
message(FATAL_ERROR "Missing staged Core library: ${_core}")
endif()
if(NOT IS_ABSOLUTE "${BUNDLE_RESOLVER_EXECUTABLE}" OR
NOT EXISTS "${BUNDLE_RESOLVER_EXECUTABLE}" OR
IS_DIRECTORY "${BUNDLE_RESOLVER_EXECUTABLE}")
message(FATAL_ERROR
"Missing absolute dependency resolver executable: ${BUNDLE_RESOLVER_EXECUTABLE}")
endif()
foreach(_resolver_library IN LISTS BUNDLE_RESOLVER_LIBRARIES)
if(NOT IS_ABSOLUTE "${_resolver_library}" OR
NOT EXISTS "${_resolver_library}" OR
IS_DIRECTORY "${_resolver_library}")
message(FATAL_ERROR
"Missing absolute dependency resolver library: ${_resolver_library}")
endif()
endforeach()
file(MAKE_DIRECTORY "${_library_dir}")
# Linux dependency resolution checks RUNPATH and then ldconfig before consulting
# DIRECTORIES. Seed the exact compiler runtimes into $ORIGIN first so an older
# host libstdc++/libgcc with the same SONAME cannot be selected accidentally.
foreach(_seed IN LISTS BUNDLE_SEED_FILES)
if(NOT IS_ABSOLUTE "${_seed}" OR NOT EXISTS "${_seed}" OR IS_DIRECTORY "${_seed}")
message(FATAL_ERROR "Missing absolute runtime seed: ${_seed}")
endif()
file(COPY "${_seed}"
DESTINATION "${_library_dir}"
FOLLOW_SYMLINK_CHAIN)
endforeach()
# glibc and the ELF loader define the portable ABI floor and must be supplied
# by the target host. Everything else, including libgcc_s and libstdc++, is
# resolved recursively and copied into lib/.
set(_system_dependency_regexes
"^linux-vdso\\.so\\.1$"
"^ld-linux-x86-64\\.so\\.2$"
"^libc\\.so\\.6$"
"^libm\\.so\\.6$"
"^libmvec\\.so\\.1$"
"^libdl\\.so\\.2$"
"^libpthread\\.so\\.0$"
"^librt\\.so\\.1$"
"^libresolv\\.so\\.2$"
"^libutil\\.so\\.1$"
"^libanl\\.so\\.1$"
"^libBrokenLocale\\.so\\.1$"
"^libthread_db\\.so\\.1$")
# These runtimes are explicit, compiler-derived seed files. Never let the
# resolver select a different host copy with the same SONAME through ldconfig.
set(_seed_dependency_regexes
"^libstdc\\+\\+\\.so.*$"
"^libgcc_s\\.so.*$")
file(GET_RUNTIME_DEPENDENCIES
RESOLVED_DEPENDENCIES_VAR _resolved_dependencies
UNRESOLVED_DEPENDENCIES_VAR _unresolved_dependencies
CONFLICTING_DEPENDENCIES_PREFIX _conflicts
EXECUTABLES "${BUNDLE_RESOLVER_EXECUTABLE}"
LIBRARIES ${BUNDLE_RESOLVER_LIBRARIES}
DIRECTORIES ${BUNDLE_SEARCH_DIRECTORIES}
PRE_EXCLUDE_REGEXES
${_system_dependency_regexes}
${_seed_dependency_regexes})
if(_unresolved_dependencies)
list(SORT _unresolved_dependencies)
list(JOIN _unresolved_dependencies ", " _unresolved_text)
message(FATAL_ERROR "Unresolved runtime dependencies: ${_unresolved_text}")
endif()
if(_conflicts_FILENAMES)
list(SORT _conflicts_FILENAMES)
list(JOIN _conflicts_FILENAMES ", " _conflict_text)
message(FATAL_ERROR "Conflicting runtime dependency names: ${_conflict_text}")
endif()
list(REMOVE_DUPLICATES _resolved_dependencies)
list(SORT _resolved_dependencies)
foreach(_dependency IN LISTS _resolved_dependencies)
if(NOT EXISTS "${_dependency}")
message(FATAL_ERROR "Resolved dependency disappeared: ${_dependency}")
endif()
cmake_path(GET _dependency PARENT_PATH _dependency_directory)
cmake_path(NORMAL_PATH _dependency_directory)
if(_dependency_directory STREQUAL _library_dir)
continue()
endif()
cmake_path(GET _dependency FILENAME _dependency_name)
if(EXISTS "${_library_dir}/${_dependency_name}" OR
IS_SYMLINK "${_library_dir}/${_dependency_name}")
continue()
endif()
file(COPY "${_dependency}"
DESTINATION "${_library_dir}"
FOLLOW_SYMLINK_CHAIN)
endforeach()
function(_echoion_is_elf path result_var)
if(IS_SYMLINK "${path}" OR NOT EXISTS "${path}")
set(${result_var} FALSE PARENT_SCOPE)
return()
endif()
file(READ "${path}" _magic OFFSET 0 LIMIT 4 HEX)
string(TOLOWER "${_magic}" _magic)
if(_magic STREQUAL "7f454c46")
set(${result_var} TRUE PARENT_SCOPE)
else()
set(${result_var} FALSE PARENT_SCOPE)
endif()
endfunction()
# Ensure a SONAME link exists even when CMake resolved a dependency directly to
# its real versioned file instead of the symlink used by DT_NEEDED.
file(GLOB _library_entries LIST_DIRECTORIES FALSE "${_library_dir}/*")
list(SORT _library_entries)
foreach(_entry IN LISTS _library_entries)
_echoion_is_elf("${_entry}" _is_elf)
if(NOT _is_elf)
continue()
endif()
execute_process(
COMMAND "${PATCHELF_EXECUTABLE}" --print-soname "${_entry}"
RESULT_VARIABLE _soname_result
OUTPUT_VARIABLE _soname
ERROR_VARIABLE _soname_error
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT _soname_result EQUAL 0)
message(FATAL_ERROR
"Cannot read SONAME from ${_entry}: ${_soname_error}")
endif()
if(NOT _soname STREQUAL "")
if(NOT _soname MATCHES "^[A-Za-z0-9][A-Za-z0-9._+~-]*$")
message(FATAL_ERROR "Unsafe SONAME '${_soname}' in ${_entry}")
endif()
get_filename_component(_entry_name "${_entry}" NAME)
set(_soname_path "${_library_dir}/${_soname}")
if(NOT _entry_name STREQUAL _soname
AND NOT EXISTS "${_soname_path}"
AND NOT IS_SYMLINK "${_soname_path}")
file(CREATE_LINK "${_entry_name}" "${_soname_path}" SYMBOLIC)
endif()
endif()
execute_process(
COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN" "${_entry}"
RESULT_VARIABLE _patch_result
ERROR_VARIABLE _patch_error)
if(NOT _patch_result EQUAL 0)
message(FATAL_ERROR "Cannot set RUNPATH on ${_entry}: ${_patch_error}")
endif()
endforeach()
execute_process(
COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN/../lib" "${_executable}"
RESULT_VARIABLE _patch_executable_result
ERROR_VARIABLE _patch_executable_error)
if(NOT _patch_executable_result EQUAL 0)
message(FATAL_ERROR
"Cannot set RUNPATH on ${_executable}: ${_patch_executable_error}")
endif()
list(LENGTH _resolved_dependencies _dependency_count)
message(STATUS "Bundled ${_dependency_count} resolved runtime dependencies")
+193
View File
@@ -0,0 +1,193 @@
FROM ubuntu:22.04 AS gcc-builder
ARG DEBIAN_FRONTEND=noninteractive
ARG GCC_VERSION=16.1.0
ARG GCC_SHA512=b3454958891ab47e1e5b6cb9396c0ad3b04f32fe2a7bf1153a143f21013fdb6b295ca94c98964698a688e4c1d7555ffd8ffbc20187507cce6b1c32cbcc09897a
ARG GCC_BUILD_JOBS=2
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
binutils \
bison \
build-essential \
ca-certificates \
curl \
flex \
libgmp-dev \
libisl-dev \
libmpc-dev \
libmpfr-dev \
libzstd-dev \
texinfo \
xz-utils \
zlib1g-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /tmp/gcc
RUN curl -fsSLO \
"https://ftp.gnu.org/gnu/gcc/gcc-${GCC_VERSION}/gcc-${GCC_VERSION}.tar.xz" \
&& echo "${GCC_SHA512} gcc-${GCC_VERSION}.tar.xz" | sha512sum -c - \
&& tar -xf "gcc-${GCC_VERSION}.tar.xz" \
&& mkdir build \
&& cd build \
&& "../gcc-${GCC_VERSION}/configure" \
--prefix="/opt/gcc-${GCC_VERSION}" \
--disable-bootstrap \
--disable-multilib \
--enable-default-pie \
--enable-default-ssp \
--enable-languages=c,c++ \
--with-system-zlib \
&& make -j"${GCC_BUILD_JOBS}" \
&& make install-strip \
&& install -d -m 0755 "/opt/gcc-${GCC_VERSION}/share/licenses/gcc" \
&& install -m 0644 \
"../gcc-${GCC_VERSION}/COPYING3" \
"../gcc-${GCC_VERSION}/COPYING.RUNTIME" \
"../gcc-${GCC_VERSION}/libstdc++-v3/COPYING" \
"/opt/gcc-${GCC_VERSION}/share/licenses/gcc/"
FROM ubuntu:22.04 AS release-builder
ARG DEBIAN_FRONTEND=noninteractive
ARG GCC_VERSION=16.1.0
ARG CMAKE_VERSION=4.0.3
ARG CMAKE_SHA256=585ae9e013107bc8e7c7c9ce872cbdcbdff569e675b07ef57aacfb88c886faac
ARG NODE_VERSION=22.17.0
ARG NODE_SHA256=325c0f1261e0c61bcae369a1274028e9cfb7ab7949c05512c5b1e630f7e80e12
ARG FFMPEG_VERSION=8.0.3
ARG FFMPEG_SHA256=6136812ea6d4e68bdba27e33c2a94382711cdf4f8602ffef056ff792bd6f9818
ARG FFMPEG_BUILD_JOBS=2
ARG BOOST_VERSION=1.87.0
ARG BOOST_VERSION_UNDERSCORE=1_87_0
ARG BOOST_SHA256=af57be25cb4c4f4b413ed692fe378affb4352ea50fbe294a11ef548f4d527d89
ARG BOOST_BUILD_JOBS=2
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
binutils \
bzip2 \
ca-certificates \
curl \
file \
git \
gzip \
jq \
libcurl4-openssl-dev \
libgmp10 \
libisl23 \
libmpc3 \
libmpfr6 \
libopus-dev \
libsodium-dev \
libsqlite3-dev \
libssl-dev \
libtbb-dev \
libzstd1 \
make \
nasm \
ninja-build \
patchelf \
pkg-config \
python3 \
tar \
xz-utils \
zstd \
&& rm -rf /var/lib/apt/lists/*
COPY --from=gcc-builder "/opt/gcc-${GCC_VERSION}" "/opt/gcc-${GCC_VERSION}"
RUN curl -fsSLO \
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& echo "${CMAKE_SHA256} cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" | sha256sum -c - \
&& tar -xzf "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
-C /usr/local --strip-components=1 \
&& rm "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& curl -fsSLO \
"https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \
&& echo "${NODE_SHA256} node-v${NODE_VERSION}-linux-x64.tar.xz" | sha256sum -c - \
&& tar -xJf "node-v${NODE_VERSION}-linux-x64.tar.xz" \
-C /usr/local --strip-components=1 \
&& rm "node-v${NODE_VERSION}-linux-x64.tar.xz"
ENV GCC_ROOT="/opt/gcc-${GCC_VERSION}"
ENV PATH="${GCC_ROOT}/bin:${PATH}" \
LD_LIBRARY_PATH="${GCC_ROOT}/lib64:${GCC_ROOT}/lib" \
CC="${GCC_ROOT}/bin/gcc" \
CXX="${GCC_ROOT}/bin/g++"
RUN test "$(uname -m)" = x86_64 \
&& gcc --version | grep -F "gcc (GCC) 16.1.0"
RUN curl -fsSLO \
"https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
&& echo "${FFMPEG_SHA256} ffmpeg-${FFMPEG_VERSION}.tar.xz" | sha256sum -c - \
&& tar -xJf "ffmpeg-${FFMPEG_VERSION}.tar.xz" \
&& cd "ffmpeg-${FFMPEG_VERSION}" \
&& ./configure \
--prefix="/opt/ffmpeg-${FFMPEG_VERSION}" \
--cc="${CC}" \
--cxx="${CXX}" \
--disable-static \
--enable-shared \
--disable-autodetect \
--disable-programs \
--disable-doc \
--disable-debug \
--disable-avdevice \
--disable-avfilter \
--disable-swscale \
--disable-encoders \
--disable-muxers \
--disable-hwaccels \
--enable-openssl \
&& make -j"${FFMPEG_BUILD_JOBS}" \
&& make install \
&& install -D -m 0644 COPYING.LGPLv2.1 \
"/opt/ffmpeg-${FFMPEG_VERSION}/share/licenses/ffmpeg/COPYING.LGPLv2.1" \
&& cd / \
&& rm -rf \
"ffmpeg-${FFMPEG_VERSION}" \
"ffmpeg-${FFMPEG_VERSION}.tar.xz"
ENV FFMPEG_ROOT="/opt/ffmpeg-${FFMPEG_VERSION}" \
PKG_CONFIG_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib/pkgconfig" \
LD_LIBRARY_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib:${LD_LIBRARY_PATH}"
RUN test "$(pkg-config --modversion libavcodec)" = 62.11.103 \
&& test "$(pkg-config --modversion libavformat)" = 62.3.103 \
&& test "$(pkg-config --modversion libavutil)" = 60.8.103 \
&& test "$(pkg-config --modversion libswresample)" = 6.1.103
RUN curl -fsSLO \
"https://archives.boost.io/release/${BOOST_VERSION}/source/boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \
&& echo "${BOOST_SHA256} boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" | sha256sum -c - \
&& tar -xjf "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \
&& cd "boost_${BOOST_VERSION_UNDERSCORE}" \
&& ./bootstrap.sh --prefix="/opt/boost-${BOOST_VERSION}" \
&& ./b2 -j"${BOOST_BUILD_JOBS}" \
cxxstd=23 \
link=shared \
runtime-link=shared \
threading=multi \
variant=release \
--with-container \
--with-stacktrace \
--with-system \
--with-thread \
--with-url \
install \
&& install -D -m 0644 \
LICENSE_1_0.txt \
"/opt/boost-${BOOST_VERSION}/share/licenses/boost/LICENSE_1_0.txt" \
&& cd / \
&& rm -rf \
"boost_${BOOST_VERSION_UNDERSCORE}" \
"boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2"
ENV BOOST_ROOT="/opt/boost-${BOOST_VERSION}" \
CMAKE_PREFIX_PATH="/opt/boost-${BOOST_VERSION}:${FFMPEG_ROOT}" \
LD_LIBRARY_PATH="/opt/boost-${BOOST_VERSION}/lib:${LD_LIBRARY_PATH}"
WORKDIR /workspace
+25
View File
@@ -0,0 +1,25 @@
# Linux installer layout
`install.sh` and `uninstall.sh` are copied into each Linux release payload.
`service/echoion.service.in` is rendered by the installer for user or system
systemd scope. `tests/installer_test.sh` exercises portable installation,
service opt-in, rollback, tamper protection, preservation, and purge behavior.
System-scoped payloads are normalized to root ownership. Registered-service
prefixes require a trusted path not writable by other identities. Purge uses
recorded directory identity plus an installer marker before removing custom
mutable paths.
Install and uninstall also take a nonblocking advisory lock on the prefix
directory so concurrent lifecycle operations fail before changing the runtime.
Self-contained portable installs add a managed `echoion` launcher and relative
install metadata, allowing a service-free tree to be moved and uninstalled as
one directory.
Create publishable artifacts from the repository root:
```bash
scripts/release.sh --version 1.2.3
```
The default command uses the version-pinned release toolchain container and
does not start the bot. Installation flags and data layouts are documented in
the root README.
+1351
View File
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
[Unit]
Description=Echoion Music Bot
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
@SERVICE_IDENTITY@
@WORKING_DIRECTORY@
@ENVIRONMENT_HOME@
@ENVIRONMENT_CORE@
@ENVIRONMENT_STATE@
@EXEC_START@
Restart=on-failure
RestartSec=5s
LimitNOFILE=65536
UMask=0077
[Install]
@INSTALL_TARGET@
+551
View File
@@ -0,0 +1,551 @@
#!/usr/bin/env bash
# shellcheck disable=SC1091,SC2034,SC2329
set -euo pipefail
SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
PACKAGING_DIR=$(cd -P -- "$SCRIPT_DIR/.." && pwd -P)
TEST_ROOT=$(mktemp -d -- "$SCRIPT_DIR/.installer-test.XXXXXX")
trap 'rm -rf -- "$TEST_ROOT"' EXIT
fail() {
printf 'FAIL: %s\n' "$*" >&2
exit 1
}
assert_file() {
[[ -f $1 ]] || fail "missing file: $1"
}
assert_not_exists() {
[[ ! -e $1 ]] || fail "unexpected path: $1"
}
assert_contains() {
local path=$1
local text=$2
grep -F -- "$text" "$path" >/dev/null || fail "$path does not contain: $text"
}
assert_not_contains() {
local path=$1
local text=$2
if grep -F -- "$text" "$path" >/dev/null; then
fail "$path unexpectedly contains: $text"
fi
}
make_payload() {
local root=$1
install -d -- "$root/bin" "$root/lib" "$root/share/echoion/web" "$root/service"
install -m 0755 -- "$PACKAGING_DIR/install.sh" "$root/install.sh"
install -m 0755 -- "$PACKAGING_DIR/uninstall.sh" "$root/uninstall.sh"
install -m 0644 -- "$PACKAGING_DIR/service/echoion.service.in" "$root/service/echoion.service.in"
cat > "$root/manifest.json" <<'EOF'
{
"schemaVersion": 2,
"version": "1.2.3",
"files": [
{"path": "bin/echoiond"}
]
}
EOF
cat > "$root/bin/echoiond" <<'EOF'
#!/usr/bin/env bash
if [[ ${1:-} == --validate-install && -n ${2:-} ]]; then
printf '%s\n' "$2" >> "${VALIDATOR_LOG:?}"
if [[ -n ${VALIDATOR_FAIL_PATH:-} && $2 == "$VALIDATOR_FAIL_PATH" ]]; then
exit 1
fi
exit 0
fi
if [[ ${ALLOW_DAEMON_RUN:-0} == 1 ]]; then
printf 'ECHOION_HOME=%s\n' "${ECHOION_HOME:-}" >> "${DAEMON_LOG:?}"
printf 'ECHOION_CORE_PATH=%s\n' "${ECHOION_CORE_PATH:-}" >> "$DAEMON_LOG"
printf 'ECHOION_STATE_DIR=%s\n' "${ECHOION_STATE_DIR:-}" >> "$DAEMON_LOG"
argument_index=0
for argument in "$@"; do
printf 'ARG_%d=%s\n' "$argument_index" "$argument" >> "$DAEMON_LOG"
argument_index=$((argument_index + 1))
done
exit 0
fi
printf 'daemon unexpectedly ran\n' >> "${DAEMON_LOG:?}"
exit 1
EOF
chmod 0755 "$root/bin/echoiond"
printf 'fake dynamic core\n' > "$root/lib/Echoion.ts"
cat > "$root/share/echoion/config.example.json" <<'EOF'
{
"web": {
"webRoot": "./web",
"enabled": false
}
}
EOF
printf '<!doctype html>\n' > "$root/share/echoion/web/index.html"
}
fake_bin=$TEST_ROOT/fake-bin
home=$TEST_ROOT/home
install -d -- "$fake_bin" "$home"
REAL_MV=$(command -v mv)
export REAL_MV
cat > "$fake_bin/systemctl" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$*" >> "${SYSTEMCTL_LOG:?}"
if [[ ${SYSTEMCTL_FAIL_RESTART:-0} == 1 && " $* " == *' restart '* ]]; then
exit 1
fi
exit 0
EOF
chmod 0755 "$fake_bin/systemctl"
cat > "$fake_bin/mv" <<'EOF'
#!/usr/bin/env bash
last=
for last in "$@"; do :; done
if [[ ${RECORD_COMMIT_FAIL:-0} == 1 && ${last##*/} == .echoion-install ]]; then
exit 73
fi
exec "${REAL_MV:?}" "$@"
EOF
chmod 0755 "$fake_bin/mv"
export PATH=$fake_bin:$PATH
export HOME=$home
export XDG_CONFIG_HOME=$home/.config
export XDG_STATE_HOME=$home/.state
export SYSTEMCTL_LOG=$TEST_ROOT/systemctl.log
export DAEMON_LOG=$TEST_ROOT/daemon.log
export VALIDATOR_LOG=$TEST_ROOT/validator.log
: > "$SYSTEMCTL_LOG"
: > "$DAEMON_LOG"
: > "$VALIDATOR_LOG"
bash -n "$PACKAGING_DIR/install.sh"
bash -n "$PACKAGING_DIR/uninstall.sh"
trusted_parent=$TEST_ROOT/trusted-parent
trusted_prefix=$trusted_parent/echoion
install -d -m 0700 -- "$trusted_prefix"
(
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
validate_trusted_path_ancestors user "$trusted_prefix" "$(id -u)" 1
) || fail 'trusted user service prefix was rejected'
chmod 0770 "$trusted_parent"
if (
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
validate_trusted_path_ancestors user "$trusted_prefix" "$(id -u)" 1
) >/dev/null 2>&1; then
fail 'group-writable service prefix ancestor was accepted'
fi
chmod 0700 "$trusted_parent"
if (
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
validate_trusted_path_ancestors system "$trusted_prefix" 0 1
) >/dev/null 2>&1; then
fail 'non-root-owned system service prefix was accepted'
fi
if (
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
validate_registration_identity user 0
) >/dev/null 2>&1; then
fail 'root user-scope service registration was accepted'
fi
CHOWN_LOG=$TEST_ROOT/chown.log
export CHOWN_LOG
(
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
chown() { printf '%s\n' "$*" >> "$CHOWN_LOG"; }
find() { return 0; }
runuser() {
[[ " $* " == *' test -w '* ]] && return 1
return 0
}
normalize_and_validate_system_runtime "$trusted_prefix"
)
assert_contains "$CHOWN_LOG" '-R root:root'
USERDEL_LOG=$TEST_ROOT/userdel.log
export USERDEL_LOG
(
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
ACCOUNT_CREATED_THIS_RUN=1
ACCOUNT_IDENTITY_CAPTURED=1
SERVICE_UID=4242
SERVICE_GID=4343
MOCK_UID=4242
MOCK_GID=4343
id() {
case $1 in
-u) printf '%s\n' "$MOCK_UID" ;;
-g) printf '%s\n' "$MOCK_GID" ;;
esac
}
userdel() { printf '%s\n' "$*" >> "$USERDEL_LOG"; }
remove_new_system_user
)
assert_contains "$USERDEL_LOG" 'echoion'
: > "$USERDEL_LOG"
(
# shellcheck source=../install.sh
source "$PACKAGING_DIR/install.sh"
ACCOUNT_CREATED_THIS_RUN=1
ACCOUNT_IDENTITY_CAPTURED=1
SERVICE_UID=4242
SERVICE_GID=4343
MOCK_UID=9999
MOCK_GID=4343
id() {
case $1 in
-u) printf '%s\n' "$MOCK_UID" ;;
-g) printf '%s\n' "$MOCK_GID" ;;
esac
}
userdel() { printf '%s\n' "$*" >> "$USERDEL_LOG"; }
remove_new_system_user
) 2>/dev/null
[[ ! -s $USERDEL_LOG ]] || fail 'recreated service account was deleted'
symlink_prefix=$TEST_ROOT/symlink-versions
install -d -- "$symlink_prefix" "$TEST_ROOT/external-versions"
ln -s -- "$TEST_ROOT/external-versions" "$symlink_prefix/versions"
payload=$TEST_ROOT/payload
make_payload "$payload"
locked_prefix=$TEST_ROOT/locked-prefix
install -d -- "$locked_prefix"
exec {TEST_LOCK_FD}< "$locked_prefix"
flock -n "$TEST_LOCK_FD"
if "$payload/install.sh" --mode portable --prefix "$locked_prefix" \
--register-service none --non-interactive >/dev/null 2>&1; then
fail 'concurrent installer acquired an already-held prefix lock'
fi
flock -u "$TEST_LOCK_FD"
exec {TEST_LOCK_FD}<&-
assert_not_exists "$locked_prefix/versions/1.2.3"
metadata_prefix=$TEST_ROOT/metadata-rollback
metadata_config=$TEST_ROOT/metadata-config
metadata_state=$TEST_ROOT/metadata-state
install -d -m 0750 -- "$metadata_config"
install -d -m 0710 -- "$metadata_state"
printf '{}\n' > "$metadata_config/config.json"
chmod 0640 "$metadata_config/config.json"
config_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config")
state_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_state")
file_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json")
export VALIDATOR_FAIL_PATH=$metadata_prefix/versions/1.2.3
if "$payload/install.sh" --mode portable --prefix "$metadata_prefix" \
--config-dir "$metadata_config" --state-dir "$metadata_state" \
--register-service none --non-interactive >/dev/null 2>&1; then
fail 'installer accepted injected post-metadata validation failure'
fi
unset VALIDATOR_FAIL_PATH
config_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config")
state_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_state")
file_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json")
[[ $config_metadata_after == "$config_metadata_before" ]] ||
fail 'failed install did not restore configuration directory uid/gid/mode'
[[ $state_metadata_after == "$state_metadata_before" ]] ||
fail 'failed install did not restore state directory uid/gid/mode'
[[ $file_metadata_after == "$file_metadata_before" ]] ||
fail 'failed install did not restore configuration file uid/gid/mode'
assert_not_exists "$metadata_prefix/versions/1.2.3"
runtime_root=$TEST_ROOT/runtime-directory
install -d -m 0700 -- "$runtime_root"
if XDG_RUNTIME_DIR=$runtime_root "$payload/install.sh" --mode portable \
--prefix "$runtime_root/echoion" --register-service user \
--non-interactive >/dev/null 2>&1; then
fail 'XDG runtime portable service prefix was accepted'
fi
unsafe_mutable_parent=$TEST_ROOT/group-writable-mutable
install -d -m 0770 -- "$unsafe_mutable_parent"
if "$payload/install.sh" --mode portable --prefix "$TEST_ROOT/mutable-trust-install" \
--config-dir "$unsafe_mutable_parent/config" \
--state-dir "$TEST_ROOT/mutable-trust-state" --register-service user \
--non-interactive >/dev/null 2>&1; then
fail 'group-writable mutable-path ancestor was accepted for a service'
fi
if "$payload/install.sh" --mode portable --prefix "$symlink_prefix" \
--register-service none --non-interactive >/dev/null 2>&1; then
fail 'symlinked versions directory was accepted'
fi
bad_payload=$TEST_ROOT/bad-payload
make_payload "$bad_payload"
sed -i 's/"schemaVersion": 2/"schemaVersion": 1/' "$bad_payload/manifest.json"
if "$bad_payload/install.sh" --mode portable --prefix "$TEST_ROOT/bad-install" \
--register-service none --non-interactive >/dev/null 2>&1; then
fail 'legacy payload manifest was accepted'
fi
self_prefix=$TEST_ROOT/self-contained
"$payload/install.sh" --mode portable --prefix "$self_prefix" \
--data-layout self-contained --register-service none --non-interactive
[[ $(readlink -- "$self_prefix/current") == versions/1.2.3 ]] || fail 'wrong current target'
assert_file "$self_prefix/versions/1.2.3/bin/echoiond"
assert_file "$self_prefix/config/config.json"
[[ -x $self_prefix/echoion ]] || fail 'portable launcher is not executable'
assert_contains "$self_prefix/.echoion-install" 'relocatable=1'
assert_contains "$self_prefix/.echoion-install" 'prefix=.'
assert_contains "$self_prefix/.echoion-install" 'config_dir=config'
assert_contains "$self_prefix/.echoion-install" 'state_dir=data'
assert_contains "$self_prefix/.echoion-install" 'launcher=echoion'
assert_contains "$self_prefix/config/config.json" '"webRoot": "./web"'
assert_not_contains "$self_prefix/config/config.json" "$self_prefix/current"
[[ ! -s $SYSTEMCTL_LOG ]] || fail 'service command ran for register-service none'
[[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during installation'
assert_contains "$VALIDATOR_LOG" "$self_prefix/versions/1.2.3"
self_moved_prefix=$TEST_ROOT/self-contained-moved
mv -- "$self_prefix" "$self_moved_prefix"
assert_not_exists "$self_prefix"
: > "$DAEMON_LOG"
ALLOW_DAEMON_RUN=1 "$self_moved_prefix/echoion" --probe 'two words'
assert_contains "$DAEMON_LOG" "ECHOION_HOME=$self_moved_prefix/current"
assert_contains "$DAEMON_LOG" "ECHOION_CORE_PATH=$self_moved_prefix/current/lib/Echoion.ts"
assert_contains "$DAEMON_LOG" "ECHOION_STATE_DIR=$self_moved_prefix/data"
assert_contains "$DAEMON_LOG" 'ARG_0=--config'
assert_contains "$DAEMON_LOG" "ARG_1=$self_moved_prefix/config/config.json"
assert_contains "$DAEMON_LOG" 'ARG_2=--state-dir'
assert_contains "$DAEMON_LOG" "ARG_3=$self_moved_prefix/data"
assert_contains "$DAEMON_LOG" 'ARG_4=--probe'
assert_contains "$DAEMON_LOG" 'ARG_5=two words'
: > "$DAEMON_LOG"
if ALLOW_DAEMON_RUN=1 "$self_moved_prefix/echoion" --config /tmp/override \
>/dev/null 2>&1; then
fail 'portable launcher accepted a managed config override'
fi
[[ ! -s $DAEMON_LOG ]] || fail 'portable launcher executed daemon after rejected override'
"$self_moved_prefix/uninstall.sh" --purge --non-interactive >/dev/null
assert_not_exists "$self_moved_prefix"
dots_prefix=$TEST_ROOT/consecutive-dot-version
dots_payload=$TEST_ROOT/consecutive-dot-payload
dots_upgrade_payload=$TEST_ROOT/consecutive-dot-upgrade-payload
cp -a -- "$payload" "$dots_payload"
sed -i 's/"version": "1.2.3"/"version": "1.0..rc1"/' "$dots_payload/manifest.json"
cp -a -- "$dots_payload" "$dots_upgrade_payload"
sed -i 's/"version": "1.0..rc1"/"version": "1.0..rc2"/' \
"$dots_upgrade_payload/manifest.json"
"$dots_payload/install.sh" --mode portable --prefix "$dots_prefix" \
--data-layout self-contained --register-service none --non-interactive >/dev/null
"$dots_upgrade_payload/install.sh" --mode portable --prefix "$dots_prefix" \
--data-layout self-contained --register-service none --non-interactive >/dev/null
[[ $(readlink -- "$dots_prefix/current") == versions/1.0..rc2 ]] ||
fail 'legal consecutive-dot version did not upgrade'
"$dots_prefix/uninstall.sh" --purge --non-interactive >/dev/null
assert_not_exists "$dots_prefix"
custom_prefix=$TEST_ROOT/custom-purge-install
custom_config=$TEST_ROOT/custom-configuration
custom_state=$TEST_ROOT/custom-runtime-state
"$payload/install.sh" --mode portable --prefix "$custom_prefix" \
--config-dir "$custom_config" --state-dir "$custom_state" \
--register-service none --non-interactive >/dev/null
assert_file "$custom_config/.echoion-managed"
assert_file "$custom_state/.echoion-managed"
assert_contains "$custom_prefix/.echoion-install" 'config_purge_allowed=1'
assert_contains "$custom_prefix/.echoion-install" 'state_purge_allowed=1'
exec {TEST_LOCK_FD}< "$custom_prefix"
flock -n "$TEST_LOCK_FD"
if "$custom_prefix/uninstall.sh" --purge --non-interactive >/dev/null 2>&1; then
fail 'concurrent uninstaller acquired an already-held prefix lock'
fi
assert_file "$custom_prefix/current/bin/echoiond"
flock -u "$TEST_LOCK_FD"
exec {TEST_LOCK_FD}<&-
"$custom_prefix/uninstall.sh" --purge --non-interactive >/dev/null
assert_not_exists "$custom_prefix"
assert_not_exists "$custom_config"
assert_not_exists "$custom_state"
service_prefix="$TEST_ROOT/portable path % dollar\$"
: > "$SYSTEMCTL_LOG"
"$payload/install.sh" --mode portable --prefix "$service_prefix" \
--data-layout standard --register-service user --non-interactive
unit=$XDG_CONFIG_HOME/systemd/user/echoion.service
assert_file "$unit"
assert_contains "$unit" 'WorkingDirectory="'
assert_contains "$unit" 'portable path %% dollar$/current"'
assert_contains "$unit" 'ExecStart="'
assert_contains "$unit" 'portable path %% dollar$$/current/bin/echoiond"'
assert_contains "$unit" 'Environment="ECHOION_HOME='
assert_contains "$unit" 'Environment="ECHOION_CORE_PATH='
assert_contains "$unit" 'Environment="ECHOION_STATE_DIR='
assert_contains "$unit" '--config "'
assert_contains "$unit" '--state-dir "'
if grep -E '@[A-Z_]+@' "$unit" >/dev/null; then
fail 'generated systemd unit contains an unresolved template marker'
fi
if command -v systemd-analyze >/dev/null 2>&1; then
verify_log=$TEST_ROOT/systemd-verify.log
if ! systemd-analyze verify "$unit" 2> "$verify_log" &&
grep -E 'echoion\.service:|Failed to load unit' "$verify_log" >/dev/null; then
cat "$verify_log" >&2
fail 'generated systemd unit did not verify'
fi
fi
assert_contains "$SYSTEMCTL_LOG" '--user daemon-reload'
assert_contains "$SYSTEMCTL_LOG" '--user disable --now echoion.service'
if grep -E -- '(^| )enable( |$)|(^| )restart( |$)' "$SYSTEMCTL_LOG" >/dev/null; then
fail 'service was activated without --start'
fi
[[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during service registration'
: > "$SYSTEMCTL_LOG"
"$payload/install.sh" --mode portable --prefix "$service_prefix" \
--data-layout standard --register-service user --start --non-interactive
assert_contains "$SYSTEMCTL_LOG" '--user enable echoion.service'
assert_contains "$SYSTEMCTL_LOG" '--user restart echoion.service'
assert_contains "$SYSTEMCTL_LOG" '--user is-active --quiet echoion.service'
: > "$SYSTEMCTL_LOG"
"$service_prefix/uninstall.sh" --non-interactive
assert_not_exists "$unit"
assert_not_exists "$service_prefix/versions"
assert_file "$XDG_CONFIG_HOME/echoion/config.json"
[[ -d $XDG_STATE_HOME/echoion ]] || fail 'state directory was not preserved'
purge_retry_prefix=$TEST_ROOT/purge-retry
purge_retry_config=$TEST_ROOT/purge-retry-config
purge_retry_state=$TEST_ROOT/purge-retry-state
"$payload/install.sh" --mode portable --prefix "$purge_retry_prefix" \
--config-dir "$purge_retry_config" --state-dir "$purge_retry_state" \
--register-service user --non-interactive >/dev/null
marker_backup=$TEST_ROOT/config-marker.backup
cp -a -- "$purge_retry_config/.echoion-managed" "$marker_backup"
printf 'tampered\n' >> "$purge_retry_config/.echoion-managed"
if "$purge_retry_prefix/uninstall.sh" --purge --non-interactive >/dev/null 2>&1; then
fail 'purge accepted a modified ownership marker'
fi
assert_file "$unit"
assert_file "$purge_retry_prefix/current/bin/echoiond"
assert_file "$purge_retry_prefix/.echoion-install"
cp -a -- "$marker_backup" "$purge_retry_config/.echoion-managed"
"$purge_retry_prefix/uninstall.sh" --purge --non-interactive >/dev/null
assert_not_exists "$unit"
assert_not_exists "$purge_retry_prefix"
assert_not_exists "$purge_retry_config"
assert_not_exists "$purge_retry_state"
rollback_prefix=$TEST_ROOT/rollback
"$payload/install.sh" --mode portable --prefix "$rollback_prefix" \
--register-service user --non-interactive >/dev/null
old_unit_hash=$(sha256sum -- "$unit")
old_unit_hash=${old_unit_hash%% *}
upgrade_payload=$TEST_ROOT/upgrade-payload
cp -a -- "$payload" "$upgrade_payload"
sed -i 's/"version": "1.2.3"/"version": "1.2.4"/' "$upgrade_payload/manifest.json"
printf '# changed in 1.2.4\n' >> "$upgrade_payload/service/echoion.service.in"
printf '# changed installer helper in 1.2.4\n' >> "$upgrade_payload/install.sh"
printf '# changed uninstaller helper in 1.2.4\n' >> "$upgrade_payload/uninstall.sh"
export SYSTEMCTL_FAIL_RESTART=1
if "$upgrade_payload/install.sh" --mode portable --prefix "$rollback_prefix" \
--register-service user --start --non-interactive >/dev/null 2>&1; then
fail 'installer accepted a failed service restart'
fi
unset SYSTEMCTL_FAIL_RESTART
[[ $(readlink -- "$rollback_prefix/current") == versions/1.2.3 ]] ||
fail 'failed service upgrade did not restore current'
restored_unit_hash=$(sha256sum -- "$unit")
restored_unit_hash=${restored_unit_hash%% *}
[[ $restored_unit_hash == "$old_unit_hash" ]] || fail 'failed upgrade did not restore unit bytes'
assert_contains "$rollback_prefix/.echoion-install" 'version=1.2.3'
"$rollback_prefix/uninstall.sh" --non-interactive >/dev/null
record_rollback_prefix=$TEST_ROOT/record-rollback
"$payload/install.sh" --mode portable --prefix "$record_rollback_prefix" \
--register-service user --non-interactive >/dev/null
record_old_unit_hash=$(sha256sum -- "$unit")
record_old_unit_hash=${record_old_unit_hash%% *}
record_old_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh")
record_old_install_hash=${record_old_install_hash%% *}
record_old_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh")
record_old_uninstall_hash=${record_old_uninstall_hash%% *}
export RECORD_COMMIT_FAIL=1
if "$upgrade_payload/install.sh" --mode portable --prefix "$record_rollback_prefix" \
--register-service user --non-interactive >/dev/null 2>&1; then
fail 'installer accepted a failed atomic record commit'
fi
unset RECORD_COMMIT_FAIL
[[ $(readlink -- "$record_rollback_prefix/current") == versions/1.2.3 ]] ||
fail 'record-commit failure did not restore current'
record_restored_unit_hash=$(sha256sum -- "$unit")
record_restored_unit_hash=${record_restored_unit_hash%% *}
[[ $record_restored_unit_hash == "$record_old_unit_hash" ]] ||
fail 'record-commit failure did not restore unit bytes'
assert_contains "$record_rollback_prefix/.echoion-install" 'version=1.2.3'
assert_not_exists "$record_rollback_prefix/versions/1.2.4"
record_restored_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh")
record_restored_install_hash=${record_restored_install_hash%% *}
record_restored_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh")
record_restored_uninstall_hash=${record_restored_uninstall_hash%% *}
[[ $record_restored_install_hash == "$record_old_install_hash" ]] ||
fail 'record-commit failure did not restore installer helper bytes'
[[ $record_restored_uninstall_hash == "$record_old_uninstall_hash" ]] ||
fail 'record-commit failure did not restore uninstaller helper bytes'
"$record_rollback_prefix/uninstall.sh" --non-interactive >/dev/null
scope_rollback_prefix=$TEST_ROOT/scope-rollback
"$payload/install.sh" --mode portable --prefix "$scope_rollback_prefix" \
--register-service user --non-interactive >/dev/null
scope_old_unit_hash=$(sha256sum -- "$unit")
scope_old_unit_hash=${scope_old_unit_hash%% *}
export RECORD_COMMIT_FAIL=1
if "$upgrade_payload/install.sh" --mode portable --prefix "$scope_rollback_prefix" \
--register-service none --non-interactive >/dev/null 2>&1; then
fail 'scope migration accepted a failed record commit'
fi
unset RECORD_COMMIT_FAIL
assert_file "$unit"
scope_restored_unit_hash=$(sha256sum -- "$unit")
scope_restored_unit_hash=${scope_restored_unit_hash%% *}
[[ $scope_restored_unit_hash == "$scope_old_unit_hash" ]] ||
fail 'scope migration failure did not restore old unit bytes'
[[ $(readlink -- "$scope_rollback_prefix/current") == versions/1.2.3 ]] ||
fail 'scope migration failure did not restore current'
assert_contains "$scope_rollback_prefix/.echoion-install" 'service_scope=user'
"$scope_rollback_prefix/uninstall.sh" --non-interactive >/dev/null
tamper_prefix=$TEST_ROOT/tamper
"$payload/install.sh" --mode portable --prefix "$tamper_prefix" \
--register-service user --non-interactive >/dev/null
printf '# local change\n' >> "$unit"
if "$tamper_prefix/uninstall.sh" --non-interactive >/dev/null 2>&1; then
fail 'uninstaller removed a modified unit'
fi
assert_file "$unit"
rm -f -- "$unit"
if "$payload/install.sh" --mode portable --prefix "/tmp/echoion-installer-test-$$" \
--register-service user --non-interactive >/dev/null 2>&1; then
fail 'temporary portable service prefix was accepted'
fi
unsafe_mutable_prefix=$TEST_ROOT/unsafe-mutable/install
if "$payload/install.sh" --mode portable --prefix "$unsafe_mutable_prefix" \
--config-dir "$TEST_ROOT/unsafe-mutable" --register-service none \
--non-interactive >/dev/null 2>&1; then
fail 'mutable directory containing the install prefix was accepted'
fi
in_place=$TEST_ROOT/in-place
make_payload "$in_place"
"$in_place/install.sh" --mode portable --prefix "$in_place" \
--data-layout self-contained --register-service none --non-interactive >/dev/null
assert_file "$in_place/versions/1.2.3/bin/echoiond"
assert_not_exists "$in_place/bin"
[[ $(readlink -- "$in_place/current") == versions/1.2.3 ]] || fail 'in-place current target is wrong'
printf 'installer tests passed\n'
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env bash
set -euo pipefail
PROGRAM=${0##*/}
SERVICE_NAME=echoion.service
SERVICE_USER=echoion
RECORD_NAME=.echoion-install
MANAGED_MARKER=.echoion-managed
die() {
printf '%s: %s\n' "$PROGRAM" "$*" >&2
exit 1
}
warn() {
printf '%s: warning: %s\n' "$PROGRAM" "$*" >&2
}
usage() {
cat <<'EOF'
Usage: uninstall.sh [--purge] [--non-interactive]
Remove the Echoion runtime and its matching registered service. Configuration
and state are preserved unless --purge is explicitly supplied.
EOF
}
sha256_file() {
local result
result=$(sha256sum -- "$1")
printf '%s\n' "${result%% *}"
}
systemctl_for() {
local scope=$1
shift
if [[ $scope == user ]]; then
systemctl --user "$@"
else
systemctl "$@"
fi
}
acquire_prefix_lock() {
local lock_prefix=$1
command -v flock >/dev/null 2>&1 || die "flock is required for safe uninstallation"
exec {UNINSTALL_LOCK_FD}< "$lock_prefix"
flock -n "$UNINSTALL_LOCK_FD" || die "another Echoion install or uninstall is active for '$lock_prefix'"
}
safe_unit_path() {
local scope=$1
local unit=$2
[[ $unit == /* && $unit != *'/../'* && $unit != *'/./'* ]] || return 1
case $scope:$unit in
system:/etc/systemd/system/echoion.service) return 0 ;;
user:/*/systemd/user/echoion.service) return 0 ;;
*) return 1 ;;
esac
}
safe_purge_path() {
local path=$1
local prefix=$2
[[ $path == /* && $path != / ]] || return 1
local relative=${path#/}
[[ $relative == */* ]] || return 1
case $path in
/etc | /var | /home | /root | /usr | /usr/local | /opt | /tmp | /var/tmp | /run)
return 1
;;
esac
case $path in
"$prefix" | "$prefix/current" | "$prefix/current"/* | "$prefix/versions" | "$prefix/versions"/*)
return 1
;;
esac
return 0
}
validate_managed_purge_path() {
local kind=$1
local path=$2
local safety_prefix=$3
local marker_prefix=$4
local install_id=$5
local allowed=$6
local expected_device=$7
local expected_inode=$8
local expected_uid=$9
local expected_gid=${10}
local expected_hash=${11}
local marker=$path/$MANAGED_MARKER
local device inode uid gid
[[ $allowed == 1 ]] || die "$kind directory is not marked as installer-owned: '$path'"
safe_purge_path "$path" "$safety_prefix" || die "refusing unsafe purge path '$path'"
if [[ ! -e $path && ! -L $path ]]; then
return 0
fi
[[ -d $path && ! -L $path ]] || die "$kind purge path is not a real directory: '$path'"
[[ $expected_device =~ ^[0-9]+$ && $expected_inode =~ ^[0-9]+$ &&
$expected_uid =~ ^[0-9]+$ && $expected_gid =~ ^[0-9]+$ && -n $expected_hash ]] ||
die "$kind purge identity is incomplete"
device=$(stat -c '%d' -- "$path")
inode=$(stat -c '%i' -- "$path")
uid=$(stat -c '%u' -- "$path")
gid=$(stat -c '%g' -- "$path")
[[ $device == "$expected_device" && $inode == "$expected_inode" &&
$uid == "$expected_uid" && $gid == "$expected_gid" ]] ||
die "$kind directory identity changed; refusing purge: '$path'"
[[ -f $marker && ! -L $marker ]] || die "$kind ownership marker is missing: '$marker'"
[[ $(sha256_file "$marker") == "$expected_hash" ]] ||
die "$kind ownership marker changed: '$marker'"
grep -Fx -- "install_id=$install_id" "$marker" >/dev/null ||
die "$kind ownership marker has the wrong install identity"
grep -Fx -- "prefix=$marker_prefix" "$marker" >/dev/null ||
die "$kind ownership marker belongs to another prefix"
}
purge=0
while [[ $# -gt 0 ]]; do
case $1 in
--purge) purge=1 ;;
--non-interactive) ;;
-h | --help)
usage
exit 0
;;
*) die "unknown option: $1" ;;
esac
shift
done
SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
prefix=$SCRIPT_DIR
[[ $prefix != / ]] || die "refusing to uninstall from the filesystem root"
acquire_prefix_lock "$prefix"
record=$prefix/$RECORD_NAME
[[ -f $record ]] || die "install record is missing: $record"
record_prefix=
relocatable=0
service_scope=none
service_unit=
service_unit_sha256=
config_dir=
state_dir=
mode=
data_layout=
launcher=
launcher_sha256=
created_system_user=0
service_uid=
service_gid=
install_id=
config_purge_allowed=0
config_dir_device=
config_dir_inode=
config_dir_uid=
config_dir_gid=
config_marker_sha256=
state_purge_allowed=0
state_dir_device=
state_dir_inode=
state_dir_uid=
state_dir_gid=
state_marker_sha256=
key=
value=
while IFS='=' read -r key value; do
case $key in
prefix) record_prefix=$value ;;
relocatable) relocatable=$value ;;
service_scope) service_scope=$value ;;
service_unit) service_unit=$value ;;
service_unit_sha256) service_unit_sha256=$value ;;
config_dir) config_dir=$value ;;
state_dir) state_dir=$value ;;
mode) mode=$value ;;
data_layout) data_layout=$value ;;
launcher) launcher=$value ;;
launcher_sha256) launcher_sha256=$value ;;
created_system_user) created_system_user=$value ;;
service_uid) service_uid=$value ;;
service_gid) service_gid=$value ;;
install_id) install_id=$value ;;
config_purge_allowed) config_purge_allowed=$value ;;
config_dir_device) config_dir_device=$value ;;
config_dir_inode) config_dir_inode=$value ;;
config_dir_uid) config_dir_uid=$value ;;
config_dir_gid) config_dir_gid=$value ;;
config_marker_sha256) config_marker_sha256=$value ;;
state_purge_allowed) state_purge_allowed=$value ;;
state_dir_device) state_dir_device=$value ;;
state_dir_inode) state_dir_inode=$value ;;
state_dir_uid) state_dir_uid=$value ;;
state_dir_gid) state_dir_gid=$value ;;
state_marker_sha256) state_marker_sha256=$value ;;
esac
done < "$record"
case $relocatable in
0)
[[ $record_prefix == "$prefix" ]] ||
die "install record belongs to '$record_prefix', not '$prefix'"
;;
1)
[[ $record_prefix == . && $mode == portable && $data_layout == self-contained ]] ||
die "relocatable install record is incomplete or unsafe"
[[ $config_dir == config && $state_dir == data ]] ||
die "relocatable install record has unsafe mutable paths"
config_dir=$prefix/config
state_dir=$prefix/data
;;
*) die "install record has an invalid relocatable value" ;;
esac
case $service_scope in
none | user | system) ;;
*) die "install record has an invalid service scope" ;;
esac
case $created_system_user in
0 | 1) ;;
*) die "install record has an invalid created_system_user value" ;;
esac
if [[ $service_scope == system || $mode == system || $created_system_user == 1 ]]; then
[[ ${EUID:-$(id -u)} -eq 0 ]] || die "uninstalling the system service requires root"
fi
# Complete every destructive preflight before stopping the service or removing
# any files, so a refused purge leaves the installation fully retryable.
if [[ $service_scope != none ]]; then
[[ -n $service_unit && -n $service_unit_sha256 ]] || die "service record is incomplete"
safe_unit_path "$service_scope" "$service_unit" || die "service record has an unsafe unit path"
[[ -f $service_unit ]] || die "registered service unit is missing: $service_unit"
[[ $(sha256_file "$service_unit") == "$service_unit_sha256" ]] ||
die "service unit was modified; refusing to remove it: $service_unit"
fi
launcher_path=
if [[ -n $launcher ]]; then
[[ $launcher == echoion && $launcher_sha256 =~ ^[0-9a-f]{64}$ ]] ||
die "portable launcher record is incomplete or unsafe"
launcher_path=$prefix/$launcher
[[ -f $launcher_path && ! -L $launcher_path && -x $launcher_path ]] ||
die "recorded portable launcher is missing or unsafe: $launcher_path"
[[ $(sha256_file "$launcher_path") == "$launcher_sha256" ]] ||
die "portable launcher was modified; refusing to remove it: $launcher_path"
elif [[ -n $launcher_sha256 ]]; then
die "portable launcher record is incomplete"
fi
if [[ -e $prefix/current && ! -L $prefix/current ]]; then
die "current is not a symlink; refusing to remove runtime files"
fi
if [[ $purge -eq 1 ]]; then
[[ $install_id =~ ^[A-Za-z0-9-]{16,64}$ ]] || die "install record has no safe install identity"
[[ -n $config_dir && -n $state_dir ]] || die "install record has an empty purge path"
validate_managed_purge_path config "$config_dir" "$prefix" "$record_prefix" "$install_id" \
"$config_purge_allowed" "$config_dir_device" "$config_dir_inode" \
"$config_dir_uid" "$config_dir_gid" "$config_marker_sha256"
validate_managed_purge_path state "$state_dir" "$prefix" "$record_prefix" "$install_id" \
"$state_purge_allowed" "$state_dir_device" "$state_dir_inode" \
"$state_dir_uid" "$state_dir_gid" "$state_marker_sha256"
fi
service_account_present=0
if [[ $purge -eq 1 && $created_system_user == 1 ]]; then
[[ $service_uid =~ ^[0-9]+$ && $service_gid =~ ^[0-9]+$ ]] ||
die "installer-created service account record has no uid/gid identity"
if id -u "$SERVICE_USER" >/dev/null 2>&1; then
[[ $(id -u "$SERVICE_USER") -eq $service_uid &&
$(id -g "$SERVICE_USER") -eq $service_gid ]] ||
die "the recorded $SERVICE_USER account was deleted or replaced"
service_account_present=1
fi
fi
if [[ $service_scope != none ]]; then
if ! systemctl_for "$service_scope" disable --now "$SERVICE_NAME"; then
die "could not stop and disable $SERVICE_NAME; runtime was not removed"
fi
fi
rm -f -- "$prefix/current"
rm -rf -- "$prefix/versions"
if [[ $purge -eq 1 ]]; then
if [[ $config_dir == "$state_dir" ]]; then
rm -rf -- "$config_dir"
else
rm -rf -- "$config_dir" "$state_dir"
fi
fi
if [[ $purge -eq 1 && $created_system_user == 1 && $service_account_present -eq 1 ]]; then
userdel "$SERVICE_USER"
fi
if [[ $service_scope != none ]]; then
rm -f -- "$service_unit"
systemctl_for "$service_scope" daemon-reload || warn "systemd daemon-reload failed"
fi
[[ -z $launcher_path ]] || rm -f -- "$launcher_path"
rm -f -- "$record" "$prefix/install.sh" "$prefix/uninstall.sh"
rmdir -- "$prefix" 2>/dev/null || true
printf 'Echoion runtime removed from %s.\n' "$prefix"
if [[ $purge -eq 0 ]]; then
printf 'Configuration and state were preserved:\n %s\n %s\n' "$config_dir" "$state_dir"
fi
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
"""Collect deterministic license notices from an installed npm dependency tree."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import shutil
import stat
import sys
import tempfile
from typing import Any
from urllib.parse import quote
NOTICE_FILE_PATTERN = re.compile(
r"^(?:licen[cs]e|copying|notice|copyright)(?:$|[._-].*)",
re.IGNORECASE,
)
class CollectionError(RuntimeError):
"""Raised when dependency metadata cannot produce a trustworthy notice."""
def is_package_root(package_json: Path, node_modules: Path) -> bool:
relative_parts = package_json.parent.relative_to(node_modules).parts
node_modules_indices = [
index
for index, component in enumerate(relative_parts)
if component == "node_modules"
]
package_start = node_modules_indices[-1] + 1 if node_modules_indices else 0
package_parts = relative_parts[package_start:]
if len(package_parts) == 1:
return not package_parts[0].startswith("@")
return (
len(package_parts) == 2
and package_parts[0].startswith("@")
and len(package_parts[0]) > 1
)
def package_json_files(node_modules: Path) -> list[Path]:
def fail_walk(error: OSError) -> None:
raise CollectionError(f"cannot scan {error.filename}: {error.strerror}")
package_files: list[Path] = []
for directory, child_directories, filenames in os.walk(
node_modules, followlinks=False, onerror=fail_walk
):
child_directories.sort()
filenames.sort()
if "package.json" not in filenames:
continue
candidate = Path(directory, "package.json")
if not stat.S_ISREG(candidate.lstat().st_mode):
continue
if is_package_root(candidate, node_modules):
package_files.append(candidate)
return package_files
def require_metadata_text(metadata: dict[str, Any], field: str, source: Path) -> str:
value = metadata.get(field)
if not isinstance(value, str) or not value.strip():
raise CollectionError(f"{source}: {field!r} must be a non-empty string")
value = value.strip()
if any(ord(character) < 32 or ord(character) == 127 for character in value):
raise CollectionError(f"{source}: {field!r} contains control characters")
return value
def require_plain_text(value: Any, description: str, source: Path) -> str:
if not isinstance(value, str) or not value.strip():
raise CollectionError(f"{source}: {description} must be a non-empty string")
value = value.strip()
if any(ord(character) < 32 or ord(character) == 127 for character in value):
raise CollectionError(f"{source}: {description} contains control characters")
return value
def validate_package_name(name: str, source: Path) -> None:
components = name.split("/")
valid_scope = (
len(components) == 2
and components[0].startswith("@")
and len(components[0]) > 1
)
if not (len(components) == 1 and not name.startswith("@")) and not valid_scope:
raise CollectionError(f"{source}: invalid npm package name {name!r}")
if any(component in {"", ".", ".."} for component in components):
raise CollectionError(f"{source}: invalid npm package name {name!r}")
if "\\" in name:
raise CollectionError(f"{source}: invalid npm package name {name!r}")
def describe_license_entry(value: Any, source: Path) -> str:
if isinstance(value, str):
return require_plain_text(value, "license", source)
if isinstance(value, dict):
description = require_plain_text(
value.get("type"), "license object type", source
)
license_url = value.get("url")
if license_url is not None:
description += (
f" ({require_plain_text(license_url, 'license URL', source)})"
)
return description
raise CollectionError(f"{source}: license metadata has an unsupported form")
def declared_license(metadata: dict[str, Any], source: Path) -> str:
if "license" in metadata:
return describe_license_entry(metadata["license"], source)
legacy_licenses = metadata.get("licenses")
if not isinstance(legacy_licenses, list) or not legacy_licenses:
raise CollectionError(f"{source}: package has no declared license")
descriptions = sorted(
{describe_license_entry(value, source) for value in legacy_licenses}
)
return "; ".join(descriptions)
def notice_files(package_root: Path) -> dict[str, bytes]:
notices: dict[str, bytes] = {}
with os.scandir(package_root) as entries:
for entry in sorted(entries, key=lambda candidate: candidate.name):
if not NOTICE_FILE_PATTERN.match(entry.name):
continue
if not entry.is_file(follow_symlinks=False):
continue
notices[entry.name] = Path(entry.path).read_bytes()
return notices
def output_component(value: str, *, safe: str) -> str:
return quote(value, safe=safe)
def collect(node_modules: Path, destination: Path) -> int:
if not node_modules.is_dir():
raise CollectionError(f"node_modules directory does not exist: {node_modules}")
packages: dict[tuple[str, str], tuple[str, dict[str, bytes], Path]] = {}
for package_file in package_json_files(node_modules):
try:
metadata = json.loads(package_file.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as error:
raise CollectionError(f"cannot read {package_file}: {error}") from error
if not isinstance(metadata, dict):
raise CollectionError(f"{package_file}: package metadata must be an object")
name = require_metadata_text(metadata, "name", package_file)
version = require_metadata_text(metadata, "version", package_file)
validate_package_name(name, package_file)
license_description = declared_license(metadata, package_file)
notices = notice_files(package_file.parent)
key = (name, version)
previous = packages.get(key)
if previous is not None:
previous_license, previous_notices, previous_source = previous
if previous_license != license_description or previous_notices != notices:
raise CollectionError(
f"conflicting contents for {name}@{version}: "
f"{previous_source} and {package_file}"
)
continue
packages[key] = (license_description, notices, package_file)
if not packages:
raise CollectionError(f"no npm packages found below {node_modules}")
destination_parent = destination.parent
destination_parent.mkdir(parents=True, exist_ok=True)
temporary = Path(
tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination_parent)
)
try:
temporary.chmod(0o755)
notice_lines = [
"Echoion frontend third-party notices",
"",
"Generated from the installed npm dependency tree.",
"Packages are sorted by name and version.",
"",
]
output_directories: set[str] = set()
for (name, version), (license_description, notices, _) in sorted(
packages.items()
):
directory_name = (
output_component(name, safe="@._+-")
+ "@"
+ output_component(version, safe="._+-")
)
if directory_name in output_directories:
raise CollectionError(
f"output-name collision while collecting {name}@{version}"
)
output_directories.add(directory_name)
package_destination = temporary / directory_name
package_destination.mkdir(mode=0o755)
package_destination.chmod(0o755)
copied_files: list[str] = []
for filename, contents in sorted(notices.items()):
output_name = output_component(filename, safe="._+-")
target = package_destination / output_name
target.write_bytes(contents)
target.chmod(0o644)
copied_files.append(f"{directory_name}/{output_name}")
notice_lines.append(f"Package: {name}@{version}")
notice_lines.append(f"Declared license: {license_description}")
if copied_files:
notice_lines.append("Notice files:")
notice_lines.extend(f" {filename}" for filename in copied_files)
else:
notice_lines.append("Notice files: none published at package root")
notice_lines.append("")
notices_path = temporary / "THIRD-PARTY-NOTICES.txt"
notices_path.write_text("\n".join(notice_lines), encoding="utf-8", newline="\n")
notices_path.chmod(0o644)
if destination.is_symlink() or (
destination.exists() and not destination.is_dir()
):
raise CollectionError(
f"destination is not a regular directory: {destination}"
)
if destination.exists():
shutil.rmtree(destination)
os.replace(temporary, destination)
except BaseException:
shutil.rmtree(temporary, ignore_errors=True)
raise
return len(packages)
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="collect npm dependency licenses for an Echoion release"
)
parser.add_argument("--node-modules", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
return parser.parse_args()
def main() -> int:
arguments = parse_arguments()
try:
count = collect(
arguments.node_modules.resolve(),
Path(os.path.abspath(arguments.output)),
)
except (CollectionError, OSError) as error:
print(f"collect-frontend-licenses: {error}", file=sys.stderr)
return 2
print(f"Collected notices for {count} frontend npm packages.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 BUILD_DIR" >&2
exit 2
fi
cache=$(realpath -e -- "$1/CMakeCache.txt")
compiler=
while IFS= read -r line; do
case $line in
CMAKE_CXX_COMPILER:FILEPATH=* | CMAKE_CXX_COMPILER:STRING=*)
[[ -z $compiler ]] || {
echo "duplicate CMAKE_CXX_COMPILER entries in $cache" >&2
exit 2
}
compiler=${line#*=}
;;
esac
done <"$cache"
[[ $compiler == /* && -x $compiler ]] || {
echo "CMake cache has no executable absolute C++ compiler: $cache" >&2
exit 2
}
realpath -e -- "$compiler"
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Generate Echoion's deterministic v2 immutable-payload manifest."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import tempfile
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for block in iter(lambda: source.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def safe_symlink_target(root: Path, path: Path) -> str:
target = os.readlink(path)
target_path = PurePosixPath(target)
target_components = target.split("/")
if (
not target
or target_path.is_absolute()
or any(component in ("", ".", "..") for component in target_components)
):
raise ValueError(f"unsafe symlink target for {path}: {target!r}")
try:
resolved = path.resolve(strict=True)
resolved.relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError) as error:
raise ValueError(f"symlink escapes the payload or is dangling: {path}") from error
return target
def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None:
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise ValueError(f"immutable payload path is group- or world-writable: {path}")
def collect_entries(root: Path) -> list[dict[str, object]]:
entries: list[dict[str, object]] = []
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise ValueError(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
pending = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending:
try:
metadata = directory.lstat()
except FileNotFoundError as error:
raise ValueError(
f"missing immutable payload directory: {directory}"
) from error
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise ValueError(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending:
directory = pending.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISLNK(metadata.st_mode):
entries.append(
{
"path": relative,
"type": "symlink",
"target": safe_symlink_target(root, path),
}
)
elif stat.S_ISDIR(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
pending.append(path)
elif stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
if metadata.st_size > (1 << 53) - 1:
raise ValueError(f"payload file is too large for the manifest: {path}")
entries.append(
{
"path": relative,
"type": "file",
"size": metadata.st_size,
"sha256": sha256(path),
"mode": f"{stat.S_IMODE(metadata.st_mode):04o}",
}
)
else:
raise ValueError(f"unsupported special file in payload: {path}")
entries.sort(key=lambda entry: str(entry["path"]))
return entries
def write_manifest(root: Path, version: str, output: Path) -> None:
entries = collect_entries(root)
regular_files = {
str(entry["path"]) for entry in entries if entry["type"] == "file"
}
executable = "bin/echoiond"
core = "lib/Echoion.ts"
web_index = "share/echoion/web/index.html"
for description, required in (
("executable", executable),
("Core library", core),
("web dashboard entry point", web_index),
):
if required not in regular_files:
raise ValueError(f"manifest {description} is missing: {required}")
if not os.access(root / executable, os.X_OK):
raise ValueError(f"manifest executable is not executable: {executable}")
manifest = {
"schemaVersion": 2,
"version": version,
"executable": executable,
"core": core,
"files": entries,
}
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
json.dump(manifest, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(temporary_name, 0o644)
os.replace(temporary_name, output)
except BaseException:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
raise
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--version", required=True)
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
if not VERSION_PATTERN.fullmatch(arguments.version):
parser.error("version must contain only letters, digits, dot, underscore, or dash")
root = arguments.root.resolve(strict=True)
output = arguments.output or root / "manifest.json"
write_manifest(root, arguments.version, output)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 6 ]]; then
echo "usage: $0 STAGE ARTIFACT_BASE SOURCE_DATE_EPOCH ARCHIVE INSTALLER WORK_DIR" >&2
exit 2
fi
stage=$(realpath -e -- "$1")
artifact_base=$2
source_date_epoch=$3
archive=$(realpath -m -- "$4")
installer=$(realpath -m -- "$5")
work_dir=$(realpath -m -- "$6")
[[ $artifact_base =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || {
echo "invalid artifact base: $artifact_base" >&2
exit 2
}
[[ $source_date_epoch =~ ^[0-9]+$ ]] || {
echo "SOURCE_DATE_EPOCH must be a non-negative integer" >&2
exit 2
}
[[ -x $stage/install.sh && -x $stage/uninstall.sh ]] || {
echo "stage is missing executable installer helpers" >&2
exit 2
}
[[ -f $stage/manifest.json && -x $stage/bin/echoiond && -f $stage/lib/Echoion.ts ]] || {
echo "stage is missing required Echoion payload files" >&2
exit 2
}
mkdir -p -- "$(dirname -- "$archive")" "$(dirname -- "$installer")" "$work_dir"
archive_tmp="$(dirname -- "$archive")/.$(basename -- "$archive").tmp.$$"
installer_tmp="$(dirname -- "$installer")/.$(basename -- "$installer").tmp.$$"
gzip_payload="$work_dir/$artifact_base.tar.gz.$$"
header="$work_dir/$artifact_base.run-header.$$"
cleanup() {
rm -f -- "$archive_tmp" "$installer_tmp" "$gzip_payload" "$header"
}
trap cleanup EXIT
tar_options=(
--sort=name
"--mtime=@$source_date_epoch"
--owner=0
--group=0
--numeric-owner
--format=posix
'--pax-option=delete=atime,delete=ctime'
)
tar -C "$stage" "${tar_options[@]}" \
--transform="s,^\\.$,$artifact_base," \
--transform="s,^\\./,$artifact_base/," \
-cf - . |
zstd -T1 -19 --no-progress -o "$archive_tmp"
mv -f -- "$archive_tmp" "$archive"
tar -C "$stage" "${tar_options[@]}" -cf - . | gzip -n -9 >"$gzip_payload"
cat >"$header" <<'RUN_HEADER'
#!/bin/sh
set -eu
self=$0
case $self in
/*) ;;
*) self=$(pwd)/$self ;;
esac
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-installer.XXXXXX")
cleanup() {
rm -rf -- "$temporary"
}
trap cleanup EXIT HUP INT TERM
payload_line=$(awk '/^__ECHOION_PAYLOAD_BELOW__$/ { print NR + 1; exit }' "$self")
if [ -z "$payload_line" ]; then
echo "Echoion installer payload marker is missing" >&2
exit 2
fi
tail -n "+$payload_line" "$self" |
tar --same-permissions --no-same-owner -xzf - -C "$temporary"
"$temporary/install.sh" "$@"
status=$?
exit "$status"
__ECHOION_PAYLOAD_BELOW__
RUN_HEADER
cat "$header" "$gzip_payload" >"$installer_tmp"
chmod 0755 "$installer_tmp"
mv -f -- "$installer_tmp" "$installer"
trap - EXIT
+354
View File
@@ -0,0 +1,354 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'EOF'
usage: scripts/release.sh --version VERSION [options]
Options:
--build-dir DIR Clean build directory (default: build-release)
--dist-dir DIR Release output directory (default: dist)
--jobs N Parallel build jobs
--skip-tests Skip CTest and frontend tests
--no-clean Reuse the configured build directory
--container Build with containers/release.Dockerfile (the default)
--host Explicitly build directly on this host
-h, --help Show this help
The release process never starts echoiond. Runtime validation uses readelf.
EOF
}
die() {
echo "release: $*" >&2
exit 2
}
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
source_dir=$(cd -- "$script_dir/.." && pwd -P)
version=
build_dir="$source_dir/build-release"
dist_dir="$source_dir/dist"
jobs=
run_tests=1
clean_build=1
use_container=1
while (($#)); do
case $1 in
--version)
(($# >= 2)) || die "--version requires a value"
version=$2
shift 2
;;
--build-dir)
(($# >= 2)) || die "--build-dir requires a value"
build_dir=$2
shift 2
;;
--dist-dir)
(($# >= 2)) || die "--dist-dir requires a value"
dist_dir=$2
shift 2
;;
--jobs)
(($# >= 2)) || die "--jobs requires a value"
jobs=$2
shift 2
;;
--skip-tests)
run_tests=0
shift
;;
--no-clean)
clean_build=0
shift
;;
--container)
use_container=1
shift
;;
--host)
use_container=0
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "unknown argument: $1"
;;
esac
done
[[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] ||
die "--version must contain only letters, digits, dot, underscore, or dash"
if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then
die "--jobs must be a positive integer"
fi
build_dir=$(realpath -m -- "$build_dir")
dist_dir=$(realpath -m -- "$dist_dir")
container_path() {
local path=$1
case $path in
"$source_dir") echo /workspace ;;
"$source_dir"/*) echo "/workspace/${path#"$source_dir"/}" ;;
*) die "container build and dist directories must be inside $source_dir" ;;
esac
}
if ((use_container)); then
command -v docker >/dev/null || die "docker is required for --container"
container_build_dir=$(container_path "$build_dir")
container_dist_dir=$(container_path "$dist_dir")
image="echoion-release-builder:gcc-16.1.0"
docker build \
--platform linux/amd64 \
--file "$source_dir/containers/release.Dockerfile" \
--tag "$image" \
"$source_dir"
container_args=(
--rm
--user "$(id -u):$(id -g)"
--volume "$source_dir:/workspace"
--workdir /workspace
--env HOME=/tmp/echoion-release-home
--env npm_config_cache=/tmp/echoion-npm-cache
)
if [[ -n ${SOURCE_DATE_EPOCH:-} ]]; then
container_args+=(--env "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH")
fi
release_args=(
--host
--version "$version"
--build-dir "$container_build_dir"
--dist-dir "$container_dist_dir"
)
[[ -n $jobs ]] && release_args+=(--jobs "$jobs")
((run_tests)) || release_args+=(--skip-tests)
((clean_build)) || release_args+=(--no-clean)
docker run --platform linux/amd64 "${container_args[@]}" "$image" \
bash scripts/release.sh "${release_args[@]}"
exit
fi
case "$(uname -s)/$(uname -m)" in
Linux/x86_64|Linux/amd64) ;;
*) die "host release builds require Linux x86_64; use the amd64 container builder" ;;
esac
required_commands=(
cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum
dpkg-query ldconfig
)
for command_name in "${required_commands[@]}"; do
command -v "$command_name" >/dev/null || die "required command not found: $command_name"
done
[[ -x $source_dir/packaging/install.sh ]] ||
die "installer source is missing: packaging/install.sh"
[[ -x $source_dir/packaging/uninstall.sh ]] ||
die "uninstaller source is missing: packaging/uninstall.sh"
[[ -f $source_dir/packaging/service/echoion.service.in ]] ||
die "service template is missing: packaging/service/echoion.service.in"
if [[ -z ${SOURCE_DATE_EPOCH:-} ]]; then
SOURCE_DATE_EPOCH=$(git -C "$source_dir" log -1 --format=%ct 2>/dev/null || true)
[[ $SOURCE_DATE_EPOCH =~ ^[0-9]+$ ]] || SOURCE_DATE_EPOCH=0
fi
export SOURCE_DATE_EPOCH
safe_remove_tree() {
local path=$1
case $path in
"$source_dir"/build*|/tmp/*) ;;
*) die "refusing to clean non-build path outside source build*/ or /tmp: $path" ;;
esac
rm -rf -- "$path"
}
if ((clean_build)); then
safe_remove_tree "$build_dir"
fi
mkdir -p "$build_dir"
configure_args=(--preset linux-release -B "$build_dir")
npm --prefix "$source_dir/EchoionWeb/frontend" ci --no-audit --no-fund
cmake -E rm -rf "$source_dir/EchoionWeb/frontend/web-dist"
(
cd "$source_dir"
cmake "${configure_args[@]}"
)
build_args=(--build "$build_dir" --config Release)
[[ -n $jobs ]] && build_args+=(--parallel "$jobs")
cmake "${build_args[@]}"
if ((run_tests)); then
ctest --test-dir "$build_dir" --build-config Release --output-on-failure
npm --prefix "$source_dir/EchoionWeb/frontend" test
npm --prefix "$source_dir/EchoionWeb/frontend" run i18n:check
fi
stage="$build_dir/runtime-stage"
safe_remove_tree "$stage"
cmake --install "$build_dir" \
--config Release \
--component Runtime \
--prefix "$stage"
mapfile -t library_directories < <(
find "$build_dir" -type f \( -name '*.so' -o -name '*.so.*' -o -name '*.ts' \) \
-printf '%h\n' | LC_ALL=C sort -u
)
library_directories+=("$stage/lib")
cxx_compiler=$("$source_dir/scripts/configured-cxx-compiler.sh" "$build_dir")
compiler_runtime_files=()
for runtime_name in libstdc++.so.6 libgcc_s.so.1; do
runtime_path=$(
"$cxx_compiler" -print-file-name="$runtime_name"
) || die "cannot locate $runtime_name with $cxx_compiler"
[[ $runtime_path == /* && -f $runtime_path ]] ||
die "$cxx_compiler did not return an existing absolute path for $runtime_name"
compiler_runtime_files+=("$runtime_path")
library_directories+=("$(dirname -- "$runtime_path")")
done
search_directories=$(IFS=';'; echo "${library_directories[*]}")
compiler_runtimes=$(IFS=';'; echo "${compiler_runtime_files[*]}")
cmake \
"-DBUNDLE_ROOT=$stage" \
"-DBUNDLE_RESOLVER_EXECUTABLE=$build_dir/bin/echoiond" \
"-DBUNDLE_RESOLVER_LIBRARIES=$build_dir/lib/Echoion.ts" \
"-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \
"-DBUNDLE_SEED_FILES=$compiler_runtimes" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_dir/cmake/BundleRuntimeDependencies.cmake"
dependency_report="$build_dir/dependency-report.txt"
python3 "$source_dir/scripts/validate-release-elf.py" \
--root "$stage" \
--max-glibc 2.35 \
--report "$dependency_report"
collect_licenses() {
local destination=$1
local candidate relative package_name license_name digest target package source_path soname
local -a license_roots=(
"$source_dir/EchoionApi"
"$source_dir/EchoionCore"
"$source_dir/EchoionHost"
"$source_dir/EchoionStandalone"
"$source_dir/EchoionWeb"
"$build_dir/_deps"
)
if [[ -n ${GCC_ROOT:-} && -d $GCC_ROOT/share/licenses ]]; then
license_roots+=("$GCC_ROOT/share/licenses")
fi
if [[ -n ${BOOST_ROOT:-} && -d $BOOST_ROOT/share/licenses ]]; then
license_roots+=("$BOOST_ROOT/share/licenses")
fi
if [[ -n ${FFMPEG_ROOT:-} && -d $FFMPEG_ROOT/share/licenses ]]; then
license_roots+=("$FFMPEG_ROOT/share/licenses")
fi
mkdir -p "$destination"
for source_path in "${license_roots[@]}"; do
[[ -d $source_path ]] || continue
while IFS= read -r -d '' candidate; do
relative=${candidate#"$source_path"/}
if [[ $relative == */* ]]; then
package_name=${relative%%/*}
else
package_name=$(basename -- "$source_path")
fi
license_name=$(basename -- "$candidate")
package_name=${package_name//[^A-Za-z0-9._+-]/_}
license_name=${license_name//[^A-Za-z0-9._+-]/_}
digest=$(sha256sum "$candidate" | cut -c1-12)
target="$destination/${package_name}--${license_name}--${digest}"
install -m 0644 -- "$candidate" "$target"
done < <(
find "$source_path" -maxdepth 5 -type f \
\( -iname 'LICENSE' -o -iname 'LICENSE.txt' -o \
-iname 'LICENSE.md' -o -iname 'LICENSE.rst' -o \
-iname 'LICENSE-*' -o -iname 'LICENSE_*' -o \
-iname 'COPYING' -o -iname 'COPYING.*' -o \
-iname 'NOTICE' -o -iname 'NOTICE.*' -o \
-iname 'COPYRIGHT' -o -iname 'COPYRIGHT.*' \) \
-not -path '*/node_modules/*' -not -path '*/.git/*' \
-print0 | LC_ALL=C sort -z
)
done
if command -v dpkg-query >/dev/null && command -v ldconfig >/dev/null; then
while IFS= read -r soname; do
[[ -n $soname ]] || continue
source_path=$(ldconfig -p 2>/dev/null |
awk -v name="$soname" '
$1 == name && !path { path = $NF }
END { if (path) print path }
')
[[ -n $source_path ]] || continue
package=$(dpkg-query -S "$(readlink -f -- "$source_path")" 2>/dev/null |
sed -n '1s/: .*//p') || package=
[[ -n $package ]] || continue
package=${package%%:*}
candidate="/usr/share/doc/${package}/copyright"
[[ -f $candidate ]] || continue
install -m 0644 -- "$candidate" "$destination/${package}--copyright"
done < <(
find "$stage/lib" -maxdepth 1 \( -type f -o -type l \) \
-printf '%f\n' | LC_ALL=C sort -u
)
fi
}
collect_licenses "$stage/share/echoion/licenses"
python3 "$source_dir/scripts/collect-frontend-licenses.py" \
--node-modules "$source_dir/EchoionWeb/frontend/node_modules" \
--output "$stage/share/echoion/licenses/frontend"
python3 "$source_dir/scripts/generate-release-manifest.py" \
--root "$stage" \
--version "$version" \
--output "$stage/manifest.json"
# Installer helpers are mutable prefix-level files and intentionally are not
# included in manifest.files. They are added only after the immutable manifest.
install -m 0755 "$source_dir/packaging/install.sh" "$stage/install.sh"
install -m 0755 "$source_dir/packaging/uninstall.sh" "$stage/uninstall.sh"
mkdir -p "$dist_dir"
artifact_base="echoion-${version}-linux-x86_64"
archive="$dist_dir/$artifact_base.tar.zst"
installer="$dist_dir/$artifact_base.run"
external_manifest="$dist_dir/$artifact_base.manifest.json"
external_report="$dist_dir/$artifact_base.dependencies.txt"
rm -f -- \
"$archive" "$archive.tmp" \
"$installer" "$installer.tmp" \
"$external_manifest" "$external_report" \
"$dist_dir/SHA256SUMS"
bash "$source_dir/scripts/package-release-payload.sh" \
"$stage" "$artifact_base" "$SOURCE_DATE_EPOCH" \
"$archive" "$installer" "$build_dir"
install -m 0644 "$stage/manifest.json" "$external_manifest"
install -m 0644 "$dependency_report" "$external_report"
(
cd "$dist_dir"
sha256sum \
"$(basename "$archive")" \
"$(basename "$installer")" \
"$(basename "$external_manifest")" \
"$(basename "$external_report")" >SHA256SUMS
)
echo "Release created without starting Echoion:"
echo " $archive"
echo " $installer"
echo " $external_manifest"
echo " $external_report"
echo " $dist_dir/SHA256SUMS"
+211 -32
View File
@@ -1,63 +1,242 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 4 || $# -gt 5 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION ECHOIOND ECHOION_CORE [MANIFEST]" >&2
if [[ $# -lt 3 || $# -gt 4 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2
exit 2
fi
release_root=$1
release_root=$(realpath -m -- "$1")
version=$2
executable=$3
core=$4
manifest=${5:-"$release_root/pending-release.json"}
bundle_root=$(realpath -e -- "$3")
manifest=${4:-"$release_root/pending-release.json"}
manifest=$(realpath -m -- "$manifest")
if [[ ! $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then
echo "invalid release version: $version" >&2
exit 2
fi
if [[ ! -x $executable ]]; then
echo "echoiond is missing or not executable: $executable" >&2
if [[ $bundle_root == "$release_root" ||
$bundle_root == "$release_root"/* ||
$release_root == "$bundle_root"/* ]]; then
echo "bundle root and release root must not overlap" >&2
exit 2
fi
if [[ ! -f $core ]]; then
echo "Core library is missing: $core" >&2
if [[ $(dirname -- "$manifest") != "$release_root" ]]; then
echo "pending manifest must be written directly below the release root" >&2
exit 2
fi
if [[ ! -x $bundle_root/bin/echoiond ]]; then
echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&2
exit 2
fi
if [[ ! -f $bundle_root/lib/Echoion.ts ]]; then
echo "Core library is missing: $bundle_root/lib/Echoion.ts" >&2
exit 2
fi
if [[ ! -f $bundle_root/manifest.json ]]; then
echo "v2 release manifest is missing: $bundle_root/manifest.json" >&2
exit 2
fi
mkdir -p "$release_root" "$(dirname "$manifest")"
mkdir -p -- "$release_root" "$(dirname -- "$manifest")"
staging="$release_root/.staging-$version-$$"
destination="$release_root/$version"
trap 'rm -rf -- "$staging"' EXIT
manifest_tmp="$(dirname -- "$manifest")/.$(basename -- "$manifest").tmp.$$"
version_lock="$release_root/.stage-$version.lock"
destination_created=0
manifest_published=0
lock_acquired=0
cleanup() {
rm -rf -- "$staging"
rm -f -- "$manifest_tmp"
if ((destination_created && !manifest_published)); then
rm -rf -- "$destination"
fi
if ((lock_acquired)); then
rmdir -- "$version_lock" 2>/dev/null || true
fi
}
trap cleanup EXIT
if ! mkdir -- "$version_lock"; then
echo "release staging is already active for version $version" >&2
exit 2
fi
lock_acquired=1
if [[ -e $destination ]]; then
echo "release already exists: $destination" >&2
exit 2
fi
mkdir "$staging"
install -m 0755 "$executable" "$staging/echoiond"
install -m 0644 "$core" "$staging/Echoion.ts"
mkdir -m 0755 -- "$staging"
cp -a -- "$bundle_root/." "$staging/"
executable_hash=$(sha256sum "$staging/echoiond" | cut -d' ' -f1)
core_hash=$(sha256sum "$staging/Echoion.ts" | cut -d' ' -f1)
mv "$staging" "$destination"
python3 - "$staging" "$version" "$manifest_tmp" <<'PY'
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import stat
import sys
manifest_tmp="$manifest.tmp.$$"
trap 'rm -rf -- "$staging"; rm -f -- "$manifest_tmp"' EXIT
printf '%s\n' \
'{' \
" \"version\": \"$version\"," \
" \"executable\": \"$version/echoiond\"," \
" \"core\": \"$version/Echoion.ts\"," \
' "sha256": {' \
" \"executable\": \"$executable_hash\"," \
" \"core\": \"$core_hash\"" \
' }' \
'}' > "$manifest_tmp"
chmod 0644 "$manifest_tmp"
mv -f "$manifest_tmp" "$manifest"
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def reject_unsafe_writable_mode(path, metadata):
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise SystemExit(
f"immutable payload path is group- or world-writable: {path}"
)
root = Path(sys.argv[1]).resolve(strict=True)
version = sys.argv[2]
output = Path(sys.argv[3])
source = root / "manifest.json"
with source.open("r", encoding="utf-8") as stream:
manifest = json.load(stream)
if manifest.get("schemaVersion") != 2:
raise SystemExit("release manifest must use schemaVersion 2")
if manifest.get("version") != version:
raise SystemExit(
f"release version mismatch: expected {version!r}, got {manifest.get('version')!r}"
)
entries = manifest.get("files")
if not isinstance(entries, list):
raise SystemExit("release manifest files must be an array")
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise SystemExit(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
actual = set()
pending_directories = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending_directories:
try:
metadata = directory.lstat()
except FileNotFoundError:
raise SystemExit(f"missing immutable payload directory: {directory}")
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise SystemExit(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending_directories:
directory = pending_directories.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISDIR(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
pending_directories.append(path)
elif stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
if stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
actual.add(relative)
else:
raise SystemExit(f"unsupported special file in payload: {path}")
seen = set()
entry_types = {}
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
raise SystemExit("invalid release manifest file entry")
relative = PurePosixPath(entry["path"])
if (
relative.is_absolute()
or not relative.parts
or relative.as_posix() != entry["path"]
or any(component in ("", ".", "..") for component in entry["path"].split("/"))
):
raise SystemExit(f"unsafe manifest path: {entry['path']!r}")
if entry["path"] in seen:
raise SystemExit(f"duplicate manifest path: {entry['path']}")
if relative.parts[0] not in IMMUTABLE_ROOTS:
raise SystemExit(
f"manifest path is outside immutable payload roots: {entry['path']}"
)
seen.add(entry["path"])
entry_types[entry["path"]] = entry.get("type")
path = root.joinpath(*relative.parts)
metadata = path.lstat()
if entry.get("type") == "file":
if not stat.S_ISREG(metadata.st_mode):
raise SystemExit(f"manifest regular file is missing: {entry['path']}")
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != entry.get("sha256") or metadata.st_size != entry.get("size"):
raise SystemExit(f"manifest file verification failed: {entry['path']}")
mode = f"{stat.S_IMODE(metadata.st_mode):04o}"
if mode != entry.get("mode"):
raise SystemExit(f"manifest mode verification failed: {entry['path']}")
reject_unsafe_writable_mode(path, metadata)
elif entry.get("type") == "symlink":
if not stat.S_ISLNK(metadata.st_mode):
raise SystemExit(f"manifest symlink is missing: {entry['path']}")
target = entry.get("target")
if not isinstance(target, str):
raise SystemExit(f"invalid manifest symlink target: {entry['path']}")
target_path = PurePosixPath(target)
if (
target_path.is_absolute()
or any(component in ("", ".", "..") for component in target.split("/"))
):
raise SystemExit(f"unsafe manifest symlink target: {entry['path']}")
if os.readlink(path) != target:
raise SystemExit(f"manifest symlink verification failed: {entry['path']}")
try:
path.resolve(strict=True).relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError):
raise SystemExit(f"manifest symlink escapes release root: {entry['path']}")
else:
raise SystemExit(f"invalid manifest entry type: {entry.get('type')!r}")
if seen != actual:
undeclared = sorted(actual - seen)
missing = sorted(seen - actual)
details = []
if undeclared:
details.append("undeclared=" + ",".join(undeclared))
if missing:
details.append("missing=" + ",".join(missing))
raise SystemExit("immutable payload coverage mismatch: " + "; ".join(details))
required_files = {
"executable": "bin/echoiond",
"core": "lib/Echoion.ts",
"web dashboard": "share/echoion/web/index.html",
}
for description, required in required_files.items():
if description in ("executable", "core") and manifest.get(description) != required:
raise SystemExit(f"manifest {description} has a non-canonical path")
if required not in seen or entry_types.get(required) != "file":
raise SystemExit(f"manifest {description} is not declared as a file")
prefix = f"{version}/"
pending = dict(manifest)
pending["executable"] = prefix + manifest["executable"]
pending["core"] = prefix + manifest["core"]
pending["files"] = [dict(entry, path=prefix + entry["path"]) for entry in entries]
with output.open("w", encoding="utf-8", newline="\n") as stream:
json.dump(pending, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(output, 0o644)
PY
mv -T -- "$staging" "$destination"
destination_created=1
mv -f -- "$manifest_tmp" "$manifest"
manifest_published=1
rmdir -- "$version_lock"
lock_acquired=0
trap - EXIT
echo "staged release $version"
echo "payload: $destination"
echo "manifest: $manifest"
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-frontend-licenses.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
node_modules="$temporary/node_modules"
mkdir -p \
"$node_modules/plain/docs" \
"$node_modules/@scope/example" \
"$node_modules/parent/node_modules/duplicate" \
"$node_modules/second/node_modules/duplicate" \
"$node_modules/no-notice"
printf '%s\n' \
'{"name":"plain","version":"1.2.3","license":"MIT"}' \
>"$node_modules/plain/package.json"
printf '%s\n' 'plain license' >"$node_modules/plain/LICENSE"
printf '%s\n' 'ignored nested file' >"$node_modules/plain/docs/LICENSE"
printf '%s\n' '{"name":"not-a-package-root"}' \
>"$node_modules/plain/docs/package.json"
printf '%s\n' \
'{"name":"@scope/example","version":"2.0.0-beta.1","license":"Apache-2.0"}' \
>"$node_modules/@scope/example/package.json"
printf '%s\n' 'scoped license' >"$node_modules/@scope/example/LICENCE.md"
printf '%s\n' 'scoped notice' >"$node_modules/@scope/example/NOTICE-extra"
for package_root in \
"$node_modules/parent/node_modules/duplicate" \
"$node_modules/second/node_modules/duplicate"; do
printf '%s\n' \
'{"name":"duplicate","version":"3.4.5","licenses":[{"type":"BSD-2-Clause"}]}' \
>"$package_root/package.json"
printf '%s\n' 'duplicate copying' >"$package_root/COPYING.txt"
done
printf '%s\n' \
'{"name":"no-notice","version":"4.0.0","license":"ISC"}' \
>"$node_modules/no-notice/package.json"
output_one="$temporary/output-one"
output_two="$temporary/output-two"
(
umask 077
python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$node_modules" \
--output "$output_one"
)
python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$node_modules" \
--output "$output_two"
diff -r -- "$output_one" "$output_two"
[[ -f $output_one/plain@1.2.3/LICENSE ]]
[[ ! -e $output_one/plain@1.2.3/docs ]]
[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/LICENCE.md ]]
[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/NOTICE-extra ]]
[[ -f $output_one/duplicate@3.4.5/COPYING.txt ]]
[[ -d $output_one/no-notice@4.0.0 ]]
if find "$output_one" -type d ! -perm 0755 -print -quit | grep -q .; then
echo "license collection created a directory with an unstable mode" >&2
exit 1
fi
if find "$output_one" -type f ! -perm 0644 -print -quit | grep -q .; then
echo "license collection created a file with an unstable mode" >&2
exit 1
fi
python3 - "$output_one/THIRD-PARTY-NOTICES.txt" <<'PY'
from pathlib import Path
import sys
contents = Path(sys.argv[1]).read_text(encoding="utf-8")
packages = [
line.removeprefix("Package: ")
for line in contents.splitlines()
if line.startswith("Package: ")
]
assert packages == sorted(packages)
assert packages == [
"@scope/example@2.0.0-beta.1",
"duplicate@3.4.5",
"no-notice@4.0.0",
"plain@1.2.3",
]
assert contents.count("Package: duplicate@3.4.5") == 1
assert "Declared license: BSD-2-Clause" in contents
assert "Notice files: none published at package root" in contents
assert "@scope%2Fexample@2.0.0-beta.1/NOTICE-extra" in contents
PY
mkdir -p "$temporary/malformed/node_modules/bad"
printf '%s\n' '{"name":"bad","version":"1.0.0"}' \
>"$temporary/malformed/node_modules/bad/package.json"
error_file="$temporary/malformed.error"
if python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$temporary/malformed/node_modules" \
--output "$temporary/malformed-output" \
>/dev/null 2>"$error_file"; then
echo "package without license metadata unexpectedly passed" >&2
exit 1
fi
grep -Fq 'package has no declared license' "$error_file"
mkdir -p \
"$temporary/conflict/node_modules/first/node_modules/same" \
"$temporary/conflict/node_modules/second/node_modules/same"
for package_root in \
"$temporary/conflict/node_modules/first/node_modules/same" \
"$temporary/conflict/node_modules/second/node_modules/same"; do
printf '%s\n' \
'{"name":"same","version":"1.0.0","license":"MIT"}' \
>"$package_root/package.json"
done
printf '%s\n' first \
>"$temporary/conflict/node_modules/first/node_modules/same/LICENSE"
printf '%s\n' second \
>"$temporary/conflict/node_modules/second/node_modules/same/LICENSE"
if python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$temporary/conflict/node_modules" \
--output "$temporary/conflict-output" >/dev/null 2>&1; then
echo "conflicting duplicate package contents unexpectedly passed" >&2
exit 1
fi
echo "frontend npm license collection regressions passed"
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-archive.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
stage="$temporary/stage"
mkdir -p "$stage/bin" "$stage/lib"
install -m 0755 /bin/true "$stage/bin/echoiond"
install -m 0644 /bin/true "$stage/lib/Echoion.ts"
printf '%s\n' '{}' >"$stage/manifest.json"
cat >"$stage/install.sh" <<'INSTALL'
#!/bin/sh
set -eu
payload_root=$(CDPATH= cd -P -- "$(dirname -- "$0")" && pwd -P)
[ "$(stat -c '%a' -- "$payload_root/bin/echoiond")" = 755 ]
[ "$(stat -c '%a' -- "$payload_root/lib/Echoion.ts")" = 644 ]
[ "$1" = --record ]
record=$2
shift 2
printf '%s\n' "$@" >"$record"
INSTALL
printf '%s\n' '#!/bin/sh' 'exit 0' >"$stage/uninstall.sh"
chmod 0755 "$stage/install.sh" "$stage/uninstall.sh"
base=echoion-1.2.3-linux-x86_64
archive_one="$temporary/one.tar.zst"
installer_one="$temporary/one.run"
archive_two="$temporary/two.tar.zst"
installer_two="$temporary/two.run"
bash "$source_root/scripts/package-release-payload.sh" \
"$stage" "$base" 1700000000 "$archive_one" "$installer_one" "$temporary"
bash "$source_root/scripts/package-release-payload.sh" \
"$stage" "$base" 1700000000 "$archive_two" "$installer_two" "$temporary"
cmp "$archive_one" "$archive_two"
cmp "$installer_one" "$installer_two"
mapfile -t members < <(tar --zstd -tf "$archive_one")
((${#members[@]} > 0))
for member in "${members[@]}"; do
[[ $member == "$base" || $member == "$base/"* ]] || {
echo "archive member escaped top-level directory: $member" >&2
exit 1
}
done
printf '%s\n' "${members[@]}" | grep -Fx "$base/bin/echoiond"
record="$temporary/installer-arguments"
(
umask 077
"$installer_one" --record "$record" alpha 'two words'
)
printf '%s\n' alpha 'two words' >"$temporary/expected-arguments"
cmp "$temporary/expected-arguments" "$record"
echo "release archive layout and .run regressions passed"
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
bundle="$temporary/bundle"
mkdir -p \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
install -m 0755 /bin/true "$bundle/bin/echoiond"
install -m 0644 /bin/true "$bundle/lib/Echoion.ts"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
ln -s Echoion.ts "$bundle/lib/Echoion-current.ts"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$bundle" --version 1.2.3
cp "$bundle/manifest.json" "$temporary/manifest.first.json"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$bundle" --version 1.2.3
cmp "$temporary/manifest.first.json" "$bundle/manifest.json"
unsafe_file_mode="$temporary/unsafe-file-mode"
cp -a "$bundle" "$unsafe_file_mode"
chmod 0666 "$unsafe_file_mode/lib/Echoion.ts"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe_file_mode" --version 1.2.3 >/dev/null 2>&1; then
echo "world-writable payload file unexpectedly entered manifest" >&2
exit 1
fi
unsafe_directory_mode="$temporary/unsafe-directory-mode"
cp -a "$bundle" "$unsafe_directory_mode"
chmod 0777 "$unsafe_directory_mode/lib"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe_directory_mode" --version 1.2.3 >/dev/null 2>&1; then
echo "world-writable payload directory unexpectedly entered manifest" >&2
exit 1
fi
python3 - "$bundle/manifest.json" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
manifest = json.load(stream)
assert manifest["schemaVersion"] == 2
assert manifest["version"] == "1.2.3"
assert manifest["executable"] == "bin/echoiond"
assert manifest["core"] == "lib/Echoion.ts"
paths = [entry["path"] for entry in manifest["files"]]
assert paths == sorted(paths)
assert "share/echoion/web/index.html" in paths
link = next(entry for entry in manifest["files"] if entry["path"].endswith("current.ts"))
assert link == {
"path": "lib/Echoion-current.ts",
"type": "symlink",
"target": "Echoion.ts",
}
for entry in manifest["files"]:
if entry["type"] == "file":
assert set(entry) == {"path", "type", "size", "sha256", "mode"}
assert len(entry["sha256"]) == 64
assert len(entry["mode"]) == 4
PY
printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/install.sh"
printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/uninstall.sh"
chmod 0755 "$bundle/install.sh" "$bundle/uninstall.sh"
for overlapping_release_root in "$bundle" "$bundle/releases"; do
if bash "$source_root/scripts/stage-release.sh" \
"$overlapping_release_root" 1.2.3 "$bundle" >/dev/null 2>&1; then
echo "overlapping bundle/release roots unexpectedly staged" >&2
exit 1
fi
done
overlap_parent="$temporary/overlap-parent"
mkdir "$overlap_parent"
cp -a "$bundle" "$overlap_parent/bundle"
if bash "$source_root/scripts/stage-release.sh" \
"$overlap_parent" 1.2.3 "$overlap_parent/bundle" >/dev/null 2>&1; then
echo "release root containing bundle root unexpectedly staged" >&2
exit 1
fi
release_root="$temporary/releases"
bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.3 "$bundle"
[[ -x $release_root/1.2.3/bin/echoiond ]]
[[ -L $release_root/1.2.3/lib/Echoion-current.ts ]]
[[ -x $release_root/1.2.3/install.sh ]]
python3 - "$release_root/pending-release.json" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
manifest = json.load(stream)
assert manifest["executable"] == "1.2.3/bin/echoiond"
assert manifest["core"] == "1.2.3/lib/Echoion.ts"
assert all(entry["path"].startswith("1.2.3/") for entry in manifest["files"])
assert not any(entry["path"].endswith("install.sh") for entry in manifest["files"])
PY
tampered="$temporary/tampered"
cp -a "$bundle" "$tampered"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$tampered" --version 1.2.4
printf '%s\n' tampered >>"$tampered/lib/Echoion.ts"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.4 "$tampered" >/dev/null 2>&1; then
echo "tampered payload unexpectedly staged" >&2
exit 1
fi
rogue="$temporary/rogue"
cp -a "$bundle" "$rogue"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$rogue" --version 1.2.6
printf '%s\n' rogue >"$rogue/lib/rogue.so"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.6 "$rogue" >/dev/null 2>&1; then
echo "undeclared immutable payload file unexpectedly staged" >&2
exit 1
fi
[[ ! -e $release_root/1.2.6 ]]
outside_entry="$temporary/outside-entry"
cp -a "$bundle" "$outside_entry"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$outside_entry" --version 1.2.8
printf '%s\n' outside >"$outside_entry/outside.dat"
python3 - "$outside_entry/manifest.json" "$outside_entry/outside.dat" <<'PY'
import hashlib
import json
from pathlib import Path
import stat
import sys
manifest_path = Path(sys.argv[1])
outside = Path(sys.argv[2])
with manifest_path.open(encoding="utf-8") as stream:
manifest = json.load(stream)
metadata = outside.stat()
manifest["files"].append(
{
"path": "outside.dat",
"type": "file",
"size": metadata.st_size,
"sha256": hashlib.sha256(outside.read_bytes()).hexdigest(),
"mode": f"{stat.S_IMODE(metadata.st_mode):04o}",
}
)
with manifest_path.open("w", encoding="utf-8", newline="\n") as stream:
json.dump(manifest, stream, indent=2)
stream.write("\n")
PY
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.8 "$outside_entry" >/dev/null 2>&1; then
echo "manifest entry outside immutable roots unexpectedly staged" >&2
exit 1
fi
[[ ! -e $release_root/1.2.8 ]]
mkdir "$release_root/.stage-1.2.7.lock"
lock_error="$temporary/stage-lock.error"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.7 "$bundle" > /dev/null 2>"$lock_error"; then
echo "concurrent same-version staging unexpectedly acquired the lock" >&2
exit 1
fi
grep -q 'release staging is already active' "$lock_error"
[[ ! -e $release_root/1.2.7 ]]
rmdir "$release_root/.stage-1.2.7.lock"
if find "$release_root" -mindepth 2 -name '.staging-*' | grep -q .; then
echo "staging directory was nested below a published release" >&2
exit 1
fi
unsafe="$temporary/unsafe"
cp -a "$bundle" "$unsafe"
rm "$unsafe/lib/Echoion-current.ts"
ln -s ../bin/echoiond "$unsafe/lib/Echoion-current.ts"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe" --version 1.2.5 >/dev/null 2>&1; then
echo "unsafe symlink unexpectedly entered manifest" >&2
exit 1
fi
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" '../unsafe' "$bundle" >/dev/null 2>&1; then
echo "unsafe version unexpectedly staged" >&2
exit 1
fi
echo "release manifest and staging regressions passed"
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
for command_name in cc cmake patchelf readelf python3; do
command -v "$command_name" >/dev/null || {
echo "missing test command: $command_name" >&2
exit 2
}
done
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-runtime-deps.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
configured_build="$temporary/configured-build"
mkdir -p "$configured_build"
configured_compiler=$(realpath -e -- "$(command -v c++)")
printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$configured_compiler" \
>"$configured_build/CMakeCache.txt"
queried_compiler=$(CXX=/bin/false \
"$source_root/scripts/configured-cxx-compiler.sh" "$configured_build")
[[ $queried_compiler == "$configured_compiler" ]] || {
echo "runtime compiler query followed CXX instead of the configured cache" >&2
exit 1
}
preferred_lib="$temporary/preferred-lib"
other_lib="$temporary/other-lib"
bundle="$temporary/bundle"
resolver="$temporary/resolver"
seed_lib="$temporary/seed-lib"
mkdir -p \
"$preferred_lib" \
"$other_lib" \
"$resolver" \
"$seed_lib" \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
cat >"$temporary/dependency.c" <<'C'
int echoion_dependency(void) { return 42; }
__attribute__((used, section(".echoion_variant")))
static const char echoion_variant[] = ECHOION_VARIANT;
C
cat >"$temporary/core.c" <<'C'
extern int echoion_dependency(void);
extern int echoion_compiler_runtime(void);
int echoion_core(void) {
return echoion_dependency() + echoion_compiler_runtime();
}
C
cat >"$temporary/main.c" <<'C'
int main(void) { return 0; }
C
cat >"$temporary/compiler-runtime.c" <<'C'
int echoion_compiler_runtime(void) { return 7; }
__attribute__((used, section(".echoion_compiler_variant")))
static const char echoion_compiler_variant[] = ECHOION_VARIANT;
C
for variant in preferred other; do
case $variant in
preferred) variant_lib=$preferred_lib ;;
other) variant_lib=$other_lib ;;
esac
cc -fPIC -shared "$temporary/dependency.c" \
'-DECHOION_VARIANT="'"$variant"'-runtime"' \
-Wl,-soname,libechoion-dependency.so.1 \
-o "$variant_lib/libechoion-dependency.so.1.2.3"
ln -s libechoion-dependency.so.1.2.3 \
"$variant_lib/libechoion-dependency.so.1"
ln -s libechoion-dependency.so.1 \
"$variant_lib/libechoion-dependency.so"
done
for variant in seeded resolver; do
case $variant in
seeded)
variant_lib=$seed_lib
variant_version=100
;;
resolver)
variant_lib=$preferred_lib
variant_version=200
;;
esac
cc -fPIC -shared "$temporary/compiler-runtime.c" \
'-DECHOION_VARIANT="'"$variant"'-compiler-runtime"' \
-Wl,-soname,libstdc++.so.6 \
-o "$variant_lib/libstdc++.so.6.0.$variant_version"
ln -s "libstdc++.so.6.0.$variant_version" \
"$variant_lib/libstdc++.so.6"
done
resolver_core="$resolver/Echoion.ts"
cc -fPIC -shared "$temporary/core.c" \
-L"$preferred_lib" -lechoion-dependency \
-Wl,-l:libstdc++.so.6 \
-Wl,-soname,Echoion.ts \
-Wl,-rpath,"$preferred_lib" \
-o "$resolver_core"
install -m 0644 "$resolver_core" "$bundle/lib/Echoion.ts"
patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts"
cc "$temporary/main.c" -o "$bundle/bin/echoiond"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
cmake \
"-DBUNDLE_ROOT=$bundle" \
"-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core" \
"-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \
"-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_root/cmake/BundleRuntimeDependencies.cmake"
python3 - "$source_root/scripts/validate-release-elf.py" <<'PY'
import importlib.util
from pathlib import Path
import sys
module_path = Path(sys.argv[1])
spec = importlib.util.spec_from_file_location("validate_release_elf", module_path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
fixture = """
Version needs section '.gnu.version_r' contains 2 entries:
000000: Version: 1 File: libm.so.6 Cnt: 1
0x0010: Name: GLIBC_9.99 Flags: none Version: 4
0x0020: Version: 1 File: libc.so.6 Cnt: 3
0x0030: Name: GLIBC_2.17 Flags: none Version: 3
0x0040: Name: GLIBC_2.36 Flags: none Version: 2
0x0050: Name: GLIBC_ABI_DT_RELR Flags: none Version: 1
"""
assert module.required_glibc_versions(fixture) == {(2, 17), (2, 36), (9, 99)}
assert module.parse_version("2.35") == (2, 35)
assert module.is_system_dependency("libc.so.6")
assert module.is_system_dependency("libm.so.6")
assert not module.is_system_dependency("libc.so.evil")
assert not module.is_system_dependency("libm.so.99")
unknown_abi = """
Version needs section '.gnu.version_r' contains 1 entry:
000000: Version: 1 File: libc.so.6 Cnt: 1
0x0010: Name: GLIBC_ABI_FUTURE Flags: none Version: 1
"""
try:
module.required_glibc_versions(unknown_abi)
except ValueError as error:
assert "unknown GLIBC ABI requirement" in str(error)
else:
raise AssertionError("unknown GLIBC ABI requirement was accepted")
PY
evil_bundle="$temporary/evil-bundle"
evil_build="$temporary/evil-build"
cp -a -- "$bundle" "$evil_bundle"
mkdir "$evil_build"
cat >"$temporary/evil-dependency.c" <<'C'
int echoion_evil_dependency(void) { return 13; }
C
cat >"$temporary/evil-user.c" <<'C'
extern int echoion_evil_dependency(void);
int echoion_evil_user(void) { return echoion_evil_dependency(); }
C
cc -fPIC -shared "$temporary/evil-dependency.c" \
-Wl,-soname,libc.so.evil -o "$evil_build/libc.so.evil"
cc -fPIC -shared "$temporary/evil-user.c" \
-L"$evil_build" -Wl,-l:libc.so.evil -Wl,-rpath,"$evil_build" \
-o "$evil_build/libevil-user.so"
rm "$evil_build/libc.so.evil"
if cmake \
"-DBUNDLE_ROOT=$evil_bundle" \
"-DBUNDLE_RESOLVER_LIBRARIES=$evil_build/libevil-user.so" \
"-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \
"-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_root/cmake/BundleRuntimeDependencies.cmake" \
>/dev/null 2>&1; then
echo "fake glibc-like SONAME was treated as a system dependency" >&2
exit 1
fi
report="$temporary/dependencies.txt"
python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" --max-glibc 2.35 --report "$report"
grep -F $'NEEDED\tlib/Echoion.ts\tlibechoion-dependency.so.1\tbundled' "$report"
grep -F $'NEEDED\tbin/echoiond\tlibc.so.6\tsystem' "$report"
[[ -L $bundle/lib/libechoion-dependency.so.1 ]]
[[ $(readlink "$bundle/lib/libechoion-dependency.so.1") != /* ]]
[[ -f $bundle/lib/libechoion-dependency.so.1.2.3 ]]
readelf -p .echoion_variant \
"$bundle/lib/libechoion-dependency.so.1.2.3" | grep -F preferred-runtime
if readelf -p .echoion_variant \
"$bundle/lib/libechoion-dependency.so.1.2.3" | grep -Fq other-runtime; then
echo "search-directory runtime replaced the exact build resolver runtime" >&2
exit 1
fi
readelf -p .echoion_compiler_variant \
"$bundle/lib/libstdc++.so.6.0.100" | grep -F seeded-compiler-runtime
if find "$bundle/lib" -maxdepth 1 -name 'libstdc++.so.6.0.200' | grep -q .; then
echo "resolver compiler runtime leaked beside the exact seed" >&2
exit 1
fi
if find "$bundle/lib" -maxdepth 1 -name 'libc.so*' | grep -q .; then
echo "glibc was unexpectedly bundled" >&2
exit 1
fi
patchelf --set-rpath /tmp/unsafe-build-path "$bundle/lib/Echoion.ts"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
echo "absolute Core RUNPATH unexpectedly passed validation" >&2
exit 1
fi
patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts"
python3 - "$bundle/lib/Echoion.ts" <<'PY'
import sys
with open(sys.argv[1], "r+b") as stream:
stream.seek(18)
stream.write(b"\xb7\x00") # EM_AARCH64 in a little-endian ELF header.
PY
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
echo "non-x86-64 Core unexpectedly passed validation" >&2
exit 1
fi
echo "runtime dependency bundling regressions passed"
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Validate a relocatable Linux ELF closure without executing its binaries."""
from __future__ import annotations
import argparse
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import subprocess
import tempfile
SYSTEM_DEPENDENCIES = tuple(
re.compile(pattern)
for pattern in (
r"^linux-vdso\.so\.1$",
r"^ld-linux-x86-64\.so\.2$",
r"^libc\.so\.6$",
r"^libm\.so\.6$",
r"^libmvec\.so\.1$",
r"^libdl\.so\.2$",
r"^libpthread\.so\.0$",
r"^librt\.so\.1$",
r"^libresolv\.so\.2$",
r"^libutil\.so\.1$",
r"^libanl\.so\.1$",
r"^libBrokenLocale\.so\.1$",
r"^libthread_db\.so\.1$",
)
)
NEEDED_PATTERN = re.compile(r"\(NEEDED\).*Shared library: \[([^]]+)]")
RUNPATH_PATTERN = re.compile(r"\((?:RPATH|RUNPATH)\).*Library r(?:un)?path: \[([^]]*)]")
INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]")
GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b")
GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$")
GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)}
def parse_version(value: str) -> tuple[int, ...]:
if not re.fullmatch(r"\d+(?:\.\d+){1,2}", value):
raise ValueError(f"invalid ABI version: {value!r}")
return tuple(int(component) for component in value.split("."))
def required_glibc_versions(version_info: str) -> set[tuple[int, ...]]:
versions: set[tuple[int, ...]] = set()
in_needs = False
for line in version_info.splitlines():
if line.startswith("Version needs section"):
in_needs = True
continue
if in_needs and line.startswith("Version "):
break
if not in_needs:
continue
name_match = GLIBC_NAME_PATTERN.search(line)
if name_match is None:
continue
name = name_match.group(1)
if name in GLIBC_ABI_MINIMUMS:
versions.add(GLIBC_ABI_MINIMUMS[name])
elif name.startswith("GLIBC_ABI_"):
raise ValueError(f"unknown GLIBC ABI requirement: {name}")
elif version_match := GLIBC_VERSION_PATTERN.fullmatch(name):
versions.add(
tuple(
int(component)
for component in version_match.groups()
if component is not None
)
)
return versions
def command_output(arguments: list[str]) -> str:
environment = os.environ.copy()
environment["LC_ALL"] = "C"
completed = subprocess.run(
arguments,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=environment,
)
if completed.returncode != 0:
message = completed.stderr.strip() or completed.stdout.strip()
raise ValueError(f"{' '.join(arguments)} failed: {message}")
return completed.stdout
def is_elf(path: Path) -> bool:
with path.open("rb") as stream:
return stream.read(4) == b"\x7fELF"
def is_system_dependency(name: str) -> bool:
return any(pattern.fullmatch(name) for pattern in SYSTEM_DEPENDENCIES)
def ensure_inside(path: Path, directory: Path, description: str) -> None:
try:
path.resolve(strict=True).relative_to(directory)
except (FileNotFoundError, RuntimeError, ValueError) as error:
raise ValueError(f"{description} escapes the bundle or is dangling: {path}") from error
def validate_symlinks(library_dir: Path) -> None:
for path in sorted(library_dir.iterdir()):
if not path.is_symlink():
continue
target = os.readlink(path)
pure_target = PurePosixPath(target)
if not target or pure_target.is_absolute() or ".." in pure_target.parts:
raise ValueError(f"unsafe library symlink: {path.name} -> {target}")
ensure_inside(path, library_dir, "library symlink")
def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]:
executable = root / "bin/echoiond"
core = root / "lib/Echoion.ts"
library_dir = (root / "lib").resolve(strict=True)
for required in (executable, core):
if not required.is_file() or required.is_symlink() or not is_elf(required):
raise ValueError(f"missing regular ELF payload: {required}")
validate_symlinks(library_dir)
elf_files: list[Path] = [executable]
for path in sorted(library_dir.iterdir()):
if path.is_symlink():
continue
if not path.is_file() or not is_elf(path):
raise ValueError(f"unexpected non-ELF entry in lib/: {path}")
elf_files.append(path)
report: list[str] = []
for path in elf_files:
relative = path.relative_to(root).as_posix()
header = command_output(["readelf", "-hW", os.fspath(path)])
if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE):
raise ValueError(f"{relative} is not a 64-bit ELF")
if not re.search(
r"^\s*Machine:\s+Advanced Micro Devices X86-64\s*$",
header,
re.MULTILINE,
):
raise ValueError(f"{relative} is not an x86-64 ELF")
dynamic = command_output(["readelf", "-dW", os.fspath(path)])
runpaths = RUNPATH_PATTERN.findall(dynamic)
expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN"
if runpaths != [expected_runpath]:
raise ValueError(
f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}"
)
report.append(f"ELF\t{relative}\tRUNPATH={expected_runpath}")
for needed in NEEDED_PATTERN.findall(dynamic):
if "/" in needed or needed in ("", ".", ".."):
raise ValueError(f"unsafe DT_NEEDED entry in {relative}: {needed!r}")
if is_system_dependency(needed):
location = "system"
else:
dependency = library_dir / needed
if not dependency.exists():
raise ValueError(f"unresolved DT_NEEDED in {relative}: {needed}")
ensure_inside(dependency, library_dir, "DT_NEEDED dependency")
location = "bundled"
report.append(f"NEEDED\t{relative}\t{needed}\t{location}")
version_info = command_output(
["readelf", "--version-info", "-W", os.fspath(path)]
)
glibc_versions = required_glibc_versions(version_info)
if maximum_glibc is not None:
incompatible = sorted(
version for version in glibc_versions if version > maximum_glibc
)
if incompatible:
rendered = ", ".join(
".".join(map(str, version)) for version in incompatible
)
maximum = ".".join(map(str, maximum_glibc))
raise ValueError(
f"{relative} requires GLIBC newer than {maximum}: {rendered}"
)
if glibc_versions:
newest = ".".join(map(str, max(glibc_versions)))
report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}")
program_headers = command_output(["readelf", "-lW", os.fspath(executable)])
interpreter_match = INTERPRETER_PATTERN.search(program_headers)
if interpreter_match is None:
raise ValueError("echoiond has no ELF interpreter")
interpreter = interpreter_match.group(1)
if not re.fullmatch(
r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)",
interpreter,
):
raise ValueError(f"unexpected ELF interpreter: {interpreter}")
report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem")
return sorted(report)
def write_report(lines: list[str], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
stream.write("# Echoion runtime dependency report\n")
stream.write("# Generated with readelf; no payload executable was run.\n")
for line in lines:
stream.write(f"{line}\n")
os.chmod(temporary_name, 0o644)
os.replace(temporary_name, output)
except BaseException:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
raise
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--report", type=Path)
parser.add_argument("--max-glibc", type=parse_version)
arguments = parser.parse_args()
if shutil.which("readelf") is None:
parser.error("readelf is required")
try:
root = arguments.root.resolve(strict=True)
report = validate(root, arguments.max_glibc)
except (OSError, ValueError) as error:
parser.error(str(error))
if arguments.report:
write_report(report, arguments.report)
else:
print("\n".join(report))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+9 -41
View File
@@ -1,43 +1,11 @@
# Echoion Standalone systemd service
# Echoion systemd compatibility note
Echoion is deployed as the `echoiond` standalone daemon. The legacy TeamSpeak
client plugin and its graphical/headless TeamSpeak client services are no
longer supported.
Service installation is owned by `packaging/install.sh`; the rendered source
template is `packaging/service/echoion.service.in`. The installer understands
system, user, and portable prefixes, escapes paths correctly, records the unit
hash for safe upgrades/removal, and leaves the service disabled and stopped
unless `--start` is supplied.
## Install
Build and install Echoion, then copy the user service:
```bash
mkdir -p ~/.config/systemd/user
cp systemd/echoion-standalone.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now echoion-standalone.service
```
For a service that starts before interactive login, enable lingering for the
service account:
```bash
sudo loginctl enable-linger "$USER"
```
The service expects the installed `echoiond` executable, configuration, and
release manifest paths documented in `echoion-standalone.service`. Override
them without editing the tracked unit:
```bash
systemctl --user edit echoion-standalone.service
```
## Operations
```bash
systemctl --user status echoion-standalone.service
journalctl --user -u echoion-standalone.service -f
systemctl --user restart echoion-standalone.service
```
TeamSpeak protocol, query transport, identity, and typed administration are
provided by VoidTeamspeak. EchoionStandalone only adapts those APIs to the
Echoion core contracts.
See the root README installation section for current commands. The old manual
unit and two-file release manifest were removed because they could not describe
the relocatable whole-payload release safely.
-35
View File
@@ -1,35 +0,0 @@
# Echoion standalone daemon. TeamSpeak transport and protocol behavior are
# provided by VoidTeamspeak; this process hosts the Echoion adapter and core.
#
# Install: copy `echoiond` and `Echoion.ts` (the Core library) somewhere on
# disk, put config.json in ~/.config/echoion/ (or pass --config), then:
# systemctl --user enable --now echoion-standalone
#
# Identity is generated on first run and persisted to
# ~/.config/echoion/identity.txt (override with ECHOION_IDENTITY_PATH).
# Import an existing TeamSpeak-exported identity before enabling the service:
# echoiond --import-identity identity.ini
[Unit]
Description=Echoion Music Bot (standalone TeamSpeak client)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Directory holding echoiond and the Core library Echoion.ts.
WorkingDirectory=%h/echoion
Environment=ECHOION_CORE_PATH=%h/echoion/Echoion.ts
# Atomically replace this manifest after staging and hashing a complete release.
Environment=ECHOION_RELEASE_MANIFEST=%h/echoion/releases/pending-release.json
# Optional tuning:
# Environment=ECHOION_SECURITY_LEVEL=8
# Environment=ECHOION_OPUS_BITRATE=96000
# Environment=ECHOION_IDENTITY_PATH=%h/.config/echoion/identity.txt
ExecStart=%h/echoion/echoiond --config %h/.config/echoion/config.json
Restart=always
RestartSec=5
LimitNOFILE=65536
[Install]
WantedBy=default.target
-9
View File
@@ -1,9 +0,0 @@
{
"version": "1.1.0",
"executable": "1.1.0/echoiond",
"core": "1.1.0/Echoion.ts",
"sha256": {
"executable": "replace-with-lowercase-sha256",
"core": "replace-with-lowercase-sha256"
}
}