Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-12 02:57:35 +03:00
1 parent 4a92d09e63
commit 45eb2cab42
12 files changed
+991 -162

No files matched your search

+51 -2
View File
@@ -1,7 +1,7 @@
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
#
# It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core,
# and implements IPluginInterface with EchoionProtocol's native UDP client.
# and implements IPluginInterface with the reusable VoidTeamspeak client.
cmake_minimum_required(VERSION 4.0.0)
project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX)
@@ -14,12 +14,15 @@ find_package(PkgConfig REQUIRED)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil)
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
add_executable(EchoionStandalone
src/main.cpp
src/StandaloneClientInterface.cpp
src/AudioEncoder.cpp
src/MessageChunker.cpp
src/ReleaseManifest.cpp
src/EventCallbackGate.cpp
)
target_include_directories(EchoionStandalone PRIVATE
@@ -27,7 +30,7 @@ target_include_directories(EchoionStandalone PRIVATE
)
target_link_libraries(EchoionStandalone PRIVATE
Echoion::Protocol
Void::TeamSpeak
Echoion::Host
Echoion::ApiBase
Echoion::ApiPlugin
@@ -36,11 +39,14 @@ target_link_libraries(EchoionStandalone PRIVATE
Echoion::ApiCoreInterface
Echoion::ApiLogger
Void::Data
Void::Core
Void::Log
Void::System
Void::Stacktrace
Threads::Threads
PkgConfig::SWRESAMPLE
PkgConfig::OPUS
OpenSSL::Crypto
)
set_target_properties(EchoionStandalone PROPERTIES
@@ -51,6 +57,17 @@ set_target_properties(EchoionStandalone PROPERTIES
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
if(BUILD_TESTS)
add_executable(echoion_core_loader_reload_tests
tests/test_core_loader_reload.cpp)
target_link_libraries(echoion_core_loader_reload_tests PRIVATE
Echoion::Host Echoion::ApiCoreInterface)
target_compile_features(echoion_core_loader_reload_tests PRIVATE cxx_std_26)
target_compile_definitions(echoion_core_loader_reload_tests PRIVATE
"ECHOION_TEST_CORE_PATH=\"$<TARGET_FILE:EchoionCore>\"")
add_dependencies(echoion_core_loader_reload_tests EchoionCore)
add_test(NAME echoion_core_loader_reload_tests
COMMAND echoion_core_loader_reload_tests)
add_executable(echoion_standalone_message_tests
tests/test_message_chunker.cpp
src/MessageChunker.cpp
@@ -61,4 +78,36 @@ if(BUILD_TESTS)
target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20)
add_test(NAME echoion_standalone_message_tests
COMMAND echoion_standalone_message_tests)
add_executable(echoion_release_manifest_tests
tests/test_release_manifest.cpp
src/ReleaseManifest.cpp
)
target_include_directories(echoion_release_manifest_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_release_manifest_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_release_manifest_tests PRIVATE
Echoion::ApiBase Void::Data Void::System OpenSSL::Crypto)
add_test(NAME echoion_release_manifest_tests
COMMAND echoion_release_manifest_tests)
add_executable(echoion_event_callback_gate_tests
tests/test_event_callback_gate.cpp
src/EventCallbackGate.cpp
)
target_include_directories(echoion_event_callback_gate_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_event_callback_gate_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_event_callback_gate_tests PRIVATE
Echoion::ApiBase Echoion::ApiConfig Echoion::ApiPlugin
Void::Core Threads::Threads)
add_test(NAME echoion_event_callback_gate_tests
COMMAND echoion_event_callback_gate_tests)
add_test(NAME echoion_stage_release_tests
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh"
"${CMAKE_SOURCE_DIR}/scripts/stage-release.sh"
$<TARGET_FILE:EchoionStandalone>)
endif()
@@ -0,0 +1,29 @@
#pragma once
#include <PluginTypes.hpp>
#include <condition_variable>
#include <cstddef>
#include <mutex>
#include <vector>
namespace Echoion::Standalone
{
// Owns plugin-event callbacks across a dynamically loaded Core boundary.
// quiesce() is a lifetime barrier: after it returns no callback object, nor
// callback invocation, can still reference code from the old Core image.
class EventCallbackGate final
{
public:
void add(Api::EventCallback callback);
void quiesce();
void dispatch(const Api::PluginEvent& event);
private:
std::mutex mutex_;
std::condition_variable cv_;
std::vector<Api::EventCallback> callbacks_;
std::size_t activeDispatches_{0};
bool accepting_{true};
};
}
@@ -0,0 +1,21 @@
#pragma once
#include <Types.hpp>
#include <filesystem>
#include <string>
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;
};
}
@@ -1,15 +1,15 @@
#pragma once
// Implements Echoion's IPluginInterface against the native TeamSpeak UDP
// protocol (EchoionProtocol) instead of the TS3 Client Plugin SDK. This is the
// protocol through VoidTeamspeak instead of the TS3 Client Plugin SDK. This is the
// single seam that lets the whole Core run as a standalone application: Core
// only ever talks to IPluginInterface, so swapping this implementation in for
// the plugin drops the TeamSpeak-client dependency entirely.
#include <PluginInterface.hpp>
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/TsClient.hpp"
#include "echoion/standalone/EventCallbackGate.hpp"
#include <Void/TeamSpeak/TeamSpeak.hpp>
#include <atomic>
#include <map>
@@ -85,6 +85,14 @@ namespace Echoion::Standalone
sendAudioData(const std::span<const short>& data) override;
Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
[[nodiscard]] Api::Result<AudioStreamId>
createAudioStream(const AudioStreamOptions& options) override;
Api::Result<void> destroyAudioStream(AudioStreamId id) override;
Api::Result<void> sendAudioDataToStream(
AudioStreamId id, const std::span<const short>& data) override;
Api::Result<void> setAudioStreamRecipients(
AudioStreamId id,
const std::vector<uint64_t>& recipients) override;
// Connection
Api::Result<void>
@@ -98,23 +106,28 @@ namespace Echoion::Standalone
registerEventCallback(const Api::EventCallback& cb) override;
void
unregisterEventCallback(const Api::EventCallback& cb) override;
// Prevent new event dispatches, release registered callbacks and wait
// until every callback already in flight has returned. The host must
// call this before unloading code that owns an event callback.
void quiesceEventCallbacks();
private:
void wireCallbacks();
void onCommand(const Protocol::ParsedCommand& parsed);
void onTextMessage(const Protocol::CommandParams& params);
void onCommand(std::string_view name,
const std::vector<Void::TeamSpeak::CommandFields>& records);
void onTextMessage(const Void::TeamSpeak::CommandFields& params);
void broadcast(const Api::PluginEvent& event);
void upsertClientGroup(const Protocol::CommandParams& p,
void upsertClientGroup(const Void::TeamSpeak::CommandFields& p,
bool emitConnected);
void refreshClient(const Protocol::CommandParams& params);
void refreshClient(const Void::TeamSpeak::CommandFields& params);
void loadInitialSnapshot();
[[nodiscard]] Api::Result<void>
commandResult(const Protocol::CommandResult& result) const;
[[nodiscard]] Api::Result<void> commandResult(
const Void::Result::Result<void, Void::TeamSpeak::Error>& result) const;
StandaloneSettings settings_;
std::unique_ptr<Protocol::Identity> identity_;
std::unique_ptr<Protocol::TsClient> client_;
std::shared_ptr<Void::TeamSpeak::Identity> identity_;
std::unique_ptr<Void::TeamSpeak::Client> client_;
std::unique_ptr<AudioEncoder> encoder_;
Api::ServerConfig currentConfig_{};
@@ -128,10 +141,13 @@ namespace Echoion::Standalone
std::map<uint64_t, std::string> avatarUrls_;
std::map<uint64_t, std::string> avatarPaths_;
std::vector<uint64_t> whisperList_;
struct AudioStreamRuntime;
std::map<AudioStreamId, std::shared_ptr<AudioStreamRuntime>> audioStreams_;
std::atomic<AudioStreamId> nextAudioStreamId_{1};
mutable std::mutex audioStreamsMutex_;
std::jthread snapshotThread_;
std::mutex cbMutex_;
std::vector<Api::EventCallback> callbacks_;
EventCallbackGate eventCallbacks_;
};
} // namespace Echoion::Standalone
+42
View File
@@ -0,0 +1,42 @@
#include "echoion/standalone/EventCallbackGate.hpp"
#include <Void/Core/Scope.hpp>
#include <utility>
namespace Echoion::Standalone
{
void EventCallbackGate::add(Api::EventCallback callback)
{
std::lock_guard lock(mutex_);
accepting_ = true;
callbacks_.push_back(std::move(callback));
}
void EventCallbackGate::quiesce()
{
std::unique_lock lock(mutex_);
accepting_ = false;
callbacks_.clear();
cv_.wait(lock, [this] { return activeDispatches_ == 0; });
}
void EventCallbackGate::dispatch(const Api::PluginEvent& event)
{
std::vector<Api::EventCallback> callbacks;
{
std::lock_guard lock(mutex_);
if (!accepting_) return;
++activeDispatches_;
callbacks = callbacks_;
}
const auto complete = Void::Scope::on_exit([this] {
std::lock_guard lock(mutex_);
--activeDispatches_;
cv_.notify_all();
});
for (const auto& callback : callbacks) {
if (callback) callback(event);
}
}
}
+127
View File
@@ -0,0 +1,127 @@
#include "echoion/standalone/ReleaseManifest.hpp"
#include <Void/Data/Json.hpp>
#include <Void/System/Path.hpp>
#include <openssl/evp.h>
#include <array>
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <memory>
#include <sstream>
namespace Echoion::Standalone
{
namespace
{
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());
}
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) {
return Api::fail(Api::ErrorCode::UnknownError,
"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 &&
EVP_DigestUpdate(context.get(), buffer.data(),
static_cast<std::size_t>(count)) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"cannot hash release artifact");
}
}
std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
unsigned int size = 0;
if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) {
return Api::fail(Api::ErrorCode::UnknownError,
"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]);
}
return output.str();
}
}
Api::Result<ReleaseManifest>
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());
}
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);
}
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");
}
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");
}
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");
}
return manifest;
}
Api::Result<void> ReleaseManifest::validate() const
{
if (!std::filesystem::is_regular_file(executable) ||
!std::filesystem::is_regular_file(core)) {
return Api::fail(Api::ErrorCode::NotFound,
"release executable and Core must be regular files");
}
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}}) {
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 {};
}
}
+296 -138
View File
@@ -2,18 +2,27 @@
#include "echoion/standalone/AudioEncoder.hpp"
#include "echoion/standalone/MessageChunker.hpp"
#include "echoion/protocol/Command.hpp"
#include <Void/Log/Log.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/TeamSpeak/Client.hpp>
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <format>
#include <limits>
#include <sstream>
namespace Echoion::Standalone
{
struct StandaloneClientInterface::AudioStreamRuntime {
std::mutex mutex;
std::shared_ptr<Void::TeamSpeak::Identity> identity;
std::unique_ptr<Void::TeamSpeak::Client> client;
std::unique_ptr<AudioEncoder> encoder;
std::vector<uint64_t> recipients;
};
namespace
{
constexpr const char* LOG = "Standalone";
@@ -27,7 +36,7 @@ namespace Echoion::Standalone
}
}
std::string get(const Protocol::CommandParams& p, const char* k)
std::string get(const Void::TeamSpeak::CommandFields& p, const char* k)
{
auto it = p.find(k);
return it == p.end() ? std::string{} : it->second;
@@ -71,7 +80,7 @@ namespace Echoion::Standalone
return {};
}
encoder_ = std::make_unique<AudioEncoder>(settings_.opusBitrate);
client_ = std::make_unique<Protocol::TsClient>();
client_ = std::make_unique<Void::TeamSpeak::Client>();
Void::Log::info(LOG, "Standalone client interface initialized");
return {};
}
@@ -81,8 +90,19 @@ namespace Echoion::Standalone
if (!initialized_.exchange(false)) {
return {};
}
std::vector<std::shared_ptr<AudioStreamRuntime>> streams;
{
std::lock_guard<std::mutex> lock(audioStreamsMutex_);
streams.reserve(audioStreams_.size());
for (auto& entry : audioStreams_) streams.push_back(entry.second);
audioStreams_.clear();
}
for (const auto& stream : streams) {
std::lock_guard lock(stream->mutex);
stream->client->close();
}
if (client_) {
client_->forceClose();
client_->close();
}
if (snapshotThread_.joinable()) {
snapshotThread_.request_stop();
@@ -110,16 +130,16 @@ namespace Echoion::Standalone
try {
std::filesystem::path idPath(settings_.identityPath);
if (!idPath.empty() && std::filesystem::exists(idPath)) {
identity_ = std::make_unique<Protocol::Identity>(
Protocol::Identity::load(idPath.string()));
identity_ = std::make_shared<Void::TeamSpeak::Identity>(
Void::TeamSpeak::Identity::load(idPath.string()));
Void::Log::info(LOG, "Loaded identity (uid={})",
identity_->uid());
} else {
Void::Log::info(LOG,
"Generating identity (security level {})...",
settings_.securityLevel);
identity_ = std::make_unique<Protocol::Identity>(
Protocol::Identity::generate(settings_.securityLevel));
identity_ = std::make_shared<Void::TeamSpeak::Identity>(
Void::TeamSpeak::Identity::generate(settings_.securityLevel));
if (!idPath.empty()) {
std::filesystem::create_directories(idPath.parent_path());
identity_->save(idPath.string());
@@ -134,21 +154,19 @@ namespace Echoion::Standalone
wireCallbacks();
Protocol::TsClientOptions opts;
Void::TeamSpeak::ConnectOptions opts;
opts.host = config.address;
opts.port = config.port ? config.port : 9987;
opts.identity = identity_.get();
opts.identity = identity_;
opts.nickname = config.nickname.empty() ? "EchoionBot" : config.nickname;
opts.serverPassword = config.serverPassword;
opts.defaultChannel =
config.defaultChannelId.value_or(std::string{});
opts.channelPassword = config.channelPassword.value_or(std::string{});
try {
client_->connect(opts);
} catch (const std::exception& e) {
if (auto connected = client_->connect(opts); !connected) {
return Api::fail(Api::ErrorCode::NetworkError,
std::string("connect failed: ") + e.what());
"connect failed: " + connected.error().message);
}
Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port,
opts.nickname);
@@ -157,15 +175,15 @@ namespace Echoion::Standalone
void StandaloneClientInterface::wireCallbacks()
{
Protocol::TsClientCallbacks cb;
cb.onConnected = [this] {
Void::TeamSpeak::Events cb;
cb.connected = [this] {
if (snapshotThread_.joinable()) {
snapshotThread_.request_stop();
snapshotThread_.join();
}
snapshotThread_ = std::jthread([this] { loadInitialSnapshot(); });
};
cb.onDisconnected = [this] {
cb.disconnected = [this] {
Void::Log::warn(LOG, "Disconnected from server");
std::lock_guard<std::mutex> lock(mirrorMutex_);
clients_.clear();
@@ -174,36 +192,32 @@ namespace Echoion::Standalone
avatarHashes_.clear();
avatarUrls_.clear();
};
cb.onError = [](const std::string& msg) {
Void::Log::error(LOG, "Protocol error: {}", msg);
cb.error = [](const Void::TeamSpeak::Error& error) {
Void::Log::error(LOG, "Protocol error: {}", error.message);
};
cb.onCommand = [this](const Protocol::ParsedCommand& p) {
onCommand(p);
cb.commandBatch = [this](const Void::TeamSpeak::CommandEvent& command) {
onCommand(command.name, command.records);
if (command.name == "notifytextmessage") {
for (const auto& record : command.records) onTextMessage(record);
}
};
cb.onTextMessage = [this](const Protocol::CommandParams& p) {
onTextMessage(p);
};
cb.onDebug = [](const std::string& msg) {
cb.debug = [](std::string_view msg) {
Void::Log::debug(LOG, "{}", msg);
};
cb.onVoice = [this](std::span<const uint8_t>) {
cb.voice = [this](std::span<const uint8_t>) {
Api::PluginEvent event;
event.type = Api::PluginEventType::VoiceDataReceived;
event.timestamp = std::chrono::system_clock::now();
broadcast(event);
};
client_->setCallbacks(std::move(cb));
client_->setEvents(std::move(cb));
}
Api::Result<void> StandaloneClientInterface::commandResult(
const Protocol::CommandResult& result) const
const Void::Result::Result<void, Void::TeamSpeak::Error>& result) const
{
if (result.ok()) {
return {};
}
return Api::fail(Api::ErrorCode::NetworkError,
"TeamSpeak error " + std::to_string(result.errorId) + ": " +
result.errorMessage);
return result ? Api::Result<void>{}
: Api::fail(Api::ErrorCode::NetworkError, result.error().message);
}
void StandaloneClientInterface::loadInitialSnapshot()
@@ -211,29 +225,29 @@ namespace Echoion::Standalone
if (!client_) {
return;
}
auto clients = client_->requestCommand(
auto clients = client_->request(
"clientlist -uid -groups -voice -away -times -info -country -ip");
if (clients.ok()) {
for (const auto& record : clients.records) {
if (clients) {
for (const auto& record : clients->records) {
refreshClient(record);
}
} else {
Void::Log::warn(LOG, "Initial client snapshot failed: {}",
clients.errorMessage);
clients.error().message);
}
auto channels = client_->requestCommand(
auto channels = client_->request(
"channellist -topic -flags -voice -limits");
if (channels.ok()) {
onCommand(Protocol::ParsedCommand{.name = "channellist",
.params = channels.records.empty()
? Protocol::CommandParams{}
: channels.records.front(),
.groups = channels.records});
if (channels) {
onCommand("channellist", channels->records);
} else {
Void::Log::warn(LOG, "Initial channel snapshot failed: {}",
channels.errorMessage);
channels.error().message);
}
if (auto subscribed = client_->request("channelsubscribeall");
!subscribed) {
Void::Log::warn(LOG, "Channel subscription failed: {}",
subscribed.error().message);
}
client_->sendCommand("channelsubscribeall");
Api::PluginEvent event;
event.type = Api::PluginEventType::ConnectionEstablished;
event.timestamp = std::chrono::system_clock::now();
@@ -251,7 +265,7 @@ namespace Echoion::Standalone
bool StandaloneClientInterface::isConnected() const
{
return client_ &&
client_->state() == Protocol::ClientState::Connected;
client_->state() == Void::TeamSpeak::ConnectionState::Connected;
}
Api::Result<void> StandaloneClientInterface::reconnect()
@@ -263,7 +277,7 @@ namespace Echoion::Standalone
// ---- Event mirror ------------------------------------------------------
void StandaloneClientInterface::upsertClientGroup(
const Protocol::CommandParams& p, bool emitConnected)
const Void::TeamSpeak::CommandFields& p, bool emitConnected)
{
uint64_t clid = toU64(get(p, "clid"));
if (clid == 0) {
@@ -290,7 +304,7 @@ namespace Echoion::Standalone
}
void StandaloneClientInterface::refreshClient(
const Protocol::CommandParams& params)
const Void::TeamSpeak::CommandFields& params)
{
const auto idText = !get(params, "clid").empty()
? get(params, "clid")
@@ -346,20 +360,18 @@ namespace Echoion::Standalone
}
}
void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p)
void StandaloneClientInterface::onCommand(std::string_view name,
const std::vector<Void::TeamSpeak::CommandFields>& records)
{
const auto& groups =
p.groups.empty()
? std::vector<Protocol::CommandParams>{p.params}
: p.groups;
const auto& groups = records;
if (p.name == "notifycliententerview" || p.name == "clientlist" ||
p.name == "clientinfo" || p.name == "notifyclientupdated" ||
p.name == "notifytalkstatuschange") {
if (name == "notifycliententerview" || name == "clientlist" ||
name == "clientinfo" || name == "notifyclientupdated" ||
name == "notifytalkstatuschange") {
for (const auto& g : groups) {
upsertClientGroup(g, p.name == "notifycliententerview");
upsertClientGroup(g, name == "notifycliententerview");
}
} else if (p.name == "notifyclientleftview") {
} else if (name == "notifyclientleftview") {
for (const auto& g : groups) {
uint64_t clid = toU64(get(g, "clid"));
if (clid == 0) {
@@ -381,7 +393,7 @@ namespace Echoion::Standalone
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
} else if (p.name == "notifyclientmoved") {
} else if (name == "notifyclientmoved") {
for (const auto& g : groups) {
uint64_t clid = toU64(get(g, "clid"));
uint64_t ctid = toU64(get(g, "ctid"));
@@ -400,15 +412,15 @@ namespace Echoion::Standalone
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
} else if (p.name == "notifychanneldeleted") {
} else if (name == "notifychanneldeleted") {
std::lock_guard<std::mutex> lock(mirrorMutex_);
for (const auto& group : groups) {
channels_.erase(toU64(get(group, "cid")));
}
} else if (p.name == "channellist" || p.name == "notifychannellist" ||
p.name == "notifychannelcreated" ||
p.name == "notifychanneledited" ||
p.name == "notifychannelmoved") {
} else if (name == "channellist" || name == "notifychannellist" ||
name == "notifychannelcreated" ||
name == "notifychanneledited" ||
name == "notifychannelmoved") {
std::lock_guard<std::mutex> lock(mirrorMutex_);
for (const auto& g : groups) {
uint64_t cid = toU64(get(g, "cid"));
@@ -438,10 +450,10 @@ namespace Echoion::Standalone
}
void StandaloneClientInterface::onTextMessage(
const Protocol::CommandParams& params)
const Void::TeamSpeak::CommandFields& params)
{
uint64_t invoker = toU64(get(params, "invokerid"));
if (client_ && invoker == client_->clientId()) {
if (client_ && invoker == client_->id().value) {
return; // ignore our own messages
}
Api::PluginEvent ev;
@@ -458,14 +470,7 @@ namespace Echoion::Standalone
void StandaloneClientInterface::broadcast(const Api::PluginEvent& event)
{
std::vector<Api::EventCallback> cbs;
{
std::lock_guard<std::mutex> lock(cbMutex_);
cbs = callbacks_;
}
for (const auto& cb : cbs) {
cb(event);
}
eventCallbacks_.dispatch(event);
}
// ---- Clients / channels ------------------------------------------------
@@ -499,18 +504,18 @@ namespace Echoion::Standalone
if (!client_ || !isConnected()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
}
Protocol::CommandParams parameters;
Void::TeamSpeak::CommandFields parameters;
parameters["clid"] = std::to_string(clientId);
auto result = client_->requestCommand(
Protocol::buildCommand("clientconnectioninfo", parameters));
if (!result.ok()) {
result = client_->requestCommand(
Protocol::buildCommand("clientinfo", parameters));
auto result = client_->request(
Void::TeamSpeak::buildCommand("clientconnectioninfo", parameters));
if (!result) {
result = client_->request(
Void::TeamSpeak::buildCommand("clientinfo", parameters));
}
if (!result.ok()) {
return Api::fail(Api::ErrorCode::NetworkError, result.errorMessage);
if (!result) {
return Api::fail(Api::ErrorCode::NetworkError, result.error().message);
}
for (const auto& record : result.records) {
for (const auto& record : result->records) {
refreshClient(record);
}
std::lock_guard<std::mutex> lock(mirrorMutex_);
@@ -536,12 +541,12 @@ namespace Echoion::Standalone
StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId)
{
if (client_ && isConnected()) {
Protocol::CommandParams parameters;
Void::TeamSpeak::CommandFields parameters;
parameters["clid"] = std::to_string(clientId);
const auto result = client_->requestCommand(
Protocol::buildCommand("clientinfo", parameters));
if (result.ok()) {
for (const auto& record : result.records) {
const auto result = client_->request(
Void::TeamSpeak::buildCommand("clientinfo", parameters));
if (result) {
for (const auto& record : result->records) {
refreshClient(record);
}
}
@@ -560,14 +565,14 @@ namespace Echoion::Standalone
if (!client_ || !isConnected()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
}
Protocol::CommandParams parameters;
Void::TeamSpeak::CommandFields parameters;
parameters["clid"] = std::to_string(clientId);
const auto info =
client_->requestCommand(Protocol::buildCommand("clientinfo", parameters));
if (!info.ok()) {
return Api::fail(Api::ErrorCode::NetworkError, info.errorMessage);
client_->request(Void::TeamSpeak::buildCommand("clientinfo", parameters));
if (!info) {
return Api::fail(Api::ErrorCode::NetworkError, info.error().message);
}
for (const auto& record : info.records) {
for (const auto& record : info->records) {
refreshClient(record);
}
std::string hash;
@@ -597,11 +602,11 @@ namespace Echoion::Standalone
const auto destination =
(std::filesystem::path(directory) / ("avatar_" + hash)).string();
if (!std::filesystem::exists(destination)) {
const auto result =
client_->downloadFile("/avatar_" + hash, destination);
if (!result.ok()) {
const auto result = client_->download(
"/avatar_" + hash, destination);
if (!result) {
return Api::fail(Api::ErrorCode::NetworkError,
result.errorMessage);
result.error().message);
}
}
{
@@ -640,11 +645,13 @@ namespace Echoion::Standalone
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["clid"] = std::to_string(clientId);
p["cid"] = std::to_string(channelId);
return commandResult(
client_->requestCommand(Protocol::buildCommand("clientmove", p)));
if (clientId == 0 || clientId > std::numeric_limits<uint16_t>::max()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"client ID exceeds TeamSpeak protocol range");
}
return commandResult(client_->move(
Void::TeamSpeak::ClientId{static_cast<uint16_t>(clientId)},
Void::TeamSpeak::ChannelId{channelId}));
}
Api::Result<void>
@@ -654,12 +661,12 @@ namespace Echoion::Standalone
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["clid"] = std::to_string(clientId);
p["reasonid"] = "5"; // kick from server
p["reasonmsg"] = reason;
return commandResult(
client_->requestCommand(Protocol::buildCommand("clientkick", p)));
if (clientId == 0 || clientId > std::numeric_limits<uint16_t>::max()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"client ID exceeds TeamSpeak protocol range");
}
return commandResult(client_->kick(
Void::TeamSpeak::ClientId{static_cast<uint16_t>(clientId)}, reason));
}
// ---- Messaging ---------------------------------------------------------
@@ -672,12 +679,10 @@ namespace Echoion::Standalone
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
for (const auto& chunk : chunkMessage(message)) {
Protocol::CommandParams p;
p["targetmode"] = "1"; // client
p["target"] = std::to_string(targetId);
p["msg"] = chunk;
if (auto result = commandResult(client_->requestCommand(
Protocol::buildCommand("sendtextmessage", p)));
if (auto result = commandResult(client_->sendText(
Void::TeamSpeak::TextTarget{
.kind = Void::TeamSpeak::TextTargetKind::Client,
.id = targetId}, chunk));
!result) {
Void::Log::warn(LOG,
"Failed to send help/reply chunk ({} bytes): {}",
@@ -695,12 +700,9 @@ namespace Echoion::Standalone
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["targetmode"] = "2"; // channel
p["target"] = std::to_string(channelId);
p["msg"] = message;
return commandResult(client_->requestCommand(
Protocol::buildCommand("sendtextmessage", p)));
return commandResult(client_->sendText(Void::TeamSpeak::TextTarget{
.kind = Void::TeamSpeak::TextTargetKind::Channel,
.id = channelId}, message));
}
Api::Result<void>
@@ -709,11 +711,8 @@ namespace Echoion::Standalone
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["targetmode"] = "3"; // server
p["msg"] = message;
return commandResult(client_->requestCommand(
Protocol::buildCommand("sendtextmessage", p)));
return commandResult(client_->sendText(Void::TeamSpeak::TextTarget{
.kind = Void::TeamSpeak::TextTargetKind::Server}, message));
}
// ---- Audio -------------------------------------------------------------
@@ -722,7 +721,7 @@ namespace Echoion::Standalone
StandaloneClientInterface::sendAudioData(const std::span<const short>& data)
{
if (!client_ || !encoder_ ||
client_->state() != Protocol::ClientState::Connected) {
client_->state() != Void::TeamSpeak::ConnectionState::Connected) {
return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
}
std::vector<uint64_t> whisper;
@@ -733,14 +732,21 @@ namespace Echoion::Standalone
auto frames = encoder_->encode(data);
for (const auto& f : frames) {
if (whisper.empty()) {
client_->sendVoice(f);
if (auto sent = client_->sendVoice(f); !sent) {
return Api::fail(Api::ErrorCode::NetworkError,
sent.error().message);
}
} else {
std::vector<uint16_t> clients;
clients.reserve(whisper.size());
Void::TeamSpeak::WhisperTargets targets;
targets.clients.reserve(whisper.size());
for (uint64_t c : whisper) {
clients.push_back(static_cast<uint16_t>(c));
targets.clients.push_back(Void::TeamSpeak::ClientId{
static_cast<uint16_t>(c)});
}
if (auto sent = client_->sendWhisper(f, targets); !sent) {
return Api::fail(Api::ErrorCode::NetworkError,
sent.error().message);
}
client_->sendWhisper(f, {}, clients);
}
}
return {};
@@ -760,13 +766,161 @@ namespace Echoion::Standalone
return {};
}
Api::Result<Api::IPluginInterface::AudioStreamId>
StandaloneClientInterface::createAudioStream(
const AudioStreamOptions& options)
{
if (!initialized_.load()) {
return Api::fail(Api::ErrorCode::NotInitialized,
"interface not initialized");
}
if (options.name.empty() || options.server.address.empty()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"stream name and server address are required");
}
if (std::ranges::any_of(options.recipients, [](uint64_t id) {
return id == 0 || id > std::numeric_limits<uint16_t>::max();
})) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"stream recipient is outside the TeamSpeak client ID range");
}
const auto id = nextAudioStreamId_.fetch_add(1);
auto runtime = std::make_shared<AudioStreamRuntime>();
const auto identityPath = std::filesystem::path(settings_.identityPath)
.parent_path() / "rooms" /
(std::format("{:016x}.identity", Void::Hash::fnv1a64(options.name)));
try {
if (std::filesystem::exists(identityPath)) {
runtime->identity = std::make_shared<Void::TeamSpeak::Identity>(
Void::TeamSpeak::Identity::load(identityPath.string()));
} else {
std::filesystem::create_directories(identityPath.parent_path());
runtime->identity = std::make_shared<Void::TeamSpeak::Identity>(
Void::TeamSpeak::Identity::generate(settings_.securityLevel));
runtime->identity->save(identityPath.string());
}
runtime->encoder = std::make_unique<AudioEncoder>(settings_.opusBitrate);
runtime->client = std::make_unique<Void::TeamSpeak::Client>();
runtime->recipients = options.recipients;
Void::TeamSpeak::Events callbacks;
callbacks.error = [id](const Void::TeamSpeak::Error& error) {
Void::Log::error(LOG, "Audio stream {} protocol error: {}", id,
error.message);
};
callbacks.disconnected = [id] {
Void::Log::warn(LOG, "Audio stream {} disconnected", id);
};
runtime->client->setEvents(std::move(callbacks));
Void::TeamSpeak::ConnectOptions connect;
connect.host = options.server.address;
connect.port = options.server.port == 0 ? 9987 : options.server.port;
connect.identity = runtime->identity;
connect.nickname = options.server.nickname.empty()
? "Echoion/" + options.name
: options.server.nickname + "/" + options.name;
connect.serverPassword = options.server.serverPassword;
connect.defaultChannel =
options.server.defaultChannelId.value_or(std::string{});
connect.channelPassword =
options.server.channelPassword.value_or(std::string{});
if (auto connected = runtime->client->connect(connect); !connected) {
return Api::fail(Api::ErrorCode::NetworkError,
connected.error().message);
}
} catch (const std::exception& exception) {
return Api::fail(Api::ErrorCode::NetworkError, exception.what());
}
std::lock_guard<std::mutex> lock(audioStreamsMutex_);
audioStreams_.emplace(id, std::move(runtime));
return id;
}
Api::Result<void>
StandaloneClientInterface::destroyAudioStream(AudioStreamId id)
{
std::shared_ptr<AudioStreamRuntime> stream;
{
std::lock_guard<std::mutex> lock(audioStreamsMutex_);
auto iterator = audioStreams_.find(id);
if (iterator == audioStreams_.end()) {
return Api::fail(Api::ErrorCode::NotFound,
"audio stream not found");
}
stream = iterator->second;
audioStreams_.erase(iterator);
}
std::lock_guard lock(stream->mutex);
stream->client->disconnect();
return {};
}
Api::Result<void> StandaloneClientInterface::sendAudioDataToStream(
AudioStreamId id, const std::span<const short>& data)
{
std::shared_ptr<AudioStreamRuntime> stream;
{
std::lock_guard<std::mutex> lock(audioStreamsMutex_);
auto iterator = audioStreams_.find(id);
if (iterator == audioStreams_.end()) {
return Api::fail(Api::ErrorCode::NotFound, "audio stream not found");
}
stream = iterator->second;
}
std::lock_guard streamLock(stream->mutex);
if (stream->client->state() !=
Void::TeamSpeak::ConnectionState::Connected) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"audio stream is not connected");
}
Void::TeamSpeak::WhisperTargets targets;
targets.clients.reserve(stream->recipients.size());
for (auto recipient : stream->recipients) {
targets.clients.push_back(Void::TeamSpeak::ClientId{
static_cast<uint16_t>(recipient)});
}
for (const auto& frame : stream->encoder->encode(data)) {
if (auto sent = stream->client->sendWhisper(frame, targets); !sent) {
return Api::fail(Api::ErrorCode::NetworkError,
sent.error().message);
}
}
return {};
}
Api::Result<void> StandaloneClientInterface::setAudioStreamRecipients(
AudioStreamId id, const std::vector<uint64_t>& recipients)
{
if (std::ranges::any_of(recipients, [](uint64_t clientId) {
return clientId == 0 ||
clientId > std::numeric_limits<uint16_t>::max();
})) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"stream recipient is outside the TeamSpeak client ID range");
}
std::shared_ptr<AudioStreamRuntime> stream;
{
std::lock_guard<std::mutex> lock(audioStreamsMutex_);
auto iterator = audioStreams_.find(id);
if (iterator == audioStreams_.end()) {
return Api::fail(Api::ErrorCode::NotFound, "audio stream not found");
}
stream = iterator->second;
}
std::lock_guard streamLock(stream->mutex);
stream->recipients = recipients;
return {};
}
// ---- Events ------------------------------------------------------------
void StandaloneClientInterface::registerEventCallback(
const Api::EventCallback& cb)
{
std::lock_guard<std::mutex> lock(cbMutex_);
callbacks_.push_back(cb);
eventCallbacks_.add(cb);
}
void StandaloneClientInterface::unregisterEventCallback(
@@ -775,8 +929,12 @@ namespace Echoion::Standalone
// Callbacks are not individually comparable (std::function); the host
// registers a single Core callback for the process lifetime, so a full
// clear on unregister is sufficient and matches usage.
std::lock_guard<std::mutex> lock(cbMutex_);
callbacks_.clear();
quiesceEventCallbacks();
}
void StandaloneClientInterface::quiesceEventCallbacks()
{
eventCallbacks_.quiesce();
}
} // namespace Echoion::Standalone
+168 -9
View File
@@ -7,12 +7,16 @@
// TeamSpeak client, no Weston/RDP, no plugin directory.
#include "echoion/host/CoreLoader.hpp"
#include "echoion/protocol/Identity.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include "echoion/standalone/ReleaseManifest.hpp"
#include <CoreInterface.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/System/FileWatcher.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Path.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <atomic>
#include <condition_variable>
@@ -30,6 +34,7 @@
namespace
{
std::atomic<bool> g_stop{false};
std::atomic<bool> g_updateRequested{false};
std::condition_variable g_cv;
std::mutex g_mu;
@@ -39,6 +44,23 @@ namespace
g_cv.notify_all();
}
void requestUpdate()
{
g_updateRequested = true;
g_cv.notify_all();
}
std::optional<std::string_view> argumentValue(
int argc, char** argv, std::string_view name)
{
for (int index = 1; index + 1 < argc; ++index) {
if (std::string_view{argv[index]} == name) {
return argv[index + 1];
}
}
return std::nullopt;
}
std::filesystem::path configDir()
{
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
@@ -50,6 +72,22 @@ namespace
return std::filesystem::path(".") / "echoion";
}
void recordInterruptedRelease(const std::filesystem::path& directory)
{
const auto transaction = directory / "release-transaction";
if (!std::filesystem::exists(transaction) ||
std::getenv("ECHOION_REEXEC_VERSION")) return;
auto version = Void::FileSystem::read_file(transaction);
if (version && !version->empty()) {
std::ignore = Void::FileSystem::atomic_write(
directory / "failed-release", *version);
Void::Log::error("main",
"Release {} failed its startup health check; stable service restored",
*version);
}
std::ignore = Void::FileSystem::remove_path(transaction);
}
std::string envOr(const char* key, const std::string& fallback)
{
const char* v = std::getenv(key);
@@ -126,7 +164,7 @@ namespace
return 2;
}
const auto identity =
Echoion::Protocol::Identity::importTeamSpeakIni(source->string());
Void::TeamSpeak::Identity::importTeamSpeakIni(source->string());
if (const auto parent = destination.parent_path(); !parent.empty()) {
std::filesystem::create_directories(parent);
}
@@ -148,8 +186,22 @@ 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")) {
auto manifest = Echoion::Standalone::ReleaseManifest::load(*validationPath);
if (!manifest) {
std::cerr << manifest.error().message << '\n';
return 2;
}
if (auto result = manifest->validate(); !result) {
std::cerr << result.error().message << '\n';
return 2;
}
return 0;
}
std::filesystem::path cfgDir = configDir();
recordInterruptedRelease(cfgDir);
std::filesystem::path cfgPath = cfgDir / "config.json";
const auto identityPath = std::filesystem::path(envOr(
"ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()));
@@ -187,6 +239,13 @@ int main(int argc, char** argv)
Void::Log::error("main", "failed to load Core: {}", r.error().message);
return 1;
}
if (const auto restorePath = argumentValue(argc, argv, "--restore-state")) {
if (auto result = loader.restoreCheckpoint(*restorePath); !result) {
Void::Log::error("main", "failed to restore restart checkpoint: {}",
result.error().message);
return 1;
}
}
auto core = loader.getCore();
if (!core) {
@@ -198,11 +257,13 @@ int main(int argc, char** argv)
interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) {
std::ignore = core->onPluginEvent(ev);
});
loader.setHotReloadPrepareCallback([interface] {
interface->quiesceEventCallbacks();
});
// Re-register the Core callback after each hot reload (new Core instance).
loader.setHotReloadCallback([&loader, interface] {
if (auto c = loader.getCore()) {
c->setPluginInterface(interface);
interface->unregisterEventCallback({});
interface->registerEventCallback(
[c](const Echoion::Api::PluginEvent& ev) {
std::ignore = c->onPluginEvent(ev);
@@ -212,21 +273,119 @@ int main(int argc, char** argv)
});
core->triggerAutoConnect();
loader.enableAutoReload();
std::unique_ptr<Void::FileSystem::FileWatcher> releaseWatcher;
std::optional<std::filesystem::path> releaseManifestPath;
if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) {
releaseManifestPath = manifest;
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(*releaseManifestPath,
[](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
requestUpdate();
}
});
Void::Log::info("main", "Watching release manifest {}",
releaseManifestPath->string());
} else {
// Compatibility mode for development. Production release bundles use
// transactional daemon re-exec instead of replacing Core in isolation.
loader.enableAutoReload();
}
std::signal(SIGINT, onSignal);
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock, [] { return g_stop.load(); });
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
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");
::unsetenv("ECHOION_REEXEC_VERSION");
Void::Log::info("main", "Release {} passed startup health check", version);
}
Void::Log::info("main", "Shutting down...");
std::optional<Echoion::Standalone::ReleaseManifest> pendingRelease;
std::filesystem::path checkpointPath;
while (!g_stop.load() && !pendingRelease) {
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock, [] {
return g_stop.load() || g_updateRequested.load();
});
}
if (g_stop.load() || !releaseManifestPath) {
break;
}
g_updateRequested = false;
auto manifest = Echoion::Standalone::ReleaseManifest::load(
*releaseManifestPath);
if (!manifest) {
Void::Log::error("main", "release rejected: {}",
manifest.error().message);
continue;
}
if (auto failed = Void::FileSystem::read_file(cfgDir / "failed-release");
failed && *failed == manifest->version) {
Void::Log::error("main",
"Release {} was previously rolled back; publish a new version to retry",
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});
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";
if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) {
Void::Log::error("main", "release checkpoint failed: {}",
checkpoint.error().message);
continue;
}
pendingRelease = std::move(*manifest);
}
releaseWatcher.reset();
Void::Log::info("main", "{}", pendingRelease
? "Applying validated release..." : "Shutting down...");
loader.disableAutoReload();
(void)interface->disconnectFromServer();
interface->quiesceEventCallbacks();
(void)loader.unload();
(void)interface->shutdown();
if (pendingRelease) {
if (auto transaction = Void::FileSystem::atomic_write(
cfgDir / "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);
std::vector<std::string> arguments;
arguments.reserve(static_cast<std::size_t>(argc) + 2);
for (int index = 1; index < argc; ++index) {
const std::string_view argument{argv[index]};
if (argument == "--restore-state") {
++index;
continue;
}
arguments.emplace_back(argument);
}
arguments.emplace_back("--restore-state");
arguments.push_back(checkpointPath.string());
if (auto result = Void::Process::reexec(pendingRelease->executable,
arguments); !result) {
Void::Log::error("main", "release re-exec failed: {}",
result.error().message());
return 1;
}
}
return 0;
}
+97
View File
@@ -0,0 +1,97 @@
#include "echoion/host/CoreLoader.hpp"
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <unistd.h>
namespace
{
int fail(const char* message)
{
std::cerr << message << '\n';
return 1;
}
}
int main()
{
const auto root = std::filesystem::temp_directory_path() /
("echoion-core-reload-" + std::to_string(::getpid()));
std::filesystem::create_directories(root);
const auto cleanup = [&root] {
std::error_code 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 ytDlp = root / ".local/share/echoion/yt-dlp/yt-dlp";
std::filesystem::create_directories(ytDlp.parent_path());
{
std::ofstream output{ytDlp};
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);
const auto config = root / "config.json";
{
std::ofstream output{config};
output << R"({
"network": {"rpcEnabled": false},
"web": {"enabled": false},
"features": {"enableAutoUpdateCheck": false},
"advanced": {"cacheEnabled": false}
})";
}
const auto corePath = root / "Echoion.ts";
std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath);
Echoion::Host::CoreLoader loader;
loader.setConfigPath(config);
if (auto result = loader.load(corePath); !result) {
cleanup();
return fail(result.error().message.c_str());
}
const auto before = loader.getCore();
if (!before) {
cleanup();
return fail("Core missing after initial load");
}
if (auto result = loader.hotReload(corePath); !result) {
cleanup();
return fail(result.error().message.c_str());
}
const auto after = loader.getCore();
if (!after || after.get() == before.get()) {
cleanup();
return fail("Core instance was not transactionally replaced");
}
const auto invalid = root / "Echoion.invalid";
{
std::ofstream output{invalid, std::ios::binary};
output << "not a shared library";
}
std::filesystem::rename(invalid, corePath);
if (auto result = loader.hotReload(corePath); result) {
cleanup();
return fail("invalid replacement unexpectedly activated");
}
const auto retained = loader.getCore();
if (!retained || retained.get() != after.get() || !retained->isInitialized()) {
cleanup();
return fail("running Core was not retained after failed activation");
}
if (auto result = loader.unload(); !result) {
cleanup();
return fail(result.error().message.c_str());
}
cleanup();
return 0;
}
+59
View File
@@ -0,0 +1,59 @@
#include "echoion/standalone/EventCallbackGate.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
int main()
{
Echoion::Standalone::EventCallbackGate gate;
std::mutex mutex;
std::condition_variable enteredCv;
std::condition_variable releaseCv;
bool entered = false;
bool release = false;
std::atomic<int> calls{0};
auto lifetime = std::make_shared<int>(42);
std::weak_ptr<int> observedLifetime = lifetime;
gate.add([&, lifetime](const Echoion::Api::PluginEvent&) {
++calls;
std::unique_lock lock(mutex);
entered = true;
enteredCv.notify_all();
releaseCv.wait(lock, [&] { return release; });
});
lifetime.reset();
Echoion::Api::PluginEvent event;
auto dispatch = std::async(std::launch::async, [&] { gate.dispatch(event); });
{
std::unique_lock lock(mutex);
enteredCv.wait(lock, [&] { return entered; });
}
auto quiesce = std::async(std::launch::async, [&] { gate.quiesce(); });
assert(quiesce.wait_for(std::chrono::milliseconds{30}) ==
std::future_status::timeout);
assert(!observedLifetime.expired());
{
std::lock_guard lock(mutex);
release = true;
}
releaseCv.notify_all();
dispatch.get();
quiesce.get();
assert(observedLifetime.expired());
gate.dispatch(event);
assert(calls == 1);
gate.add([&](const Echoion::Api::PluginEvent&) { ++calls; });
gate.dispatch(event);
assert(calls == 2);
}
+38
View File
@@ -0,0 +1,38 @@
#include "echoion/standalone/ReleaseManifest.hpp"
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <iostream>
int main()
{
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';
return 1;
}
if (Echoion::Standalone::ReleaseManifest::load(manifestPath)) {
std::cerr << "path traversal manifest was accepted\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";
return 1;
}
return 0;
}
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
stage_script=$1
validator=$2
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"
"$stage_script" "$root/releases" 1.2.3 \
"$root/source-echoiond" "$root/source-core.ts"
manifest="$root/releases/pending-release.json"
test -x "$root/releases/1.2.3/echoiond"
test -f "$root/releases/1.2.3/Echoion.ts"
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"
"$validator" --validate-release "$manifest"
printf 'tampered\n' >> "$root/releases/1.2.3/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
echo "unsafe version was accepted" >&2
exit 1
fi