Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-12 02:57:35 +03:00
1 parent 2d1d03db1e
commit ef3139ca64
60 files changed
+1774 -4412

No files matched your search

+26 -14
View File
@@ -26,6 +26,18 @@ if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
endif()
endif()
# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary
# 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)
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")
endif()
# Include CPM
file(
DOWNLOAD
@@ -56,6 +68,18 @@ CPMAddPackage(
"VOID_ENABLE_TESTING OFF"
)
# Modern native TeamSpeak client library. Local development can point at the
# adjacent history-preserving extraction with:
# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
CPMAddPackage(
NAME VoidTeamspeak
GIT_REPOSITORY http://git.faumaray.ru/void/voidteamspeak.git
GIT_TAG main
OPTIONS
"VOID_TEAMSPEAK_BUILD_TESTS OFF"
"VOID_ENABLE_TESTING OFF"
)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
@@ -106,23 +130,13 @@ option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build archived EchoionPlugin compatibility target" OFF)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
option(BUILD_PROTOCOL "Build EchoionProtocol (native TeamSpeak UDP client)" ON)
option(BUILD_STANDALONE "Build EchoionStandalone (daemon; no TeamSpeak client)" ON)
option(BUILD_TESTS "Build tests" OFF)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
if(BUILD_TESTS)
enable_testing()
endif()
# Static linking configuration
if(ECHOION_STATIC_LINK)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
set(BUILD_SHARED_LIBS OFF)
message(STATUS "Static linking enabled - building standalone distribution")
endif()
# Find packages
find_package(Threads REQUIRED)
@@ -154,10 +168,8 @@ if(BUILD_PLUGIN)
add_subdirectory(EchoionPlugin)
endif()
# EchoionProtocol: standalone TeamSpeak UDP client library (no Echoion deps).
if(BUILD_PROTOCOL OR BUILD_STANDALONE)
add_subdirectory(EchoionProtocol)
endif()
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
# in-tree EchoionProtocol directory is intentionally no longer built.
# EchoionStandalone links the host-common loader and native protocol client.
if(BUILD_STANDALONE)
+2 -9
View File
@@ -1,16 +1,8 @@
cmake_minimum_required(VERSION 4.0.0)
project(EchoionHost VERSION 1.0.0 LANGUAGES CXX)
CPMAddPackage(
NAME dylib
GITHUB_REPOSITORY martin-olivier/dylib
GIT_TAG "v3.0.1"
OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON"
)
add_library(EchoionHost STATIC
src/CoreLoader.cpp
src/FileWatcher.cpp
)
add_library(Echoion::Host ALIAS EchoionHost)
@@ -27,11 +19,12 @@ target_link_libraries(EchoionHost
Echoion::ApiPlugin
Echoion::ApiOpaque
Echoion::ApiCoreInterface
dylib
PRIVATE
Echoion::ApiLogger
Void::Data
Void::Log
Void::Plugin
Void::System
Void::Stacktrace
Threads::Threads
)
+16 -11
View File
@@ -1,11 +1,11 @@
#pragma once
#include "echoion/host/FileWatcher.hpp"
#include <Void/System/FileWatcher.hpp>
#include <Void/Plugin/Manager.hpp>
#include <CoreInterface.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <dylib.hpp>
#include <filesystem>
#include <functional>
#include <memory>
@@ -32,6 +32,10 @@ namespace Echoion::Host
void setConfigPath(const std::filesystem::path& configPath);
[[nodiscard]] std::filesystem::path getConfigPath() const;
[[nodiscard]] bool isHotReloading() const noexcept;
Api::Result<void>
checkpoint(const std::filesystem::path& destination);
Api::Result<void>
restoreCheckpoint(const std::filesystem::path& source);
// Automatic hot reload
void enableAutoReload();
@@ -41,6 +45,11 @@ namespace Echoion::Host
// Callback for hot reload completion (called after auto-reload
// finishes)
using HotReloadCallback = std::function<void()>;
using HotReloadPrepareCallback = std::function<void()>;
void setHotReloadPrepareCallback(HotReloadPrepareCallback callback)
{
hotReloadPrepareCallback_ = std::move(callback);
}
void setHotReloadCallback(HotReloadCallback callback)
{
hotReloadCallback_ = std::move(callback);
@@ -51,24 +60,19 @@ namespace Echoion::Host
Api::Result<void>
loadLibraryInternal(const std::filesystem::path& path);
Api::Result<void> unloadLibraryInternal();
[[nodiscard]] Api::SerializedState saveStateInternal();
[[nodiscard]] Api::Result<void>
restoreStateInternal(const Api::SerializedState& state);
[[nodiscard]] std::filesystem::path
getTempLibraryPath(const std::filesystem::path& original) const;
void cleanupTempFiles();
[[nodiscard]] Api::Result<void> refreshCoreHandle();
std::unique_ptr<dylib::library> library_;
Void::Plugin::PluginManager pluginManager_;
std::string pluginName_;
Api::CoreInterfacePtr core_;
std::filesystem::path currentLibraryPath_;
std::filesystem::path tempLibraryPath_;
std::filesystem::path configPath_;
mutable std::mutex mutex_;
std::atomic<bool> loaded_{false};
std::atomic<bool> hotReloading_{false};
// Auto reload
FileWatcher fileWatcher_;
Void::FileSystem::FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
// Deferred reload - waits for current track to finish
@@ -82,6 +86,7 @@ namespace Echoion::Host
mutable std::mutex pendingReloadMutex_;
// Hot reload completion callback
HotReloadPrepareCallback hotReloadPrepareCallback_;
HotReloadCallback hotReloadCallback_;
void onCoreFileChanged();
@@ -1,65 +0,0 @@
#pragma once
#include <atomic>
#include <chrono>
#include <filesystem>
#include <functional>
#include <mutex>
#include <thread>
namespace Echoion::Host
{
/**
* @brief Simple file watcher that monitors a file for changes
* and triggers a callback when the file is modified.
*/
class FileWatcher
{
public:
using ChangeCallback = std::function<void()>;
FileWatcher();
~FileWatcher();
// Disable copy
FileWatcher(const FileWatcher&) = delete;
FileWatcher& operator=(const FileWatcher&) = delete;
/**
* @brief Start watching a file for changes
* @param filePath Path to the file to watch
* @param callback Function to call when file changes
* @param intervalMs Polling interval in milliseconds
*/
void startWatching(const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs =
std::chrono::milliseconds(1000));
/**
* @brief Stop watching
*/
void stopWatching();
[[nodiscard]] bool isWatching() const noexcept;
private:
void watchLoop();
std::filesystem::path watchedPath_;
ChangeCallback callback_;
std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
std::atomic<bool> stopRequested_{false};
std::thread watchThread_;
std::mutex mutex_;
// Store last modification time
std::filesystem::file_time_type lastWriteTime_;
std::uint64_t lastFileSize_ = 0;
};
} // namespace Echoion::Host
+204 -231
View File
@@ -1,5 +1,6 @@
#include <Void/Log/Log.hpp>
#include "dylib.hpp"
#include <Void/Plugin/Loader.hpp>
#include <Void/System/Path.hpp>
#include "echoion/host/CoreLoader.hpp"
#include <chrono>
#include <format>
@@ -10,7 +11,19 @@
namespace Echoion::Host
{
CoreLoader::CoreLoader() { cleanupTempFiles(); }
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;
}})
{
}
void CoreLoader::enableAutoReload()
{
@@ -24,15 +37,21 @@ namespace Echoion::Host
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.startWatching(currentLibraryPath_,
[this]() { onCoreFileChanged(); });
fileWatcher_.watch(currentLibraryPath_,
[this](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
onCoreFileChanged();
}
});
}
}
void CoreLoader::disableAutoReload()
{
autoReloadEnabled_ = false;
fileWatcher_.stopWatching();
if (!currentLibraryPath_.empty()) {
fileWatcher_.unwatch(currentLibraryPath_);
}
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
}
@@ -89,10 +108,6 @@ namespace Echoion::Host
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
}
@@ -168,15 +183,14 @@ namespace Echoion::Host
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
CoreLoader::~CoreLoader()
{
if (autoReloadEnabled_.load()) {
disableAutoReload();
}
// Signal the deferred reload thread to stop and wait for it. It must
// never outlive this object: it dereferences core_ and this.
stopDeferredReload_ = true;
@@ -189,12 +203,11 @@ namespace Echoion::Host
std::format("Unload from destructor failed: {}",
result.error().message));
}
cleanupTempFiles();
}
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
{
std::lock_guard<std::mutex> lock(mutex_);
std::unique_lock<std::mutex> lock(mutex_);
if (loaded_) {
return Api::fail(Api::ErrorCode::AlreadyExists,
@@ -207,24 +220,9 @@ namespace Echoion::Host
std::format("Library not found: {}", libraryPath.string()));
}
tempLibraryPath_ = getTempLibraryPath(libraryPath);
try {
std::filesystem::copy_file(
libraryPath, tempLibraryPath_,
std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) {
return Api::fail(
Api::ErrorCode::UnknownError,
std::format("Failed to copy library to temp: {}", e.what()));
}
auto result = loadLibraryInternal(tempLibraryPath_);
auto result = loadLibraryInternal(libraryPath);
if (result) {
currentLibraryPath_ = libraryPath;
} else {
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
}
return result;
@@ -234,127 +232,105 @@ namespace Echoion::Host
{
std::lock_guard<std::mutex> lock(mutex_);
auto result = unloadLibraryInternal();
if (!tempLibraryPath_.empty()) {
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
}
return result;
return unloadLibraryInternal();
}
Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
{
std::lock_guard<std::mutex> lock(mutex_);
std::unique_lock<std::mutex> lock(mutex_);
if (!loaded_) {
return Api::fail(Api::ErrorCode::NotFound,
"No core loaded to reload");
}
hotReloading_ = true;
Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file...");
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
Api::StateBlob stateBlob;
if (core_) {
stateBlob = core_->saveState();
Void::Log::info("CoreLoader", "{}",
std::format("Saved state: version={}, size={} bytes",
stateBlob.version, stateBlob.size()));
}
auto targetPath =
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
if (!std::filesystem::exists(targetPath)) {
hotReloading_ = false;
return Api::fail(
Api::ErrorCode::NotFound,
std::format("New library not found: {}", targetPath.string()));
}
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
try {
std::filesystem::copy_file(
targetPath, newTempPath,
std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) {
hotReloading_ = false;
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return Api::fail(Api::ErrorCode::UnknownError,
std::format("Failed to copy new library to temp: {}",
e.what()));
if (targetPath != currentLibraryPath_) {
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");
}
auto unloadResult = unloadLibraryInternal();
if (!unloadResult) {
hotReloading_ = false;
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return unloadResult;
hotReloading_ = true;
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
// producers have been drained.
if (hotReloadPrepareCallback_) {
hotReloadPrepareCallback_();
}
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
tempLibraryPath_ = newTempPath;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
auto loadResult = loadLibraryInternal(tempLibraryPath_);
if (!loadResult) {
hotReloading_ = false;
return loadResult;
}
// Step 4: Ask new Core to restore state (it handles migration
// internally)
if (!stateBlob.empty()) {
auto coreVersion = core_->getStateFormatVersion();
auto stateVersion = stateBlob.version;
Void::Log::info("CoreLoader", "{}", std::format("Restoring state v{} to Core v{}",
stateVersion, coreVersion));
if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(stateBlob);
if (!restoreResult) {
Void::Log::error("CoreLoader", "{}",
std::format("Failed to restore state: {}",
restoreResult.error().message));
// Check if it's a version issue
if (restoreResult.error().code ==
Api::ErrorCode::IncompatibleVersion) {
// Signal user to update/restart
Void::Log::warn("CoreLoader", "{}", "State version incompatible. "
"User needs to update/restart.");
// Optionally: notify through plugin interface
}
// Continue with empty state - graceful degradation
} else {
Void::Log::info("CoreLoader", "{}", "State restored successfully");
// Core owns exclusive process resources (HTTP/RPC listeners), so its
// two generations cannot both be initialized during an RCU swap.
// Capture state first, then stop the old services while its plugin
// instance remains pinned for rollback.
Api::StateBlob state;
if (core_) {
state = core_->saveState();
if (auto stopped = core_->shutdown(); !stopped) {
hotReloading_ = false;
lock.unlock();
if (hotReloadCallback_) {
hotReloadCallback_();
}
} else {
Void::Log::warn("CoreLoader", "{}", std::format(
"Cannot restore state v{} in Core v{}. "
"Version age exceeds maximum supported ({} versions).",
stateVersion, coreVersion,
Api::MAX_SUPPORTED_STATE_VERSION_AGE));
// Continue with empty state
return stopped;
}
}
currentLibraryPath_ = targetPath;
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()));
if (core_) {
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(
"; retained Core state restore failed: {}",
restored.error().message);
}
}
}
Void::Log::warn("CoreLoader", "{}", message);
lock.unlock();
// The prepare callback removed the event route. Restore it against
// the still-current Core even though no swap occurred.
if (hotReloadCallback_) {
hotReloadCallback_();
}
return Api::fail(Api::ErrorCode::PluginError, message);
}
if (auto refreshed = refreshCoreHandle(); !refreshed) {
hotReloading_ = false;
return refreshed;
}
if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) {
Void::Log::warn("CoreLoader", "new Core state restore failed: {}",
restored.error().message);
}
}
hotReloading_ = false;
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
lock.unlock();
if (hotReloadCallback_) {
hotReloadCallback_();
}
return {};
}
@@ -383,67 +359,109 @@ namespace Echoion::Host
return hotReloading_.load();
}
Api::Result<void>
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");
}
const auto state = core_->saveState();
std::string bytes;
bytes.reserve(8 + state.timestamp.size() + state.data.size());
auto appendU32 = [&bytes](uint32_t value) {
for (int shift : {24, 16, 8, 0}) {
bytes.push_back(static_cast<char>((value >> shift) & 0xffU));
}
};
appendU32(state.version);
appendU32(static_cast<uint32_t>(state.timestamp.size()));
bytes.append(state.timestamp);
bytes.append(reinterpret_cast<const char*>(state.data.data()),
state.data.size());
if (auto result = Void::FileSystem::atomic_write(destination, bytes);
!result) {
return Api::fail(Api::ErrorCode::PluginError,
result.error().message());
}
return {};
}
Api::Result<void>
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");
}
auto contents = Void::FileSystem::read_file(source);
if (!contents) {
return Api::fail(Api::ErrorCode::NotFound,
contents.error().message());
}
if (contents->size() < 8) {
return Api::fail(Api::ErrorCode::ParseError,
"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]);
}
return value;
};
Api::StateBlob state;
state.version = readU32(0);
const auto timestampSize = readU32(4);
if (timestampSize > contents->size() - 8) {
return Api::fail(Api::ErrorCode::ParseError,
"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());
return core_->restoreState(state);
}
Api::Result<void>
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
{
try {
std::cout << std::format("[Echoion] Loading core library: {}",
path.string())
<< '\n';
// Use no decorations - the path already has the correct extension
// (.ts)
library_ = std::make_unique<dylib::library>(
path.string(), dylib::decorations::none());
auto createFunc =
library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
auto versionFunc =
library_->get_function<const char*()>("GetApiVersion");
auto compatibleFunc =
library_->get_function<bool(uint32_t, uint32_t)>(
"IsApiCompatible");
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
library_.reset();
return Api::fail(
Api::ErrorCode::InvalidArgument,
std::format("API version mismatch. Expected {}.{}, got {}",
Api::VERSION_MAJOR, Api::VERSION_MINOR,
versionFunc()));
}
core_ = createFunc();
if (!core_) {
library_.reset();
return Api::fail(Api::ErrorCode::UnknownError,
"Failed to create core instance");
}
auto initResult = core_->initialize(configPath_);
if (!initResult) {
core_.reset();
library_.reset();
return initResult;
}
loaded_ = true;
Void::Log::info("CoreLoader", "{}", std::format(
"Core library loaded (API version: {})", versionFunc()));
return {};
} catch (const dylib::load_error& e) {
return Api::fail(
Api::ErrorCode::PluginError,
std::format("Failed to load library: {}", e.what()));
} catch (const dylib::symbol_error& e) {
auto result = pluginManager_.load(path);
if (!result) {
return Api::fail(Api::ErrorCode::PluginError,
std::format("Failed to find symbol: {}", e.what()));
} catch (const std::exception& e) {
return Api::fail(Api::ErrorCode::UnknownError,
std::format("Unexpected error: {}", e.what()));
std::format("failed to load Core plugin: {}",
Void::Plugin::to_string(result.error())));
}
pluginName_ = std::move(*result);
if (auto refreshed = refreshCoreHandle(); !refreshed) {
std::ignore = pluginManager_.unload(pluginName_);
pluginName_.clear();
return refreshed;
}
loaded_ = true;
Void::Log::info("CoreLoader", "Core plugin '{}' loaded", pluginName_);
return {};
}
Api::Result<void> CoreLoader::refreshCoreHandle()
{
auto pin = std::make_shared<Void::Plugin::PluginHandle>(
pluginManager_.acquire(pluginName_));
if (!*pin) {
return Api::fail(Api::ErrorCode::PluginError,
"Core plugin disappeared from the registry");
}
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
if (interface == nullptr) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Void plugin does not implement Echoion Core interface");
}
core_ = Api::CoreInterfacePtr{std::move(pin), interface};
return {};
}
Api::Result<void> CoreLoader::unloadLibraryInternal()
@@ -454,64 +472,19 @@ namespace Echoion::Host
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
if (core_) {
if (auto result = core_->shutdown(); !result) {
Void::Log::warn(
"CoreLoader", "{}",
std::format("Core shutdown reported failure: {}",
result.error().message));
core_.reset();
if (!pluginName_.empty()) {
if (auto result = pluginManager_.unload(pluginName_); !result) {
return Api::fail(Api::ErrorCode::PluginError,
std::format("failed to unload Core plugin: {}",
Void::Plugin::to_string(result.error())));
}
core_.reset();
pluginName_.clear();
}
library_.reset();
loaded_ = false;
std::cout << "[Echoion] Core library unloaded" << '\n';
return {};
}
std::filesystem::path CoreLoader::getTempLibraryPath(
const std::filesystem::path& original) const
{
auto tempDir = std::filesystem::temp_directory_path();
auto filename = original.filename().string();
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
// Use the same extension as the original file (.ts for TeamSpeak plugin)
#ifdef _WIN32
auto tempName = std::format(
"echoion_{}_{}.dll", ms,
std::hash<std::thread::id>{}(std::this_thread::get_id()));
#else
auto tempName = std::format(
"echoion_{}_{}.ts", ms,
std::hash<std::thread::id>{}(std::this_thread::get_id()));
#endif
return tempDir / tempName;
}
void CoreLoader::cleanupTempFiles()
{
auto tempDir = std::filesystem::temp_directory_path();
std::error_code ec;
for (const auto& entry :
std::filesystem::directory_iterator(tempDir, ec)) {
if (entry.is_regular_file()) {
auto name = entry.path().filename().string();
if (name.starts_with("echoion_") &&
(name.ends_with(".dll") || name.ends_with(".so") ||
name.ends_with(".ts"))) {
std::filesystem::remove(entry.path(), ec);
}
}
}
}
} // namespace Echoion::Host
-98
View File
@@ -1,98 +0,0 @@
#include "echoion/host/FileWatcher.hpp"
#include <chrono>
#include <format>
#include <iostream>
namespace Echoion::Host
{
FileWatcher::FileWatcher() = default;
FileWatcher::~FileWatcher() { stopWatching(); }
void FileWatcher::startWatching(const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs)
{
std::lock_guard<std::mutex> lock(mutex_);
if (watching_.load()) {
stopWatching();
}
watchedPath_ = filePath;
callback_ = std::move(callback);
intervalMs_ = intervalMs;
stopRequested_ = false;
// Get initial file state
if (std::filesystem::exists(watchedPath_)) {
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
lastFileSize_ = std::filesystem::file_size(watchedPath_);
}
watching_ = true;
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
}
void FileWatcher::stopWatching()
{
stopRequested_ = true;
if (watchThread_.joinable()) {
watchThread_.join();
}
watching_ = false;
}
bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
void FileWatcher::watchLoop()
{
while (!stopRequested_.load()) {
// Sleep first to avoid checking immediately
std::this_thread::sleep_for(intervalMs_);
if (stopRequested_.load()) {
break;
}
std::lock_guard<std::mutex> lock(mutex_);
if (!std::filesystem::exists(watchedPath_)) {
continue;
}
try {
auto currentWriteTime =
std::filesystem::last_write_time(watchedPath_);
auto currentFileSize = std::filesystem::file_size(watchedPath_);
// Check if file has changed (time or size)
if (currentWriteTime != lastWriteTime_ ||
currentFileSize != lastFileSize_) {
// Update stored values
lastWriteTime_ = currentWriteTime;
lastFileSize_ = currentFileSize;
// Trigger callback
if (callback_) {
try {
callback_();
} catch (const std::exception& e) {
std::cerr
<< std::format("FileWatcher callback error: {}",
e.what())
<< '\n';
}
}
}
} catch (const std::exception& e) {
// Ignore errors (file might be locked during write)
}
}
}
} // namespace Echoion::Host
-49
View File
@@ -1,49 +0,0 @@
# EchoionProtocol — reverse-engineered TeamSpeak 3/6 full-client voice protocol.
#
# Deliberately dependency-isolated: it knows nothing about Echoion::Api, Void or
# reflection. It links only OpenSSL (crypto), libopus (voice) and a vendored
# QuickLZ. This keeps it independently unit-testable and reusable, and lets it
# build with a plain C++20 toolchain even though the rest of Echoion needs
# C++26/reflection.
cmake_minimum_required(VERSION 3.24)
# Allow standalone configuration (own build) as well as add_subdirectory() from
# the Echoion root.
if(NOT DEFINED PROJECT_NAME)
project(EchoionProtocol LANGUAGES CXX)
endif()
option(ECHOIONPROTOCOL_BUILD_TESTS "Build EchoionProtocol unit tests" OFF)
find_package(OpenSSL REQUIRED)
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(OPUS IMPORTED_TARGET opus)
# libsodium provides the raw Ed25519 point arithmetic the TS6 license chain
# (initivexpand2) needs; OpenSSL cannot do it.
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
endif()
file(GLOB ECHOIONPROTOCOL_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
add_library(EchoionProtocol STATIC ${ECHOIONPROTOCOL_SOURCES})
add_library(Echoion::Protocol ALIAS EchoionProtocol)
target_include_directories(EchoionProtocol
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
# This target is standalone C++20 on purpose — do not inherit the tree's C++26.
target_compile_features(EchoionProtocol PUBLIC cxx_std_20)
target_link_libraries(EchoionProtocol PUBLIC OpenSSL::Crypto PkgConfig::SODIUM)
if(TARGET PkgConfig::OPUS)
target_link_libraries(EchoionProtocol PUBLIC PkgConfig::OPUS)
target_compile_definitions(EchoionProtocol PUBLIC ECHOION_HAVE_OPUS=1)
endif()
if(ECHOIONPROTOCOL_BUILD_TESTS OR BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
-47
View File
@@ -1,47 +0,0 @@
# EchoionProtocol
A native C++ implementation of the TeamSpeak 3/6 **full-client voice protocol**,
so Echoion can connect to a TeamSpeak server as its own client — no TeamSpeak
client and no plugin required. Ported from
[ts6-manager](https://github.com/clusterzx/ts6-manager)'s `tslib` (MIT) and
cross-checked against ReSpeak's protocol documentation.
TeamSpeak 6 has **no WebRTC voice** — its voice is still the legacy TS3 UDP
protocol on port 9987, which this library speaks.
## Modules
| Module | Purpose |
|--------|---------|
| `Crypto` | AES-128-EAX (composed from AES-CTR + CMAC/OMAC1), per-packet key/nonce derivation, SHA hashes. **Byte-verified against RFC 4493 (CMAC) and the EAX spec test vectors.** |
| `Identity` | ECDSA P-256 identity, libtomcrypt public-key export ("omega"), uid, hashcash security-level. OpenSSL. |
| `License` | TS6 `initivexpand2` license chain — Ed25519 point arithmetic via libsodium. |
| `Command` | TS3 escaped `key=value` command serialization + notify parsing. |
| `QuickLz` | QuickLZ level-1 decompression for compressed command packets. |
| `TsClient` | UDP socket, handshake (`init0`–`init4` + RSA puzzle, `clientinitiv`, `initivexpand`/`initivexpand2`), per-packet crypto, ack/resend, keepalive, voice/whisper send, event callbacks. |
## Dependencies
OpenSSL (crypto), libsodium (Ed25519), libopus (only consumed by the host's
audio encoder, not this library). No Boost, no Void, no reflection — plain C++20,
independently buildable and testable.
## Build & test standalone
```bash
cmake -S . -B build -DECHOIONPROTOCOL_BUILD_TESTS=ON
cmake --build build
./build/tests/echoion_protocol_tests
```
## Verified
- Unit tests: CMAC (RFC 4493), EAX (spec vectors), SHA-1, base64, command
escaping, QuickLZ, identity uid/security-level/sign, save/load.
- **Live handshake**: connects to a real TeamSpeak 3 server (Docker) through the
full handshake and appears in the server's client list.
## Not yet integration-tested against a live server
Audio audibility to a second client, whisper targeting, and inbound-command
event mapping are implemented but need a full end-to-end run with Core.
@@ -1,36 +0,0 @@
#pragma once
// TS3 command wire format: "commandname key=value key=value|key=value".
// Ported from ts6-manager tslib/commands.ts.
#include <map>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
// Escape / unescape a single token per the TS3 rules
// (\\ \/ \s \p \f \n \r \t \v).
std::string tsEscape(const std::string& str);
std::string tsUnescape(const std::string& str);
// Ordered key/value params for a command. std::map keeps a stable order so
// serialization is deterministic (helpful for tests); the server does not
// care about ordering.
using CommandParams = std::map<std::string, std::string>;
struct ParsedCommand {
std::string name;
CommandParams params; // first group
std::vector<CommandParams> groups; // all '|'-separated groups
};
// Serialize "name k=v k=v". Empty values are emitted as "k=".
std::string buildCommand(const std::string& name,
const CommandParams& params);
// Parse a raw command / notify line into name + params (+ pipe groups).
ParsedCommand parseCommand(const std::string& raw);
} // namespace Echoion::Protocol
@@ -1,88 +0,0 @@
#pragma once
// Low-level cryptographic primitives for the TeamSpeak 3/6 full-client voice
// protocol. Ported byte-for-byte from ts6-manager's tslib/crypto.ts (MIT) so the
// on-wire behaviour is identical; implemented over OpenSSL EVP.
//
// The protocol uses AES-128-EAX for per-packet authenticated encryption. OpenSSL
// has no native EAX, so — exactly like the reference — we compose it from
// AES-128-CTR (confidentiality) and AES-128-CMAC / OMAC1 (authenticity).
#include <array>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Crypto
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
inline constexpr size_t BLOCK_SIZE = 16;
inline constexpr size_t MAC_LEN = 8;
// "TS3INIT1" — the fake/static MAC stamped on low-level init packets before a
// shared secret exists.
inline constexpr std::array<uint8_t, 8> INIT_MAC = {'T', 'S', '3', 'I',
'N', 'I', 'T', '1'};
// "c:\\windows\\syste" / "m\\firewall32.cpl" — the fixed key/nonce used to
// (de)crypt command packets during the handshake, before key exchange.
inline constexpr std::array<uint8_t, 16> DUMMY_KEY = {
'c', ':', '\\', 'w', 'i', 'n', 'd', 'o',
'w', 's', '\\', 's', 'y', 's', 't', 'e'};
inline constexpr std::array<uint8_t, 16> DUMMY_NONCE = {
'm', '\\', 'f', 'i', 'r', 'e', 'w', 'a',
'l', 'l', '3', '2', '.', 'c', 'p', 'l'};
// Client version signature used in clientinit (3.5.0 [Stable]).
inline constexpr uint32_t INIT_VERSION = 1566914096u;
// --- Hashes -------------------------------------------------------------
std::array<uint8_t, 20> sha1(ByteView data);
std::array<uint8_t, 32> sha256(ByteView data);
std::array<uint8_t, 64> sha512(ByteView data);
// --- XOR helpers --------------------------------------------------------
// out[i] = a[i] ^ b[i] for i in [0, min(a,b)).
Bytes xorBuffers(ByteView a, ByteView b);
// a[i] ^= b[i] for i in [0, len). Caller guarantees bounds.
void xorInto(std::span<uint8_t> a, ByteView b, size_t len);
// --- AES-128-CMAC (OMAC1) ----------------------------------------------
// 16-byte MAC over `data` under the 16-byte `key`.
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data);
// --- AES-128-EAX --------------------------------------------------------
struct EaxResult {
Bytes ciphertext;
std::array<uint8_t, MAC_LEN> mac;
};
// Encrypt `plaintext` with 16-byte `key`, `nonce` and associated `header`.
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
ByteView plaintext);
// Decrypt/verify; returns nullopt on MAC mismatch.
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
ByteView header, ByteView ciphertext,
ByteView mac);
// --- Per-packet key/nonce derivation -----------------------------------
struct KeyNonce {
std::array<uint8_t, 16> key;
std::array<uint8_t, 16> nonce;
};
// Derive the packet key+nonce from the connection `ivStruct` (20 bytes for
// the SHA1 handshake secret, 64 bytes for the license path), keyed by
// direction, packet id, generation and packet type.
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
uint32_t generationId, uint8_t packetType,
ByteView ivStruct);
// --- Misc ---------------------------------------------------------------
// base64(sha1(utf8(password))); empty string for empty password.
std::string hashPassword(const std::string& password);
} // namespace Echoion::Protocol::Crypto
@@ -1,65 +0,0 @@
#pragma once
// TeamSpeak client identity: an ECDSA P-256 keypair plus the libtomcrypt-style
// public-key export ("omega"), the derived unique-id, and the hashcash
// key-offset that raises the identity's "security level".
// Ported from ts6-manager tslib/identity.ts.
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
class Identity
{
public:
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Generate a fresh identity and raise it to at least `securityLevel`
// leading-zero bits (hashcash over the public key + offset).
static Identity generate(int securityLevel = 8);
// Load / save the identity to a small text file:
// privateKeyPem, publicKeyString, keyOffset (one per line).
static Identity load(const std::string& path);
// Import an identity exported by the TeamSpeak client. The export is
// an INI file containing its obfuscated "<offset>V<base64>" key.
static Identity importTeamSpeakIni(const std::string& path);
void save(const std::string& path) const;
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
const std::string& publicKeyString() const { return publicKeyString_; }
// base64(sha1(ascii(publicKeyString))).
const std::string& uid() const { return uid_; }
uint64_t keyOffset() const { return keyOffset_; }
int securityLevel() const;
// ECDSA sign `data` with SHA-256; returns the raw signature.
Bytes sign(ByteView data) const;
// ECDH(this private key, server public key) → SHA-1 of the shared
// x-coordinate. `serverPublicKeyDer` is the libtomcrypt DER blob
// (base64-decoded "omega" from initivexpand).
Bytes sharedSecret(ByteView serverPublicKeyDer) const;
private:
Identity() = default;
struct PKeyDeleter {
void operator()(void* p) const noexcept;
};
// EVP_PKEY* held opaquely so this header stays OpenSSL-free.
std::shared_ptr<void> pkey_;
std::string publicKeyString_;
std::string uid_;
uint64_t keyOffset_ = 0;
};
} // namespace Echoion::Protocol
@@ -1,45 +0,0 @@
#pragma once
// TeamSpeak license chain handling for the modern handshake (initivexpand2).
// The chain is walked with Ed25519 point arithmetic (scalar-mult + point-add),
// which OpenSSL does not expose, so this module uses libsodium.
// Ported from ts6-manager tslib/license.ts.
#include <array>
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
struct LicenseBlock {
std::array<uint8_t, 32> key;
std::array<uint8_t, 32> hash; // first 32 bytes of SHA-512(content)
uint8_t type = 0;
};
struct TempKey {
std::array<uint8_t, 32> publicKey;
std::array<uint8_t, 32> privateKey;
};
// Parse the server license blob into its chain of blocks.
std::vector<LicenseBlock> parseLicense(ByteView data);
// Walk the chain from the root key to the final server public key (32 bytes).
std::array<uint8_t, 32>
deriveLicenseKey(const std::vector<LicenseBlock>& blocks);
// Generate an ephemeral Ed25519 keypair (clamped like the reference).
TempKey generateTemporaryKey();
// initivexpand2 shared secret: SHA-512( tempPriv * serverDerivedKey ),
// 64 bytes. Returns the raw digest.
std::array<uint8_t, 64>
getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey);
} // namespace Echoion::Protocol
@@ -1,23 +0,0 @@
#pragma once
// QuickLZ level-1 decompression, used to inflate compressed command packets.
// Clients send commands uncompressed, so only decompression is needed.
// Ported from ts6-manager tslib/quicklz.ts (itself from TSLib QuickerLz.cs).
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
uint32_t qlzDecompressedSize(ByteView data);
uint32_t qlzCompressedSize(ByteView data);
// Throws std::runtime_error on malformed input or unsupported level.
Bytes qlzDecompress(ByteView data);
} // namespace Echoion::Protocol
@@ -1,229 +0,0 @@
#pragma once
// Full-client connection to a TeamSpeak 3/6 server over the native UDP voice
// protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and
// voice send path. Ported from ts6-manager tslib/client.ts.
//
// Threading: a single background thread runs the receive + timer loop. Public
// send methods are thread-safe (guarded by an internal mutex) so the audio
// thread can call sendVoice() directly. Callbacks fire on the loop thread.
#include "echoion/protocol/Command.hpp"
#include "echoion/protocol/Identity.hpp"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <thread>
#include <vector>
namespace Echoion::Protocol
{
enum class PacketType : uint8_t {
Voice = 0,
VoiceWhisper = 1,
Command = 2,
CommandLow = 3,
Ping = 4,
Pong = 5,
Ack = 6,
AckLow = 7,
Init1 = 8,
};
enum class ClientState {
Disconnected,
Init,
Handshake,
Connected,
Disconnecting,
};
struct TsClientOptions {
std::string host;
uint16_t port = 9987;
const Identity* identity = nullptr; // not owned
std::string nickname = "EchoionBot";
std::string serverPassword;
std::string defaultChannel; // channel id or name
std::string channelPassword;
};
// All callbacks fire on the internal loop thread.
struct TsClientCallbacks {
std::function<void()> onConnected;
std::function<void()> onDisconnected;
std::function<void(const std::string&)> onError;
std::function<void(const ParsedCommand&)> onCommand;
std::function<void(const CommandParams&)> onTextMessage;
std::function<void(std::span<const uint8_t>)> onVoice;
std::function<void(const std::string&)> onDebug;
};
struct CommandResult {
std::vector<CommandParams> records;
int errorId = 0;
std::string errorMessage;
[[nodiscard]] bool ok() const noexcept { return errorId == 0; }
};
class TsClient
{
public:
TsClient();
~TsClient();
TsClient(const TsClient&) = delete;
TsClient& operator=(const TsClient&) = delete;
void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); }
// Begin connecting. Returns immediately; onConnected/onError fire
// asynchronously. Throws only on immediate socket setup failure.
void connect(const TsClientOptions& opts);
// Graceful: send clientdisconnect, then close.
void disconnect();
// Immediate close, no disconnect command.
void forceClose();
ClientState state() const { return state_.load(); }
uint16_t clientId() const { return clientId_.load(); }
// Send one already-Opus-encoded 20 ms frame to the current channel.
void sendVoice(std::span<const uint8_t> opus);
// Whisper the frame to the given channel/client targets.
void sendWhisper(std::span<const uint8_t> opus,
const std::vector<uint64_t>& channelIds,
const std::vector<uint16_t>& clientIds);
// End-of-voice marker (empty frame).
void sendVoiceStop();
// Send a raw pre-built TS3 command line (fragmented if large).
void sendCommand(const std::string& cmd);
// Send a command and wait for its data records plus terminating
// `error` response. Safe to call from threads other than the receive
// callback thread.
CommandResult requestCommand(
const std::string& cmd,
std::chrono::milliseconds timeout = std::chrono::seconds{3});
CommandResult downloadFile(
const std::string& remotePath, const std::string& destination,
uint64_t channelId = 0, const std::string& channelPassword = {},
std::chrono::milliseconds timeout = std::chrono::seconds{10});
private:
// ---- packet path ----
void loopThread();
void handleIncomingPacket(std::span<const uint8_t> raw);
void sendOutgoing(std::span<const uint8_t> data, PacketType type,
uint8_t extraFlags = 0);
std::vector<uint8_t> buildRawPacket(std::span<const uint8_t> data,
PacketType type,
uint16_t packetId,
uint8_t flags);
void encryptPacket(std::vector<uint8_t>& raw, PacketType type,
uint16_t packetId, uint32_t gen, uint8_t flags,
std::span<const uint8_t> data);
std::vector<uint8_t> decryptPacket(std::span<const uint8_t> raw,
PacketType type,
uint16_t packetId, uint32_t gen,
uint8_t flags, bool& ok);
void sendRawLocked(const std::vector<uint8_t>& raw);
void sendInitPacket(const std::vector<uint8_t>& data);
// ---- handshake / commands ----
std::vector<uint8_t> buildInit0();
void handleInit(std::span<const uint8_t> data);
void handleCommandData(std::span<const uint8_t> data, uint8_t flags);
void processCommand(std::span<const uint8_t> data, uint8_t flags);
void handleInitIvExpand(const CommandParams& params);
void handleInitIvExpand2(const CommandParams& params);
void sendClientInit();
void handleInitServer(const CommandParams& params);
void handleChannelList(const ParsedCommand& parsed);
void handleChannelListFinished();
void sendAck(uint16_t ackId, PacketType ackType);
void handlePing(uint16_t packetId);
void resendTick();
void debug(const std::string& msg);
void cleanup();
void cancelPendingRequests(const std::string& reason);
// counters / crypto
struct Counter {
uint16_t id = 0;
uint32_t gen = 0;
};
Counter getCounter(PacketType type);
void incCounter(PacketType type);
TsClientOptions opts_;
TsClientCallbacks cb_;
int sock_ = -1;
std::atomic<ClientState> state_{ClientState::Disconnected};
std::atomic<uint16_t> clientId_{0};
std::thread thread_;
std::atomic<bool> running_{false};
// Recursive: command handlers running under the loop lock call
// sendCommand()/sendOutgoing() which re-lock.
mutable std::recursive_mutex mu_;
int64_t disconnectDeadline_ = 0;
std::array<uint16_t, 9> packetCounter_{};
std::array<uint32_t, 9> generationCounter_{};
bool cryptoInitComplete_ = false;
std::vector<uint8_t> ivStruct_;
std::array<uint8_t, 8> fakeSignature_{};
std::vector<uint8_t> alphaTmp_;
// resend tracking
struct Resend {
std::vector<uint8_t> raw;
uint16_t packetId = 0;
int64_t firstSend = 0;
int64_t lastSend = 0;
};
std::map<uint16_t, Resend> resendMap_;
std::unique_ptr<Resend> initResend_;
int64_t lastMessageTime_ = 0;
int64_t lastPing_ = 0;
int64_t connectStart_ = 0;
// fragment reassembly
std::vector<uint8_t> fragmentBuffer_;
bool fragmenting_ = false;
uint8_t fragmentFlags_ = 0;
// channel map for auto-move
std::map<std::string, uint64_t> channelMap_;
struct PendingRequest {
CommandResult result;
std::string returnCode;
bool completed = false;
std::condition_variable cv;
};
std::mutex requestSerialMutex_;
std::mutex pendingMutex_;
std::deque<std::shared_ptr<PendingRequest>> pendingRequests_;
std::atomic<uint64_t> requestId_{0};
std::atomic<uint16_t> transferId_{0};
};
} // namespace Echoion::Protocol
@@ -1,24 +0,0 @@
#pragma once
// Small dependency-free encoding helpers shared across the protocol modules.
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Util
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Standard base64 (RFC 4648) with '+' '/' and '=' padding.
std::string base64Encode(ByteView data);
Bytes base64Decode(const std::string& text);
// Lowercase hex, no separators.
std::string toHex(ByteView data);
Bytes fromHex(const std::string& hex);
} // namespace Echoion::Protocol::Util
-184
View File
@@ -1,184 +0,0 @@
#include "echoion/protocol/Command.hpp"
#include <sstream>
#include <stdexcept>
namespace Echoion::Protocol
{
std::string tsEscape(const std::string& str)
{
std::string out;
out.reserve(str.size());
for (char c : str) {
switch (c) {
case '\\':
out += "\\\\";
break;
case '/':
out += "\\/";
break;
case ' ':
out += "\\s";
break;
case '|':
out += "\\p";
break;
case '\f':
out += "\\f";
break;
case '\n':
out += "\\n";
break;
case '\r':
out += "\\r";
break;
case '\t':
out += "\\t";
break;
case '\v':
out += "\\v";
break;
default:
out.push_back(c);
}
}
return out;
}
std::string tsUnescape(const std::string& str)
{
std::string out;
out.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] == '\\') {
if (++i >= str.size()) {
throw std::runtime_error("invalid escape sequence");
}
switch (str[i]) {
case '\\':
out.push_back('\\');
break;
case '/':
out.push_back('/');
break;
case 's':
out.push_back(' ');
break;
case 'p':
out.push_back('|');
break;
case 'f':
out.push_back('\f');
break;
case 'n':
out.push_back('\n');
break;
case 'r':
out.push_back('\r');
break;
case 't':
out.push_back('\t');
break;
case 'v':
out.push_back('\v');
break;
default:
throw std::runtime_error(std::string("unknown escape: \\") +
str[i]);
}
} else {
out.push_back(str[i]);
}
}
return out;
}
std::string buildCommand(const std::string& name,
const CommandParams& params)
{
std::string cmd = tsEscape(name);
for (const auto& [key, value] : params) {
cmd += ' ';
cmd += key;
cmd += '=';
cmd += tsEscape(value);
}
return cmd;
}
namespace
{
CommandParams parseGroup(const std::string& part)
{
CommandParams params;
std::istringstream iss(part);
std::string token;
while (std::getline(iss, token, ' ')) {
if (token.empty()) {
continue;
}
auto eq = token.find('=');
if (eq != std::string::npos) {
params[token.substr(0, eq)] =
tsUnescape(token.substr(eq + 1));
} else {
params[token] = "";
}
}
return params;
}
std::string trim(const std::string& s)
{
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) {
return "";
}
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
} // namespace
ParsedCommand parseCommand(const std::string& raw)
{
// Split on '|' into groups.
std::vector<std::string> parts;
{
std::string cur;
for (char c : raw) {
if (c == '|') {
parts.push_back(cur);
cur.clear();
} else {
cur.push_back(c);
}
}
parts.push_back(cur);
}
ParsedCommand out;
std::string first = trim(parts[0]);
// The command name is the first whitespace-delimited token.
std::string body;
auto sp = first.find(' ');
if (sp == std::string::npos) {
out.name = tsUnescape(first);
body = "";
} else {
out.name = tsUnescape(first.substr(0, sp));
body = first.substr(sp + 1);
}
out.params = parseGroup(body);
if (parts.size() > 1) {
out.groups.push_back(out.params);
for (size_t g = 1; g < parts.size(); ++g) {
out.groups.push_back(parseGroup(trim(parts[g])));
}
}
return out;
}
} // namespace Echoion::Protocol
-253
View File
@@ -1,253 +0,0 @@
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <cstring>
#include <stdexcept>
namespace Echoion::Protocol::Crypto
{
namespace
{
// Raw single-block AES-128-ECB encryption (no padding). Used to build
// CMAC; matches the reference's aesEncryptBlock().
std::array<uint8_t, BLOCK_SIZE> aesEncryptBlock(
ByteView key, std::span<const uint8_t, BLOCK_SIZE> block)
{
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
}
std::array<uint8_t, BLOCK_SIZE> out{};
int len = 0;
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(),
nullptr) != 1 ||
EVP_CIPHER_CTX_set_padding(ctx, 0) != 1 ||
EVP_EncryptUpdate(ctx, out.data(), &len, block.data(),
static_cast<int>(BLOCK_SIZE)) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-ECB block encrypt failed");
}
EVP_CIPHER_CTX_free(ctx);
return out;
}
// GF(2^128) left-shift-by-one with the 0x87 reduction polynomial.
std::array<uint8_t, BLOCK_SIZE> doubleBlock(
const std::array<uint8_t, BLOCK_SIZE>& buf)
{
std::array<uint8_t, BLOCK_SIZE> out{};
uint8_t carry = 0;
for (int i = BLOCK_SIZE - 1; i >= 0; --i) {
uint16_t tmp = static_cast<uint16_t>((buf[i] << 1) | carry);
out[i] = static_cast<uint8_t>(tmp & 0xff);
carry = (buf[i] >> 7) & 1;
}
if (carry) {
out[BLOCK_SIZE - 1] ^= 0x87;
}
return out;
}
// EAX OMAC over a tag byte prepended in a leading block, then `data`.
std::array<uint8_t, BLOCK_SIZE> eaxOmac(ByteView key, uint8_t tag,
ByteView data)
{
Bytes input(BLOCK_SIZE + data.size(), 0);
input[BLOCK_SIZE - 1] = tag;
if (!data.empty()) {
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size());
}
return cmac(key, input);
}
// AES-128-CTR keystream applied to `in`, IV = `nonce`.
Bytes aesCtr(ByteView key, std::span<const uint8_t, BLOCK_SIZE> nonce,
ByteView in)
{
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
}
Bytes out(in.size(), 0);
int len = 0;
int total = 0;
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key.data(),
nonce.data()) != 1 ||
EVP_EncryptUpdate(ctx, out.data(), &len, in.data(),
static_cast<int>(in.size())) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-CTR failed");
}
total = len;
if (EVP_EncryptFinal_ex(ctx, out.data() + total, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-CTR final failed");
}
EVP_CIPHER_CTX_free(ctx);
out.resize(static_cast<size_t>(total) + len);
return out;
}
} // namespace
std::array<uint8_t, 20> sha1(ByteView data)
{
std::array<uint8_t, 20> out{};
::SHA1(data.data(), data.size(), out.data());
return out;
}
std::array<uint8_t, 32> sha256(ByteView data)
{
std::array<uint8_t, 32> out{};
::SHA256(data.data(), data.size(), out.data());
return out;
}
std::array<uint8_t, 64> sha512(ByteView data)
{
std::array<uint8_t, 64> out{};
::SHA512(data.data(), data.size(), out.data());
return out;
}
Bytes xorBuffers(ByteView a, ByteView b)
{
size_t len = std::min(a.size(), b.size());
Bytes out(len, 0);
for (size_t i = 0; i < len; ++i) {
out[i] = a[i] ^ b[i];
}
return out;
}
void xorInto(std::span<uint8_t> a, ByteView b, size_t len)
{
for (size_t i = 0; i < len; ++i) {
a[i] ^= b[i];
}
}
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data)
{
const std::array<uint8_t, BLOCK_SIZE> zero{};
auto L = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
zero.data(), BLOCK_SIZE));
auto K1 = doubleBlock(L);
auto K2 = doubleBlock(K1);
const size_t n = data.size();
const size_t numBlocks = n == 0 ? 1 : (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
const bool lastComplete = n > 0 && n % BLOCK_SIZE == 0;
std::array<uint8_t, BLOCK_SIZE> x{};
for (size_t i = 0; i + 1 < numBlocks; ++i) {
std::array<uint8_t, BLOCK_SIZE> block{};
std::memcpy(block.data(), data.data() + i * BLOCK_SIZE, BLOCK_SIZE);
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
block[j] ^= x[j];
}
x = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
block.data(), BLOCK_SIZE));
}
std::array<uint8_t, BLOCK_SIZE> last{};
const size_t off = (numBlocks - 1) * BLOCK_SIZE;
if (lastComplete) {
std::memcpy(last.data(), data.data() + off, BLOCK_SIZE);
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= K1[j];
}
} else {
const size_t rem = n - off;
if (rem != 0) {
std::memcpy(last.data(), data.data() + off, rem);
}
last[rem] = 0x80;
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= K2[j];
}
}
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= x[j];
}
return aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
last.data(), BLOCK_SIZE));
}
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
ByteView plaintext)
{
auto N = eaxOmac(key, 0, nonce);
auto H = eaxOmac(key, 1, header);
Bytes ciphertext = aesCtr(
key, std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
plaintext);
auto C = eaxOmac(key, 2, ciphertext);
EaxResult res;
res.ciphertext = std::move(ciphertext);
for (size_t i = 0; i < MAC_LEN; ++i) {
res.mac[i] = N[i] ^ H[i] ^ C[i];
}
return res;
}
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
ByteView header, ByteView ciphertext,
ByteView mac)
{
auto N = eaxOmac(key, 0, nonce);
auto H = eaxOmac(key, 1, header);
auto C = eaxOmac(key, 2, ciphertext);
std::array<uint8_t, MAC_LEN> tag{};
uint8_t diff = 0;
for (size_t i = 0; i < MAC_LEN; ++i) {
tag[i] = N[i] ^ H[i] ^ C[i];
diff |= static_cast<uint8_t>(tag[i] ^ (i < mac.size() ? mac[i] : 0));
}
if (diff != 0 || mac.size() < MAC_LEN) {
return std::nullopt;
}
return aesCtr(key,
std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
ciphertext);
}
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
uint32_t generationId, uint8_t packetType,
ByteView ivStruct)
{
const size_t tmpLen = ivStruct.size() == 20 ? 26 : 70;
Bytes tmp(tmpLen, 0);
tmp[0] = fromServer ? 0x30 : 0x31;
tmp[1] = packetType;
tmp[2] = static_cast<uint8_t>((generationId >> 24) & 0xff);
tmp[3] = static_cast<uint8_t>((generationId >> 16) & 0xff);
tmp[4] = static_cast<uint8_t>((generationId >> 8) & 0xff);
tmp[5] = static_cast<uint8_t>(generationId & 0xff);
std::memcpy(tmp.data() + 6, ivStruct.data(), ivStruct.size());
auto kn = sha256(tmp);
KeyNonce out;
std::memcpy(out.key.data(), kn.data(), 16);
std::memcpy(out.nonce.data(), kn.data() + 16, 16);
out.key[0] ^= static_cast<uint8_t>((packetId >> 8) & 0xff);
out.key[1] ^= static_cast<uint8_t>(packetId & 0xff);
return out;
}
std::string hashPassword(const std::string& password)
{
if (password.empty()) {
return "";
}
auto digest = sha1(ByteView(
reinterpret_cast<const uint8_t*>(password.data()), password.size()));
return Util::base64Encode(ByteView(digest.data(), digest.size()));
}
} // namespace Echoion::Protocol::Crypto
-675
View File
@@ -1,675 +0,0 @@
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/param_build.h>
#include <openssl/pem.h>
#include <algorithm>
#include <array>
#include <filesystem>
#include <fstream>
#include <regex>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
namespace Echoion::Protocol
{
namespace
{
using Bytes = std::vector<uint8_t>;
[[noreturn]] void fail(const char* what)
{
throw std::runtime_error(std::string("Identity: ") + what);
}
EVP_PKEY* asPkey(const std::shared_ptr<void>& p)
{
return static_cast<EVP_PKEY*>(p.get());
}
struct ParsedPrivateKey {
BIGNUM* privateKey = nullptr;
BIGNUM* publicX = nullptr;
BIGNUM* publicY = nullptr;
~ParsedPrivateKey()
{
BN_free(privateKey);
BN_free(publicX);
BN_free(publicY);
}
ParsedPrivateKey() = default;
ParsedPrivateKey(const ParsedPrivateKey&) = delete;
ParsedPrivateKey& operator=(const ParsedPrivateKey&) = delete;
ParsedPrivateKey(ParsedPrivateKey&& other) noexcept
: privateKey(std::exchange(other.privateKey, nullptr)),
publicX(std::exchange(other.publicX, nullptr)),
publicY(std::exchange(other.publicY, nullptr))
{
}
};
size_t readDerLength(Crypto::ByteView der, size_t& position)
{
if (position >= der.size()) {
fail("truncated DER length");
}
const auto first = der[position++];
if (first < 0x80) {
return first;
}
const auto bytes = static_cast<size_t>(first & 0x7f);
if (bytes == 0 || bytes > sizeof(size_t) ||
position + bytes > der.size()) {
fail("invalid DER length");
}
size_t length = 0;
for (size_t i = 0; i < bytes; ++i) {
length = (length << 8) | der[position++];
}
return length;
}
ParsedPrivateKey parsePrivateKeyDer(Crypto::ByteView der)
{
if (der.empty() || der.front() != 0x30) {
fail("imported key is not a DER sequence");
}
size_t position = 1;
const auto sequenceLength = readDerLength(der, position);
if (position + sequenceLength != der.size()) {
fail("invalid imported key length");
}
uint8_t keyKind = 0;
std::vector<BIGNUM*> integers;
while (position < der.size()) {
const auto tag = der[position++];
const auto length = readDerLength(der, position);
if (position + length > der.size()) {
for (auto* value : integers) {
BN_free(value);
}
fail("truncated imported key");
}
if (tag == 0x03) {
if (length < 2) {
fail("invalid imported key flags");
}
keyKind = der[position + 1];
} else if (tag == 0x02) {
integers.push_back(BN_bin2bn(
der.data() + position, static_cast<int>(length), nullptr));
}
position += length;
}
ParsedPrivateKey parsed;
// INTEGER lists exclude the bit string. Public+private is
// [32, x, y, d]; private-only is [32, d].
if (keyKind == 0x80 && integers.size() == 4) {
parsed.publicX = integers[1];
parsed.publicY = integers[2];
parsed.privateKey = integers[3];
BN_free(integers[0]);
} else if (keyKind == 0xc0 && integers.size() == 2) {
parsed.privateKey = integers[1];
BN_free(integers[0]);
} else {
for (auto* value : integers) {
BN_free(value);
}
fail("unsupported imported identity key");
}
return parsed;
}
EVP_PKEY* makePrivateKey(ParsedPrivateKey& parsed)
{
std::array<uint8_t, 65> publicPoint{};
publicPoint[0] = 0x04;
if (!parsed.publicX || !parsed.publicY) {
EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
EC_POINT* point = group ? EC_POINT_new(group) : nullptr;
if (!group || !point ||
EC_POINT_mul(group, point, parsed.privateKey, nullptr, nullptr,
nullptr) != 1 ||
EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED,
publicPoint.data(), publicPoint.size(), nullptr) !=
publicPoint.size()) {
EC_POINT_free(point);
EC_GROUP_free(group);
fail("cannot derive imported public key");
}
EC_POINT_free(point);
EC_GROUP_free(group);
} else {
if (BN_bn2binpad(parsed.publicX, publicPoint.data() + 1, 32) != 32 ||
BN_bn2binpad(parsed.publicY, publicPoint.data() + 33, 32) != 32) {
fail("invalid imported public key");
}
}
OSSL_PARAM_BLD* builder = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME,
"prime256v1", 0);
OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY,
publicPoint.data(), publicPoint.size());
OSSL_PARAM_BLD_push_BN(builder, OSSL_PKEY_PARAM_PRIV_KEY,
parsed.privateKey);
OSSL_PARAM* params = OSSL_PARAM_BLD_to_param(builder);
EVP_PKEY_CTX* context =
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
EVP_PKEY* key = nullptr;
const bool ok = context && EVP_PKEY_fromdata_init(context) == 1 &&
EVP_PKEY_fromdata(context, &key, EVP_PKEY_KEYPAIR, params) == 1;
EVP_PKEY_CTX_free(context);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(builder);
if (!ok) {
fail("cannot construct imported private key");
}
return key;
}
// Minimal big-endian encoding of a BIGNUM (no leading zeros).
Bytes bnBytes(const BIGNUM* bn)
{
int n = BN_num_bytes(bn);
Bytes out(static_cast<size_t>(n < 0 ? 0 : n), 0);
if (n > 0) {
BN_bn2bin(bn, out.data());
}
return out;
}
Bytes derLength(size_t len)
{
if (len < 0x80) {
return {static_cast<uint8_t>(len)};
}
if (len < 0x100) {
return {0x81, static_cast<uint8_t>(len)};
}
return {0x82, static_cast<uint8_t>((len >> 8) & 0xff),
static_cast<uint8_t>(len & 0xff)};
}
// DER INTEGER from a non-negative big-endian magnitude.
Bytes derInteger(Bytes mag)
{
if (mag.empty()) {
mag.push_back(0);
}
if (mag[0] & 0x80) {
mag.insert(mag.begin(), 0x00);
}
Bytes out;
out.push_back(0x02);
Bytes len = derLength(mag.size());
out.insert(out.end(), len.begin(), len.end());
out.insert(out.end(), mag.begin(), mag.end());
return out;
}
Bytes derIntegerFromU64(uint64_t v)
{
BIGNUM* bn = BN_new();
BN_set_word(bn, v);
Bytes r = derInteger(bnBytes(bn));
BN_free(bn);
return r;
}
// libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x),
// INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00)
// plus 0x07 0x00 in the reference; we reproduce it verbatim.
std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y)
{
Bytes content;
const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00};
content.insert(content.end(), std::begin(bitStr), std::end(bitStr));
Bytes i32 = derIntegerFromU64(32);
Bytes ix = derInteger(bnBytes(x));
Bytes iy = derInteger(bnBytes(y));
content.insert(content.end(), i32.begin(), i32.end());
content.insert(content.end(), ix.begin(), ix.end());
content.insert(content.end(), iy.begin(), iy.end());
Bytes der;
der.push_back(0x30);
Bytes len = derLength(content.size());
der.insert(der.end(), len.begin(), len.end());
der.insert(der.end(), content.begin(), content.end());
return Util::base64Encode(Crypto::ByteView(der.data(), der.size()));
}
// Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY.
Bytes pubPoint(EVP_PKEY* pkey)
{
size_t len = 0;
if (EVP_PKEY_get_octet_string_param(
pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) {
fail("cannot read public point length");
}
Bytes buf(len, 0);
if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY,
buf.data(), len, &len) != 1) {
fail("cannot read public point");
}
buf.resize(len);
return buf;
}
int countLeadingZeroBits(Crypto::ByteView data)
{
int count = 0;
for (uint8_t b : data) {
if (b == 0) {
count += 8;
} else {
for (int bit = 0; bit < 8; ++bit) {
if ((b & (1 << bit)) == 0) {
++count;
} else {
return count;
}
}
}
}
return count;
}
int securityLevelFor(const std::string& pubKeyString, uint64_t offset)
{
std::string s = pubKeyString + std::to_string(offset);
auto h = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(s.data()), s.size()));
return countLeadingZeroBits(
Crypto::ByteView(h.data(), h.size()));
}
// libtomcrypt DER parse → the two public-key INTEGERs (x, y). See
// reference parseDerSequence: collected = [bitByte, 32, x, y].
void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y)
{
size_t pos = 0;
auto readLen = [&](size_t& p) -> size_t {
uint8_t first = der[p++];
if (first < 0x80) {
return first;
}
int nb = first & 0x7f;
size_t len = 0;
for (int i = 0; i < nb; ++i) {
len = (len << 8) | der[p++];
}
return len;
};
if (der.empty() || der[pos++] != 0x30) {
fail("server key: expected SEQUENCE");
}
readLen(pos);
std::vector<BIGNUM*> ints;
while (pos < der.size()) {
uint8_t tag = der[pos++];
size_t len = readLen(pos);
if (tag == 0x02) {
ints.push_back(
BN_bin2bn(der.data() + pos, static_cast<int>(len),
nullptr));
}
pos += len;
}
// ints = [32, x, y]; guard against short input.
if (ints.size() < 3) {
for (auto* b : ints) {
BN_free(b);
}
fail("server key: too few integers");
}
*x = ints[1];
*y = ints[2];
for (size_t i = 0; i < ints.size(); ++i) {
if (i != 1 && i != 2) {
BN_free(ints[i]);
}
}
}
} // namespace
void Identity::PKeyDeleter::operator()(void* p) const noexcept
{
EVP_PKEY_free(static_cast<EVP_PKEY*>(p));
}
Identity Identity::importTeamSpeakIni(const std::string& path)
{
std::ifstream input(path, std::ios::binary);
if (!input) {
fail("cannot open TeamSpeak identity export");
}
const std::string contents((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// TeamSpeak's exported value is <valid-key-offset>V<base64>. It may
// appear quoted or as the value of an INI property.
const std::regex pattern{R"((\d+)V([A-Za-z0-9+/]+={0,2}))"};
std::smatch match;
if (!std::regex_search(contents, match, pattern)) {
fail("TeamSpeak export does not contain an identity");
}
uint64_t offset = 0;
try {
offset = std::stoull(match[1].str());
} catch (const std::exception&) {
fail("invalid TeamSpeak key offset");
}
auto obfuscated = Util::base64Decode(match[2].str());
if (obfuscated.size() < 20) {
fail("TeamSpeak identity is too short");
}
const auto payloadBegin = obfuscated.begin() + 20;
const auto nullPosition =
std::find(payloadBegin, obfuscated.end(), uint8_t{0});
const auto hash = Crypto::sha1(Crypto::ByteView(
&*payloadBegin, static_cast<size_t>(nullPosition - payloadBegin)));
for (size_t i = 0; i < hash.size(); ++i) {
obfuscated[i] ^= hash[i];
}
constexpr std::string_view obfuscationKey =
"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802"
"01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e";
const auto xorLength = std::min(obfuscated.size(), size_t{100});
for (size_t i = 0; i < xorLength; ++i) {
obfuscated[i] ^= static_cast<uint8_t>(obfuscationKey[i]);
}
std::string encoded(obfuscated.begin(), obfuscated.end());
if (const auto nul = encoded.find('\0'); nul != std::string::npos) {
encoded.resize(nul);
}
const auto der = Util::base64Decode(encoded);
auto parsed = parsePrivateKeyDer(der);
EVP_PKEY* key = makePrivateKey(parsed);
EVP_PKEY_CTX* checkContext = EVP_PKEY_CTX_new(key, nullptr);
const bool valid = checkContext &&
EVP_PKEY_private_check(checkContext) == 1 &&
EVP_PKEY_pairwise_check(checkContext) == 1;
EVP_PKEY_CTX_free(checkContext);
if (!valid) {
EVP_PKEY_free(key);
fail("TeamSpeak identity key pair is inconsistent");
}
Identity identity;
identity.pkey_ = std::shared_ptr<void>(key, PKeyDeleter{});
const auto point = pubPoint(key);
if (point.size() != 65 || point.front() != 0x04) {
fail("unexpected imported public key format");
}
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
identity.publicKeyString_ = buildPublicKeyString(x, y);
BN_free(x);
BN_free(y);
identity.keyOffset_ = offset;
const auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(identity.publicKeyString_.data()),
identity.publicKeyString_.size()));
identity.uid_ = Util::base64Encode(uidHash);
return identity;
}
Identity Identity::generate(int securityLevel)
{
EVP_PKEY* pkey = nullptr;
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!ctx) {
fail("keygen ctx");
}
if (EVP_PKEY_keygen_init(ctx) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen init");
}
OSSL_PARAM params[2] = {
OSSL_PARAM_construct_utf8_string(
OSSL_PKEY_PARAM_GROUP_NAME,
const_cast<char*>("prime256v1"), 0),
OSSL_PARAM_construct_end()};
EVP_PKEY_CTX_set_params(ctx, params);
if (EVP_PKEY_keygen(ctx, &pkey) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen");
}
EVP_PKEY_CTX_free(ctx);
Identity id;
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
Bytes point = pubPoint(pkey);
if (point.size() != 65 || point[0] != 0x04) {
fail("unexpected public point format");
}
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
id.publicKeyString_ = buildPublicKeyString(x, y);
BN_free(x);
BN_free(y);
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
// Hashcash: find the offset giving the most leading-zero bits, up to
// the requested level.
if (securityLevel > 0) {
uint64_t offset = 0;
int best = securityLevelFor(id.publicKeyString_, offset);
uint64_t checked = 0;
while (best < securityLevel) {
++checked;
int curr = securityLevelFor(id.publicKeyString_, checked);
if (curr > best) {
best = curr;
offset = checked;
}
}
id.keyOffset_ = offset;
}
return id;
}
int Identity::securityLevel() const
{
return securityLevelFor(publicKeyString_, keyOffset_);
}
Identity::Bytes Identity::sign(ByteView data) const
{
EVP_PKEY* pkey = asPkey(pkey_);
EVP_MD_CTX* md = EVP_MD_CTX_new();
if (!md) {
fail("sign ctx");
}
size_t siglen = 0;
if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 ||
EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign init");
}
Bytes sig(siglen, 0);
if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign");
}
sig.resize(siglen);
EVP_MD_CTX_free(md);
return sig;
}
Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const
{
BIGNUM* x = nullptr;
BIGNUM* y = nullptr;
parseServerPub(serverPublicKeyDer, &x, &y);
// Build uncompressed point 0x04 || x(32) || y(32).
Bytes point(65, 0);
point[0] = 0x04;
BN_bn2binpad(x, point.data() + 1, 32);
BN_bn2binpad(y, point.data() + 33, 32);
BN_free(x);
BN_free(y);
EVP_PKEY* peer = nullptr;
{
OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
"prime256v1", 0);
OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY,
point.data(), point.size());
OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld);
EVP_PKEY_CTX* pctx =
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 ||
EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) {
if (pctx) {
EVP_PKEY_CTX_free(pctx);
}
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
fail("build peer key");
}
EVP_PKEY_CTX_free(pctx);
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
}
EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr);
size_t secretLen = 0;
if (!dctx || EVP_PKEY_derive_init(dctx) != 1 ||
EVP_PKEY_derive_set_peer(dctx, peer) != 1 ||
EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) {
if (dctx) {
EVP_PKEY_CTX_free(dctx);
}
EVP_PKEY_free(peer);
fail("ecdh derive init");
}
Bytes secret(secretLen, 0);
if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) {
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
fail("ecdh derive");
}
secret.resize(secretLen);
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
// Pad/truncate to 32 bytes, then SHA-1 (matches reference).
Bytes keyArr(32, 0);
if (secret.size() >= 32) {
std::copy(secret.end() - 32, secret.end(), keyArr.begin());
} else {
std::copy(secret.begin(), secret.end(),
keyArr.begin() + (32 - secret.size()));
}
auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size()));
return Bytes(h.begin(), h.end());
}
void Identity::save(const std::string& path) const
{
EVP_PKEY* pkey = asPkey(pkey_);
BIO* mem = BIO_new(BIO_s_mem());
if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr,
nullptr)) {
BIO_free(mem);
fail("serialize private key");
}
char* data = nullptr;
long n = BIO_get_mem_data(mem, &data);
std::string pem(data, static_cast<size_t>(n));
BIO_free(mem);
const std::filesystem::path destination{path};
const auto temporary = destination.string() + ".tmp";
std::ofstream out(temporary, std::ios::binary | std::ios::trunc);
if (!out) {
fail("cannot open identity file for writing");
}
out << "ECHOION_IDENTITY_V1\n";
out << keyOffset_ << "\n";
out << publicKeyString_ << "\n";
out << "-----PRIVATE-----\n";
out << pem;
out.close();
if (!out) {
std::filesystem::remove(temporary);
fail("cannot finish writing identity file");
}
std::filesystem::permissions(
temporary,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace);
std::error_code renameError;
std::filesystem::rename(temporary, destination, renameError);
if (renameError) {
std::filesystem::remove(temporary);
fail("cannot install identity file");
}
}
Identity Identity::load(const std::string& path)
{
std::ifstream in(path);
if (!in) {
fail("cannot open identity file");
}
std::string magic;
std::getline(in, magic);
if (magic != "ECHOION_IDENTITY_V1") {
fail("bad identity file magic");
}
std::string offsetLine;
std::getline(in, offsetLine);
Identity id;
id.keyOffset_ = std::stoull(offsetLine);
std::getline(in, id.publicKeyString_);
std::string sep;
std::getline(in, sep); // -----PRIVATE-----
std::string pem((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
BIO* mem = BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size()));
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr);
BIO_free(mem);
if (!pkey) {
fail("cannot parse private key");
}
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
return id;
}
} // namespace Echoion::Protocol
-171
View File
@@ -1,171 +0,0 @@
#include "echoion/protocol/License.hpp"
#include "echoion/protocol/Crypto.hpp"
#include <sodium.h>
#include <cstring>
#include <mutex>
#include <stdexcept>
namespace Echoion::Protocol
{
namespace
{
[[noreturn]] void fail(const char* what)
{
throw std::runtime_error(std::string("License: ") + what);
}
void ensureSodium()
{
static std::once_flag once;
static bool ok = false;
std::call_once(once, [] { ok = sodium_init() >= 0; });
if (!ok) {
fail("libsodium init failed");
}
}
// Ed25519 point compressed root key.
constexpr std::array<uint8_t, 32> LICENSE_ROOT_KEY = {
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c,
0xfd, 0x8f, 0x68, 0xb3, 0xdc, 0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec,
0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a};
size_t findNullTerminator(ByteView data, size_t start)
{
for (size_t i = start; i < data.size(); ++i) {
if (data[i] == 0) {
return i - start;
}
}
fail("non-null-terminated string in license");
}
} // namespace
std::vector<LicenseBlock> parseLicense(ByteView data)
{
if (data.size() < 1) {
fail("license too short");
}
if (data[0] != 1) {
fail("unsupported license version");
}
std::vector<LicenseBlock> blocks;
size_t pos = 1;
while (pos < data.size()) {
if (data.size() - pos < 42) {
fail("license block too short");
}
if (data[pos] != 0) {
fail("wrong key kind");
}
LicenseBlock block;
std::memcpy(block.key.data(), data.data() + pos + 1, 32);
const uint8_t blockType = data[pos + 33];
block.type = blockType;
size_t extraLen = 0;
switch (blockType) {
case 0: // Intermediate
extraLen = findNullTerminator(data, pos + 46) + 5;
break;
case 2: // Server
extraLen = findNullTerminator(data, pos + 47) + 6;
break;
case 8: { // TS5 Server
size_t p = pos + 44;
const uint8_t propCount = data[pos + 43];
for (uint8_t i = 0; i < propCount; ++i) {
const uint8_t propLen = data[p];
p += 1 + propLen;
}
extraLen = p - (pos + 42);
break;
}
case 32: // Ephemeral
extraLen = 0;
break;
default:
fail("invalid license block type");
}
const size_t blockLen = 42 + extraLen;
if (pos + blockLen > data.size()) {
fail("license block overruns buffer");
}
auto content = data.subspan(pos + 1, blockLen - 1);
auto h = Crypto::sha512(content);
std::memcpy(block.hash.data(), h.data(), 32);
blocks.push_back(block);
pos += blockLen;
}
return blocks;
}
std::array<uint8_t, 32>
deriveLicenseKey(const std::vector<LicenseBlock>& blocks)
{
ensureSodium();
std::array<uint8_t, 32> parentKey = LICENSE_ROOT_KEY;
for (const auto& block : blocks) {
// Clamp the block hash into an Ed25519 scalar.
std::array<uint8_t, 32> scalar = block.hash;
scalar[0] &= 0xf8;
scalar[31] &= 0x3f;
scalar[31] |= 0x40;
std::array<uint8_t, 32> mul{};
if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(),
block.key.data()) != 0) {
fail("ed25519 scalarmult failed");
}
std::array<uint8_t, 32> sum{};
if (crypto_core_ed25519_add(sum.data(), mul.data(),
parentKey.data()) != 0) {
fail("ed25519 point add failed");
}
parentKey = sum;
}
return parentKey;
}
TempKey generateTemporaryKey()
{
ensureSodium();
TempKey out;
randombytes_buf(out.privateKey.data(), out.privateKey.size());
out.privateKey[0] &= 248;
out.privateKey[31] &= 127;
out.privateKey[31] |= 64;
if (crypto_scalarmult_ed25519_base_noclamp(out.publicKey.data(),
out.privateKey.data()) != 0) {
fail("ed25519 base mult failed");
}
return out;
}
std::array<uint8_t, 64> getSharedSecret2(ByteView serverDerivedKey,
ByteView tempPrivateKey)
{
ensureSodium();
if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) {
fail("bad key length for shared secret");
}
std::array<uint8_t, 32> priv{};
std::memcpy(priv.data(), tempPrivateKey.data(), 32);
priv[31] &= 0x7f;
std::array<uint8_t, 32> mul{};
if (crypto_scalarmult_ed25519_noclamp(mul.data(), priv.data(),
serverDerivedKey.data()) != 0) {
fail("ed25519 scalarmult failed");
}
return Crypto::sha512(ByteView(mul.data(), mul.size()));
}
} // namespace Echoion::Protocol
-158
View File
@@ -1,158 +0,0 @@
#include "echoion/protocol/QuickLz.hpp"
#include <algorithm>
#include <stdexcept>
namespace Echoion::Protocol
{
namespace
{
constexpr int TABLE_SIZE = 4096;
constexpr uint32_t MAX_DECOMPRESSED_SIZE = 1024 * 1024;
uint32_t readU32LE(ByteView b, size_t off)
{
return static_cast<uint32_t>(b[off]) |
(static_cast<uint32_t>(b[off + 1]) << 8) |
(static_cast<uint32_t>(b[off + 2]) << 16) |
(static_cast<uint32_t>(b[off + 3]) << 24);
}
int32_t readI32LE(ByteView b, size_t off)
{
return static_cast<int32_t>(readU32LE(b, off));
}
uint32_t read24(const Bytes& b, size_t off)
{
return static_cast<uint32_t>(b[off]) |
(static_cast<uint32_t>(b[off + 1]) << 8) |
(static_cast<uint32_t>(b[off + 2]) << 16);
}
int hashVal(uint32_t value)
{
return static_cast<int>(((value >> 12) ^ value) & 0xfff);
}
} // namespace
uint32_t qlzDecompressedSize(ByteView data)
{
return (data[0] & 0x02) != 0
? static_cast<uint32_t>(readI32LE(data, 5))
: data[2];
}
uint32_t qlzCompressedSize(ByteView data)
{
return (data[0] & 0x02) != 0
? static_cast<uint32_t>(readI32LE(data, 1))
: data[1];
}
Bytes qlzDecompress(ByteView data)
{
if (data.empty()) {
throw std::runtime_error("QuickLZ: empty input");
}
const uint8_t flags = data[0];
const int level = (flags >> 2) & 0x03;
if (level != 1) {
throw std::runtime_error("QuickLZ level not supported");
}
const size_t headerLen = (flags & 0x02) != 0 ? 9 : 3;
const uint32_t decompressedSize = qlzDecompressedSize(data);
if (decompressedSize > MAX_DECOMPRESSED_SIZE) {
throw std::runtime_error("QuickLZ: decompressed size exceeds max");
}
Bytes dest(decompressedSize, 0);
if ((flags & 0x01) == 0) {
// Stored, not compressed.
if (headerLen + decompressedSize > data.size()) {
throw std::runtime_error("QuickLZ: truncated stored block");
}
std::copy_n(data.begin() + headerLen, decompressedSize,
dest.begin());
return dest;
}
std::vector<int32_t> hashtable(TABLE_SIZE, 0);
uint32_t control = 1;
size_t sourcePos = headerLen;
size_t destPos = 0;
size_t nextHashed = 0;
while (true) {
if (control == 1) {
control = readU32LE(data, sourcePos);
sourcePos += 4;
}
if ((control & 1) != 0) {
control >>= 1;
const uint8_t next = data[sourcePos++];
const int hashIdx = (next >> 4) | (data[sourcePos++] << 4);
uint32_t matchLen = next & 0x0f;
if (matchLen != 0) {
matchLen += 2;
} else {
matchLen = data[sourcePos++];
}
const int32_t offset = hashtable[hashIdx];
dest[destPos] = dest[offset];
dest[destPos + 1] = dest[offset + 1];
dest[destPos + 2] = dest[offset + 2];
for (uint32_t i = 3; i < matchLen; ++i) {
dest[destPos + i] = dest[offset + i];
}
destPos += matchLen;
const size_t end = destPos + 1 - matchLen;
if (nextHashed < end) {
uint32_t nxt = read24(dest, nextHashed);
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
for (size_t i = nextHashed + 1; i < end; ++i) {
nxt = (nxt >> 8) |
(static_cast<uint32_t>(dest[i + 2]) << 16);
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
}
}
nextHashed = destPos;
} else if (destPos >=
std::max<size_t>(decompressedSize, 10) - 10) {
while (destPos < decompressedSize) {
if (control == 1) {
sourcePos += 4;
}
control >>= 1;
dest[destPos++] = data[sourcePos++];
}
break;
} else {
dest[destPos++] = data[sourcePos++];
control >>= 1;
const size_t end = destPos >= 2 ? destPos - 2 : 0;
if (nextHashed < end) {
uint32_t nxt = read24(dest, nextHashed);
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
for (size_t i = nextHashed + 1; i < end; ++i) {
nxt = (nxt >> 8) |
(static_cast<uint32_t>(dest[i + 2]) << 16);
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
}
}
nextHashed = std::max(nextHashed, end);
}
}
return dest;
}
} // namespace Echoion::Protocol
File diff suppressed because it is too large. Load diff
-116
View File
@@ -1,116 +0,0 @@
#include "echoion/protocol/Util.hpp"
#include <array>
#include <stdexcept>
namespace Echoion::Protocol::Util
{
namespace
{
constexpr char kEnc[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::array<int8_t, 256> makeDecodeTable()
{
std::array<int8_t, 256> t{};
t.fill(-1);
for (int i = 0; i < 64; ++i) {
t[static_cast<uint8_t>(kEnc[i])] = static_cast<int8_t>(i);
}
return t;
}
const std::array<int8_t, 256> kDec = makeDecodeTable();
} // namespace
std::string base64Encode(ByteView data)
{
std::string out;
out.reserve((data.size() + 2) / 3 * 4);
size_t i = 0;
for (; i + 3 <= data.size(); i += 3) {
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
(static_cast<uint32_t>(data[i + 1]) << 8) |
static_cast<uint32_t>(data[i + 2]);
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back(kEnc[(n >> 6) & 0x3f]);
out.push_back(kEnc[n & 0x3f]);
}
const size_t rem = data.size() - i;
if (rem == 1) {
uint32_t n = static_cast<uint32_t>(data[i]) << 16;
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back('=');
out.push_back('=');
} else if (rem == 2) {
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
(static_cast<uint32_t>(data[i + 1]) << 8);
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back(kEnc[(n >> 6) & 0x3f]);
out.push_back('=');
}
return out;
}
Bytes base64Decode(const std::string& text)
{
Bytes out;
out.reserve(text.size() / 4 * 3);
uint32_t buf = 0;
int bits = 0;
for (char c : text) {
if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
continue;
}
int8_t v = kDec[static_cast<uint8_t>(c)];
if (v < 0) {
throw std::runtime_error("invalid base64 character");
}
buf = (buf << 6) | static_cast<uint32_t>(v);
bits += 6;
if (bits >= 8) {
bits -= 8;
out.push_back(static_cast<uint8_t>((buf >> bits) & 0xff));
}
}
return out;
}
std::string toHex(ByteView data)
{
static const char* h = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (uint8_t b : data) {
out.push_back(h[b >> 4]);
out.push_back(h[b & 0x0f]);
}
return out;
}
Bytes fromHex(const std::string& hex)
{
auto nib = [](char c) -> int {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
throw std::runtime_error("invalid hex character");
};
if (hex.size() % 2 != 0) {
throw std::runtime_error("odd-length hex string");
}
Bytes out;
out.reserve(hex.size() / 2);
for (size_t i = 0; i < hex.size(); i += 2) {
out.push_back(static_cast<uint8_t>((nib(hex[i]) << 4) |
nib(hex[i + 1])));
}
return out;
}
} // namespace Echoion::Protocol::Util
-12
View File
@@ -1,12 +0,0 @@
# Unit tests for EchoionProtocol. Uses a tiny header-only harness (check.hpp),
# no external test framework required.
file(GLOB ECHOIONPROTOCOL_TEST_SOURCES CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/test_*.cpp")
add_executable(echoion_protocol_tests ${ECHOIONPROTOCOL_TEST_SOURCES})
target_link_libraries(echoion_protocol_tests PRIVATE EchoionProtocol)
target_include_directories(echoion_protocol_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_protocol_tests COMMAND echoion_protocol_tests)
-82
View File
@@ -1,82 +0,0 @@
#pragma once
// Minimal dependency-free test harness. Tests register cases with TEST_CASE and
// assert with CHECK / CHECK_EQ; main() runs them and reports a non-zero exit on
// any failure so ctest treats it as a failing test.
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
namespace echotest
{
struct Case {
std::string name;
std::function<void()> fn;
};
inline std::vector<Case>& registry()
{
static std::vector<Case> cases;
return cases;
}
inline int& failures()
{
static int f = 0;
return f;
}
struct Registrar {
Registrar(const std::string& name, std::function<void()> fn)
{
registry().push_back({name, std::move(fn)});
}
};
inline int run()
{
int failed = 0;
for (auto& c : registry()) {
int before = failures();
try {
c.fn();
} catch (const std::exception& e) {
std::printf(" [THROW] %s: %s\n", c.name.c_str(), e.what());
++failures();
}
if (failures() > before) {
std::printf("[FAIL] %s\n", c.name.c_str());
++failed;
} else {
std::printf("[ok] %s\n", c.name.c_str());
}
}
std::printf("\n%zu cases, %d failed\n", registry().size(), failed);
return failed == 0 ? 0 : 1;
}
} // namespace echotest
#define TEST_CASE(name) \
static void name(); \
static echotest::Registrar reg_##name(#name, name); \
static void name()
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::printf(" CHECK failed: %s (%s:%d)\n", #cond, __FILE__, \
__LINE__); \
++echotest::failures(); \
} \
} while (0)
#define CHECK_EQ(a, b) \
do { \
if (!((a) == (b))) { \
std::printf(" CHECK_EQ failed: %s == %s (%s:%d)\n", #a, #b, \
__FILE__, __LINE__); \
++echotest::failures(); \
} \
} while (0)
-55
View File
@@ -1,55 +0,0 @@
#include "check.hpp"
#include "echoion/protocol/Command.hpp"
using namespace Echoion::Protocol;
TEST_CASE(escape_roundtrip)
{
std::string raw = "hello world|pipe/slash\ttab\nnl\\back";
auto esc = tsEscape(raw);
// Spaces and specials must be escaped (no raw space/pipe left).
CHECK(esc.find(' ') == std::string::npos);
CHECK(esc.find('|') == std::string::npos);
CHECK_EQ(tsUnescape(esc), raw);
}
TEST_CASE(escape_known)
{
CHECK_EQ(tsEscape("a b"), std::string("a\\sb"));
CHECK_EQ(tsEscape("a|b"), std::string("a\\pb"));
CHECK_EQ(tsEscape("a/b"), std::string("a\\/b"));
CHECK_EQ(tsUnescape("a\\sb"), std::string("a b"));
}
TEST_CASE(build_command)
{
CommandParams p;
p["client_nickname"] = "My Bot";
p["cid"] = "5";
auto cmd = buildCommand("clientmove", p);
// Params are ordered by key (map): cid before client_nickname.
CHECK_EQ(cmd, std::string("clientmove cid=5 client_nickname=My\\sBot"));
}
TEST_CASE(parse_notify)
{
auto pc = parseCommand(
"notifytextmessage targetmode=2 msg=hello\\sworld invokerid=7 "
"invokername=Alice");
CHECK_EQ(pc.name, std::string("notifytextmessage"));
CHECK_EQ(pc.params["targetmode"], std::string("2"));
CHECK_EQ(pc.params["msg"], std::string("hello world"));
CHECK_EQ(pc.params["invokername"], std::string("Alice"));
}
TEST_CASE(parse_pipe_groups)
{
auto pc = parseCommand("channellist cid=1 channel_name=Default|cid=2 "
"channel_name=Talk");
CHECK_EQ(pc.name, std::string("channellist"));
CHECK_EQ(pc.groups.size(), size_t(2));
CHECK_EQ(pc.groups[0]["cid"], std::string("1"));
CHECK_EQ(pc.groups[0]["channel_name"], std::string("Default"));
CHECK_EQ(pc.groups[1]["cid"], std::string("2"));
CHECK_EQ(pc.groups[1]["channel_name"], std::string("Talk"));
}
-123
View File
@@ -1,123 +0,0 @@
#include "check.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <string>
using namespace Echoion::Protocol;
using Crypto::ByteView;
namespace
{
Crypto::Bytes hex(const std::string& h) { return Util::fromHex(h); }
std::string hx(ByteView b) { return Util::toHex(b); }
std::string hx(const std::vector<uint8_t>& b)
{
return Util::toHex(ByteView(b.data(), b.size()));
}
template <size_t N> std::string hx(const std::array<uint8_t, N>& b)
{
return Util::toHex(ByteView(b.data(), b.size()));
}
} // namespace
// RFC 4493 AES-128-CMAC known-answer vectors.
TEST_CASE(cmac_rfc4493)
{
auto key = hex("2b7e151628aed2a6abf7158809cf4f3c");
// Example 1: empty message.
CHECK_EQ(hx(Crypto::cmac(key, {})),
std::string("bb1d6929e95937287fa37d129b756746"));
// Example 2: 16-byte message.
auto m2 = hex("6bc1bee22e409f96e93d7e117393172a");
CHECK_EQ(hx(Crypto::cmac(key, m2)),
std::string("070a16b46b4d4144f79bdd9dd04a287c"));
// Example 3: 40-byte message.
auto m3 = hex("6bc1bee22e409f96e93d7e117393172a"
"ae2d8a571e03ac9c9eb76fac45af8e51"
"30c81c46a35ce411");
CHECK_EQ(hx(Crypto::cmac(key, m3)),
std::string("dfa66747de9ae63030ca32611497c827"));
// Example 4: 64-byte message.
auto m4 = hex("6bc1bee22e409f96e93d7e117393172a"
"ae2d8a571e03ac9c9eb76fac45af8e51"
"30c81c46a35ce411e5fbc1191a0a52ef"
"f69f2445df4f9b17ad2b417be66c3710");
CHECK_EQ(hx(Crypto::cmac(key, m4)),
std::string("51f0bebf7e3b9d92fc49741779363cfe"));
}
// EAX specification test vectors (Bellare/Rogaway/Wagner). The EAX output is
// ciphertext||tag where tag is the full 16-byte value; TeamSpeak truncates the
// MAC to 8 bytes, so we compare against the first 8 tag bytes.
TEST_CASE(eax_spec_vectors)
{
// Empty message.
{
auto key = hex("233952dee4d5ed5f9b9c6d6ff80ff478");
auto nonce = hex("62ec67f9c3a4a407fcb2a8c49031a8b3");
auto hdr = hex("6bfb914fd07eae6b");
auto res = Crypto::eaxEncrypt(key, nonce, hdr, {});
CHECK(res.ciphertext.empty());
CHECK_EQ(hx(res.mac), std::string("e037830e8389f27b"));
// Round-trip.
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
CHECK(dec.has_value());
CHECK(dec && dec->empty());
}
// 2-byte message F7FB.
{
auto key = hex("91945d3f4dcbee0bf45ef52255f095a4");
auto nonce = hex("becaf043b0a23d843194ba972c66debd");
auto hdr = hex("fa3bfd4806eb53fa");
auto msg = hex("f7fb");
auto res = Crypto::eaxEncrypt(key, nonce, hdr, msg);
CHECK_EQ(hx(res.ciphertext), std::string("19dd"));
CHECK_EQ(hx(res.mac), std::string("5c4c9331049d0bda"));
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
CHECK(dec.has_value());
CHECK(dec && hx(*dec) == std::string("f7fb"));
// Tamper → reject.
auto bad = res.mac;
bad[0] ^= 0x01;
CHECK(!Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, bad));
}
}
TEST_CASE(sha_and_base64)
{
// sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d
std::string abc = "abc";
auto s1 = Crypto::sha1(
ByteView(reinterpret_cast<const uint8_t*>(abc.data()), abc.size()));
CHECK_EQ(hx(s1),
std::string("a9993e364706816aba3e25717850c26c9cd0d89d"));
// base64 round-trip + known value.
CHECK_EQ(Util::base64Encode(ByteView(
reinterpret_cast<const uint8_t*>("foobar"), 6)),
std::string("Zm9vYmFy"));
auto dec = Util::base64Decode("Zm9vYmFy");
CHECK_EQ(std::string(dec.begin(), dec.end()), std::string("foobar"));
}
// deriveKeyNonce: verify the packetId XOR into key[0..1] and the deterministic
// structure. Uses a fixed 20-byte ivStruct.
TEST_CASE(derive_key_nonce)
{
auto iv = hex("000102030405060708090a0b0c0d0e0f10111213"); // 20 bytes
auto a = Crypto::deriveKeyNonce(false, 0, 0, 2, iv);
auto b = Crypto::deriveKeyNonce(false, 0x0102, 0, 2, iv);
// key[0] ^= pid>>8, key[1] ^= pid&0xff; nonce unchanged.
CHECK_EQ(a.key[0] ^ 0x01, b.key[0]);
CHECK_EQ(a.key[1] ^ 0x02, b.key[1]);
CHECK_EQ(hx(a.nonce), hx(b.nonce));
// Direction changes the derivation.
auto c = Crypto::deriveKeyNonce(true, 0, 0, 2, iv);
CHECK(hx(a.key) != hx(c.key));
}
-125
View File
@@ -1,125 +0,0 @@
#include "check.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/Util.hpp"
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <string>
using namespace Echoion::Protocol;
TEST_CASE(identity_generate_uid_and_level)
{
auto id = Identity::generate(8);
// uid must equal base64(sha1(ascii(publicKeyString))).
auto h = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString().data()),
id.publicKeyString().size()));
CHECK_EQ(id.uid(),
Util::base64Encode(Crypto::ByteView(h.data(), h.size())));
// publicKeyString is valid base64 of a DER SEQUENCE (starts with 0x30).
auto der = Util::base64Decode(id.publicKeyString());
CHECK(!der.empty());
CHECK_EQ(der[0], uint8_t(0x30));
// Security level actually reached the requested threshold.
CHECK(id.securityLevel() >= 8);
}
TEST_CASE(identity_sign_verifiable_length)
{
auto id = Identity::generate(0);
std::string msg = "hello";
auto sig = id.sign(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(msg.data()), msg.size()));
// DER ECDSA signature over P-256 is ~70-72 bytes; never empty.
CHECK(!sig.empty());
CHECK(sig[0] == 0x30); // DER SEQUENCE
}
TEST_CASE(identity_save_load_roundtrip)
{
auto id = Identity::generate(0);
std::string path = "/tmp/echoion_identity_test.txt";
id.save(path);
auto loaded = Identity::load(path);
CHECK_EQ(loaded.publicKeyString(), id.publicKeyString());
CHECK_EQ(loaded.uid(), id.uid());
CHECK_EQ(loaded.keyOffset(), id.keyOffset());
std::remove(path.c_str());
}
namespace
{
std::string teamSpeakExportForScalarOne(uint64_t offset)
{
// libtomcrypt private-only key: flags 0xc0, 256 bits, scalar d=1.
const std::vector<uint8_t> der{0x30, 0x0a, 0x03, 0x02, 0x06, 0xc0,
0x02, 0x01, 0x20, 0x02, 0x01, 0x01};
const auto decoded = Util::base64Encode(der);
std::vector<uint8_t> obfuscated(decoded.begin(), decoded.end());
constexpr std::string_view key =
"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802"
"01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e";
// Real exported identities are longer than 20 bytes. Pad the base64
// text with whitespace, which the decoder accepts, to exercise the
// exact TeamSpeak obfuscation algorithm.
obfuscated.resize(32, static_cast<uint8_t>(' '));
for (size_t i = 20; i < obfuscated.size(); ++i) {
obfuscated[i] ^= static_cast<uint8_t>(key[i]);
}
const auto hash = Crypto::sha1(Crypto::ByteView(
obfuscated.data() + 20, obfuscated.size() - 20));
for (size_t i = 0; i < 20; ++i) {
obfuscated[i] ^=
static_cast<uint8_t>(key[i]) ^ hash[i];
}
return std::to_string(offset) + "V" + Util::base64Encode(obfuscated);
}
}
TEST_CASE(identity_import_teamspeak_ini)
{
const std::string exportPath = "/tmp/echoion_ts_identity.ini";
const std::string nativePath = "/tmp/echoion_imported_identity.txt";
{
std::ofstream output(exportPath);
output << "[Identity]\nidentity=\"" << teamSpeakExportForScalarOne(42)
<< "\"\n";
}
const auto imported = Identity::importTeamSpeakIni(exportPath);
CHECK_EQ(imported.keyOffset(), uint64_t{42});
CHECK(!imported.uid().empty());
CHECK(!imported.sign({reinterpret_cast<const uint8_t*>("x"), 1}).empty());
imported.save(nativePath);
const auto loaded = Identity::load(nativePath);
CHECK_EQ(loaded.uid(), imported.uid());
const auto permissions = std::filesystem::status(nativePath).permissions();
CHECK((permissions & std::filesystem::perms::group_all) ==
std::filesystem::perms::none);
CHECK((permissions & std::filesystem::perms::others_all) ==
std::filesystem::perms::none);
std::remove(exportPath.c_str());
std::remove(nativePath.c_str());
}
TEST_CASE(identity_import_rejects_malformed_export)
{
const std::string path = "/tmp/echoion_bad_identity.ini";
{
std::ofstream output(path);
output << "[Identity]\nidentity=not-a-private-key\n";
}
bool rejected = false;
try {
(void)Identity::importTeamSpeakIni(path);
} catch (const std::exception&) {
rejected = true;
}
CHECK(rejected);
std::remove(path.c_str());
}
-6
View File
@@ -1,6 +0,0 @@
#include "check.hpp"
int main()
{
return echotest::run();
}
-36
View File
@@ -1,36 +0,0 @@
#include "check.hpp"
#include "echoion/protocol/QuickLz.hpp"
using namespace Echoion::Protocol;
// QuickLZ level-1 "stored" (uncompressed) block: header byte with level=1
// (bits 2-3 = 01 -> 0x04), compressed bit (bit0) = 0, short size form
// (bit1 = 0) -> 3-byte header: [flags, compressedSize, decompressedSize].
TEST_CASE(qlz_stored_block)
{
Bytes payload = {'h', 'e', 'l', 'l', 'o'};
Bytes buf;
buf.push_back(0x04); // flags: level 1, not compressed, short header
buf.push_back(static_cast<uint8_t>(3 + payload.size())); // compressed size
buf.push_back(static_cast<uint8_t>(payload.size())); // decompressed size
buf.insert(buf.end(), payload.begin(), payload.end());
CHECK_EQ(qlzDecompressedSize(buf), uint32_t(payload.size()));
CHECK_EQ(qlzCompressedSize(buf), uint32_t(3 + payload.size()));
auto out = qlzDecompress(buf);
CHECK_EQ(out.size(), payload.size());
CHECK(out == payload);
}
TEST_CASE(qlz_rejects_bad_level)
{
Bytes buf = {0x00, 0x03, 0x00}; // level 0 -> unsupported
bool threw = false;
try {
qlzDecompress(buf);
} catch (const std::exception&) {
threw = true;
}
CHECK(threw);
}
+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
@@ -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 {};
}
}
@@ -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;
}
@@ -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;
}
@@ -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);
}
@@ -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
+3
View File
@@ -19,6 +19,7 @@ import { StatsView } from './views/StatsView';
import { WatchView } from './views/WatchView';
import { ServerView } from './views/ServerView';
import { RpcView } from './views/RpcView';
import { RoomsView } from './views/RoomsView';
const HEADS: Record<string, [string, string]> = {
now: ['Now Playing', 'What Echoion is streaming to the channel'],
@@ -26,6 +27,7 @@ const HEADS: Record<string, [string, string]> = {
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
rooms: ['Listening Rooms', 'Independent music streams for different groups'],
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
@@ -102,6 +104,7 @@ export function App() {
{s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{s.view === 'rooms' && <RoomsView />}
{/* The watch view stays mounted so the embedded player and
room connection survive view switches (the old UI only
toggled `hidden`). */}
@@ -18,6 +18,7 @@ import {
HeartIcon,
PlayIcon,
QueueIcon,
RoomsIcon,
SearchIcon,
StatsIcon,
WatchIcon,
@@ -30,6 +31,7 @@ const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'rooms', icon: <RoomsIcon />, label: 'Listening Rooms' },
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
@@ -57,6 +57,9 @@ export const StatsIcon = makeIcon(
export const WatchIcon = makeIcon(
'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z'
);
export const RoomsIcon = makeIcon(
'M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z'
);
export const GearIcon = makeIcon(
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
);
@@ -76,6 +79,8 @@ export const RefreshIcon = makeIcon(
'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z'
);
export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z');
export const ArrowUpIcon = makeIcon('M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z');
export const ArrowDownIcon = makeIcon('M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.59-5.58L4 12l8 8 8-8z');
export const VolumeIcon = makeIcon(
'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z'
);
+42
View File
@@ -10,6 +10,9 @@ export const ru: Record<string, string> = {
'Library': 'Библиотека',
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Listening Rooms': 'Комнаты прослушивания',
'Independent music streams for different groups':
'Независимые музыкальные потоки для разных групп',
'Server & Admin': 'Сервер и админ',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
@@ -286,6 +289,45 @@ export const ru: Record<string, string> = {
'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист',
// Independent TeamSpeak listening rooms
'MULTI-STREAM': 'МУЛЬТИПОТОК',
'NOW TUNED': 'СЕЙЧАС В КОМНАТЕ',
'Your channel, split into listening spaces':
'Разделите канал на пространства для прослушивания',
'Each room has its own queue and bot stream. Join one to hear and control it.':
'У каждой комнаты своя очередь и поток бота. Войдите, чтобы слушать и управлять.',
'Room name': 'Название комнаты',
'Create room': 'Создать комнату',
'Created room “{0}”': 'Комната «{0}» создана',
'Live rooms': 'Активные комнаты',
'No listening rooms yet': 'Комнат прослушивания пока нет',
'{0} listeners · {1} queued': '{0} слушателей · {1} в очереди',
'JOINED': 'ВЫ В КОМНАТЕ',
'PAUSED': 'ПАУЗА',
'IDLE': 'ТИШИНА',
'Choose a room': 'Выберите комнату',
'Your TeamSpeak audio follows the room you join.':
'Звук TeamSpeak переключается на комнату, в которую вы вошли.',
'Leave': 'Выйти',
'Delete room': 'Удалить комнату',
'Delete “{0}” for everyone?': 'Удалить «{0}» для всех?',
'Stop': 'Остановить',
'Skip': 'Пропустить',
'Move up': 'Переместить выше',
'Move down': 'Переместить ниже',
'Pause': 'Пауза',
'Resume': 'Продолжить',
'Paused': 'На паузе',
'Streaming now': 'Сейчас транслируется',
'Ready': 'Готово',
'{0} people are tuned in': 'Подключено: {0}',
'Paste a URL or search for a track…':
'Вставьте ссылку или найдите трек…',
'Add': 'Добавить',
'Added to room queue': 'Добавлено в очередь комнаты',
'Room queue': 'Очередь комнаты',
'This room queue is empty': 'Очередь этой комнаты пуста',
// Controllable embeds (Kodik / Playerjs)
'Embed synced': 'Встраиваемый плеер синхронизирован',
'Embed is view-only': 'Встраиваемый плеер — только просмотр',
+1
View File
@@ -22,6 +22,7 @@ export type ViewName =
| 'search'
| 'library'
| 'stats'
| 'rooms'
| 'watch'
| 'server'
| 'rpc';
@@ -0,0 +1,11 @@
import { describe, expect, it } from 'vitest';
import { auditMethodName } from './auditMethods';
describe('audit RPC method mapping', () => {
it('keeps listening-room methods append-only and aligned with RpcTypes.hpp', () => {
expect(auditMethodName(53)).toBe('ListListeningRooms');
expect(auditMethodName(62)).toBe('GetListeningRoomQueue');
expect(auditMethodName(63)).toBe('SkipListeningRoom');
expect(auditMethodName(66)).toBe('ClearListeningRoomQueue');
});
});
@@ -58,6 +58,20 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
'AddCustomEmoji', // 50
'RemoveCustomEmoji',
'GetLyrics',
'ListListeningRooms',
'CreateListeningRoom',
'DeleteListeningRoom',
'JoinListeningRoom',
'LeaveListeningRoom',
'PlayInListeningRoom',
'PauseListeningRoom',
'ResumeListeningRoom',
'StopListeningRoom',
'GetListeningRoomQueue',
'SkipListeningRoom',
'RemoveFromListeningRoomQueue',
'MoveInListeningRoomQueue',
'ClearListeningRoomQueue',
];
export function auditMethodName(method: number): string {
+1
View File
@@ -13,6 +13,7 @@ const VIEWS: readonly ViewName[] = [
'search',
'library',
'stats',
'rooms',
'watch',
'server',
'rpc',
+14
View File
@@ -139,4 +139,18 @@ describe('RpcClient wire contract', () => {
});
expect(seen).toEqual([['queue.updated', { size: 3 }]]);
});
it('unsubscribes a notification listener', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
const unsubscribe = rpc.on('listening_rooms.updated', (data) =>
seen.push(data)
);
unsubscribe();
ws.receive({ event: 'listening_rooms.updated', data: '{}' });
expect(seen).toEqual([]);
});
});
+23 -1
View File
@@ -64,7 +64,22 @@ export type RpcMethodName =
| 'SetUserPrefs'
| 'GetCustomEmojis'
| 'AddCustomEmoji'
| 'RemoveCustomEmoji';
| 'RemoveCustomEmoji'
| 'ListListeningRooms'
| 'CreateListeningRoom'
| 'DeleteListeningRoom'
| 'JoinListeningRoom'
| 'LeaveListeningRoom'
| 'PlayInListeningRoom'
| 'PauseListeningRoom'
| 'ResumeListeningRoom'
| 'StopListeningRoom'
| 'GetListeningRoomQueue'
| 'SkipListeningRoom'
| 'RemoveFromListeningRoomQueue'
| 'MoveInListeningRoomQueue'
| 'ClearListeningRoomQueue';
type Pending = {
resolve: (value: unknown) => void;
@@ -226,6 +241,13 @@ export class RpcClient {
on(event: string, cb: (...args: unknown[]) => void) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event)!.push(cb);
return () => {
const listeners = this.listeners.get(event);
if (!listeners) return;
const index = listeners.indexOf(cb);
if (index >= 0) listeners.splice(index, 1);
if (listeners.length === 0) this.listeners.delete(event);
};
}
authenticate(token: string) {
+15
View File
@@ -19,6 +19,21 @@ export interface QueueEntry {
addedBy?: string;
}
export interface ListeningRoom {
name: string;
ownerId: number;
members: number[];
isPlaying: boolean;
isPaused: boolean;
queueSize: number;
isOwner: boolean;
}
export interface ListeningRoomList {
rooms: ListeningRoom[];
currentRoom?: string;
}
export interface Status {
isPlaying?: boolean;
isPaused?: boolean;
+62
View File
@@ -739,6 +739,68 @@ select:focus:not(:focus-visible) { outline: none; }
.rooms-create { display: flex; gap: 8px; }
.rooms-create input { flex: 1; }
/* ── Independent listening rooms ─────────────────────────────────────── */
.listening-rooms-view { --room-cyan: #61e4d8; --room-cyan-soft: rgba(97, 228, 216, .12); }
.rooms-hero {
display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(280px, .7fr);
gap: 28px; align-items: end; margin-bottom: 18px; padding: 24px;
border: 1px solid rgba(97, 228, 216, .15); border-radius: 18px;
background: radial-gradient(circle at 92% 8%, rgba(97, 228, 216, .14), transparent 34%), linear-gradient(115deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025));
position: relative; overflow: hidden;
}
.rooms-hero::after {
content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .22;
background-image: linear-gradient(rgba(255,255,255,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.035) 1px, transparent 1px);
background-size: 28px 28px; mask-image: linear-gradient(90deg, transparent, #000);
}
.rooms-hero > * { position: relative; z-index: 1; }
.rooms-hero h2 { font-size: clamp(20px, 2.5vw, 31px); max-width: 620px; letter-spacing: -.035em; }
.rooms-hero p { color: var(--muted); line-height: 1.55; max-width: 620px; margin-top: 8px; }
.rooms-kicker { display: block; margin-bottom: 7px; color: var(--room-cyan); font-family: var(--font-mono); font-size: 10px; font-weight: 700; letter-spacing: .18em; }
.listening-room-create { display: flex; gap: 8px; }
.listening-room-create input { flex: 1; min-width: 0; }
.listening-room-create .btn, .room-play-form .btn { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.listening-room-grid { display: grid; grid-template-columns: minmax(260px, .7fr) minmax(0, 1.3fr); gap: 18px; align-items: start; }
.room-directory, .room-console { min-height: 440px; }
.listening-room-list { display: flex; flex-direction: column; gap: 8px; }
.listening-room-card { width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding: 12px; text-align: left; color: var(--text-2); background: rgba(255,255,255,.025); border: 1px solid rgba(255,255,255,.055); border-radius: 11px; cursor: pointer; transition: border-color .16s, background .16s, transform .16s; }
.listening-room-card:hover { transform: translateX(2px); border-color: rgba(97,228,216,.22); background: rgba(97,228,216,.045); }
.listening-room-card.active { border-color: rgba(97,228,216,.5); background: var(--room-cyan-soft); box-shadow: inset 3px 0 0 var(--room-cyan); }
.room-signal { width: 9px; height: 9px; border-radius: 50%; background: var(--faint); box-shadow: 0 0 0 4px rgba(255,255,255,.025); }
.room-signal.playing { background: var(--room-cyan); box-shadow: 0 0 0 4px rgba(97,228,216,.1), 0 0 14px rgba(97,228,216,.45); animation: ech-pulse 1.6s infinite; }
.room-card-copy { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.room-card-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.room-card-copy small { color: var(--muted-2); }
.room-state { font-family: var(--font-mono); font-size: 9px; font-weight: 700; letter-spacing: .1em; color: var(--room-cyan); }
.room-console { position: relative; overflow: hidden; }
.room-console::before { content: ''; position: absolute; top: 0; right: 0; width: 180px; height: 180px; background: radial-gradient(circle at top right, rgba(124,92,255,.1), transparent 68%); pointer-events: none; }
.room-console-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; margin-bottom: 18px; position: relative; }
.room-console-head h2 { font-size: 25px; }
.room-console-empty { min-height: 390px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; color: var(--muted); }
.room-console-empty h2 { color: var(--text); margin: 8px 0 5px; }
.room-console-glyph { font-family: var(--font-mono); font-size: 54px; font-weight: 700; color: rgba(97,228,216,.15); letter-spacing: -.12em; }
.room-transport { display: flex; align-items: center; gap: 12px; padding: 14px; margin-bottom: 14px; border: 1px solid rgba(97,228,216,.12); border-radius: 13px; background: linear-gradient(90deg, rgba(97,228,216,.07), rgba(255,255,255,.025)); }
.room-transport .ctrl-main { background: var(--room-cyan); color: #061715; box-shadow: 0 5px 22px rgba(97,228,216,.22); }
.stop-square { width: 9px; height: 9px; background: currentColor; border-radius: 1px; }
.room-transport-copy { display: flex; flex-direction: column; gap: 2px; }
.room-transport-copy small { color: var(--muted-2); }
.room-play-form { display: flex; gap: 8px; margin-bottom: 20px; }
.room-play-form input { flex: 1; min-width: 0; }
.room-queue-head { display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--line); padding-top: 16px; margin-bottom: 5px; }
.room-queue-head span { color: var(--muted-2); font-family: var(--font-mono); font-size: 11px; }
.room-tracklist { max-height: 330px; overflow-y: auto; }
@media (max-width: 1080px) {
.listening-room-grid { grid-template-columns: 1fr; }
.room-directory, .room-console { min-height: 0; }
}
@media (max-width: 560px) {
.rooms-hero { grid-template-columns: 1fr; padding: 18px; }
.listening-room-create, .room-play-form { flex-wrap: wrap; }
.listening-room-create input, .room-play-form input { flex-basis: 100%; }
.room-console-head { flex-direction: column; }
}
/* Watch search (item 20). */
.watch-search { position: relative; margin-bottom: 8px; }
.watch-search-results {
+244
View File
@@ -0,0 +1,244 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type {
ListeningRoom,
ListeningRoomList,
QueueEntry,
} from '../lib/types';
import { confirmDialog } from '../lib/dialog';
import {
CloseIcon,
ArrowDownIcon,
ArrowUpIcon,
PauseIcon,
PlayIcon,
PlusIcon,
RefreshIcon,
SkipNextIcon,
} from '../components/icons';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { t, tf } from '../i18n';
import { rpc } from '../lib/rpc';
export function RoomsView() {
const [rooms, setRooms] = useState<ListeningRoom[]>([]);
const [currentRoom, setCurrentRoom] = useState<string | null>(null);
const [queue, setQueue] = useState<QueueEntry[]>([]);
const [roomName, setRoomName] = useState('');
const [query, setQuery] = useState('');
const [busy, setBusy] = useState(false);
const current = useMemo(
() => rooms.find((room) => room.name === currentRoom) || null,
[rooms, currentRoom]
);
const refresh = useCallback(async () => {
const result = await safeCall<ListeningRoomList>('ListListeningRooms');
if (!result) return;
setRooms(result.rooms || []);
setCurrentRoom(result.currentRoom || null);
if (result.currentRoom) {
const queueResult = await safeCall<{ queue?: QueueEntry[] }>(
'GetListeningRoomQueue',
{ room: result.currentRoom }
);
setQueue(queueResult?.queue || []);
} else {
setQueue([]);
}
}, []);
useEffect(() => {
void refresh();
const unsubscribe = rpc.on('listening_rooms.updated', () => void refresh());
const timer = window.setInterval(refresh, 30000);
return () => {
unsubscribe();
window.clearInterval(timer);
};
}, [refresh]);
const action = async (
method:
| 'JoinListeningRoom'
| 'LeaveListeningRoom'
| 'PauseListeningRoom'
| 'ResumeListeningRoom'
| 'StopListeningRoom'
| 'SkipListeningRoom'
| 'ClearListeningRoomQueue',
room?: string
) => {
setBusy(true);
const result = await safeCall(method, room ? { room } : undefined);
setBusy(false);
if (result) await refresh();
};
return (
<section className="view listening-rooms-view" id="view-rooms">
<div className="rooms-hero">
<div>
<span className="rooms-kicker">{t('MULTI-STREAM')}</span>
<h2>{t('Your channel, split into listening spaces')}</h2>
<p>
{t(
'Each room has its own queue and bot stream. Join one to hear and control it.'
)}
</p>
</div>
<form
className="listening-room-create"
onSubmit={async (event) => {
event.preventDefault();
const name = roomName.trim();
if (!name) return;
setBusy(true);
const result = await safeCall('CreateListeningRoom', {
room: name,
});
setBusy(false);
if (result) {
setRoomName('');
toast(tf('Created room “{0}”', name));
await refresh();
}
}}
>
<input
value={roomName}
onChange={(event) => setRoomName(event.target.value)}
placeholder={t('Room name')}
maxLength={48}
/>
<button className="btn btn-accent" disabled={busy || !roomName.trim()}>
<PlusIcon /> {t('Create room')}
</button>
</form>
</div>
<div className="listening-room-grid">
<div className="card room-directory">
<div className="card-head">
<h2>{t('Live rooms')}</h2>
<button className="icon-btn" onClick={refresh} title={t('Refresh rooms')}>
<RefreshIcon />
</button>
</div>
{rooms.length === 0 ? (
<EmptyRow text={t('No listening rooms yet')} />
) : (
<div className="listening-room-list">
{rooms.map((room) => {
const selected = room.name === currentRoom;
return (
<button
key={room.name}
className={'listening-room-card' + (selected ? ' active' : '')}
disabled={busy}
onClick={() => !selected && action('JoinListeningRoom', room.name)}
>
<span className={'room-signal' + (room.isPlaying ? ' playing' : '')} />
<span className="room-card-copy">
<strong>{room.name}</strong>
<small>
{tf('{0} listeners · {1} queued', room.members.length, room.queueSize)}
</small>
</span>
<span className="room-state">
{selected ? t('JOINED') : room.isPaused ? t('PAUSED') : room.isPlaying ? t('LIVE') : t('IDLE')}
</span>
</button>
);
})}
</div>
)}
</div>
<div className="card room-console">
{!current ? (
<div className="room-console-empty">
<span className="room-console-glyph">04</span>
<h2>{t('Choose a room')}</h2>
<p>{t('Your TeamSpeak audio follows the room you join.')}</p>
</div>
) : (
<>
<div className="room-console-head">
<div>
<span className="rooms-kicker">{t('NOW TUNED')}</span>
<h2>{current.name}</h2>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={() => action('LeaveListeningRoom')} disabled={busy}>
{t('Leave')}
</button>
{current.isOwner && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (!(await confirmDialog({ title: t('Delete room'), message: tf('Delete “{0}” for everyone?', current.name), confirmLabel: t('Delete'), danger: true }))) return;
const result = await safeCall('DeleteListeningRoom', { room: current.name });
if (result) await refresh();
}}
>
<CloseIcon /> {t('Delete')}
</button>
)}
</div>
</div>
<div className="room-transport">
<button className="ctrl" title={t('Stop')} onClick={() => action('StopListeningRoom', current.name)}><span className="stop-square" /></button>
<button
className="ctrl ctrl-main"
title={current.isPlaying && !current.isPaused ? t('Pause') : t('Resume')}
onClick={() => action(current.isPlaying && !current.isPaused ? 'PauseListeningRoom' : 'ResumeListeningRoom', current.name)}
>
{current.isPlaying && !current.isPaused ? <PauseIcon /> : <PlayIcon />}
</button>
<button className="ctrl" title={t('Skip')} onClick={() => action('SkipListeningRoom', current.name)}><SkipNextIcon /></button>
<div className="room-transport-copy">
<strong>{current.isPlaying ? (current.isPaused ? t('Paused') : t('Streaming now')) : t('Ready')}</strong>
<small>{tf('{0} people are tuned in', current.members.length)}</small>
</div>
</div>
<form
className="room-play-form"
onSubmit={async (event) => {
event.preventDefault();
const value = query.trim();
if (!value) return;
const result = await safeCall<{ message?: string }>('PlayInListeningRoom', { room: current.name, query: value });
if (result) { setQuery(''); toast(result.message || t('Added to room queue')); await refresh(); }
}}
>
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t('Paste a URL or search for a track…')} />
<button className="btn btn-accent" disabled={!query.trim()}><PlusIcon /> {t('Add')}</button>
</form>
<div className="room-queue-head">
<h3>{t('Room queue')}</h3>
<div className="row-gap">
<span>{tf('{0} tracks', queue.length)}</span>
{!!queue.length && <button className="btn btn-danger-ghost" onClick={() => action('ClearListeningRoomQueue', current.name)}>{t('Clear')}</button>}
</div>
</div>
<div className="tracklist room-tracklist">
{queue.length ? queue.map((entry, index) => (
<TrackRow key={entry.queueId} track={entry.track} num={index + 1} playing={entry.isPlaying} actions={[
index > 0 && { icon: <ArrowUpIcon />, title: t('Move up'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index - 1 }); await refresh(); } },
index + 1 < queue.length && { icon: <ArrowDownIcon />, title: t('Move down'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index + 1 }); await refresh(); } },
{ icon: <CloseIcon />, title: t('Remove'), cls: 'danger', onClick: async () => { await safeCall('RemoveFromListeningRoomQueue', { room: current.name, queueId: entry.queueId }); await refresh(); } },
]} />
)) : <EmptyRow text={t('This room queue is empty')} />}
</div>
</>
)}
</div>
</div>
</section>
);
}
+22 -3
View File
@@ -14,9 +14,14 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
- ⭐ **History & Favorites** - `!history`, `!stats`, `!fav add|list|play` backed by SQLite
- 📋 **Playlist Support** - Queue management with shuffle, repeat, and skip functionality
- 🎧 **High Quality Audio** - 192kHz stereo internal pipeline
- 🔄 **Hot Reload** - Update the bot without disconnecting from the server
- 🎚️ **Named Listening Rooms** - Independent queues and playback engines can
whisper different music to different user groups simultaneously
- 🔄 **Transactional Updates** - Validate a complete daemon/Core/protocol
release, checkpoint every room, re-exec, reconnect, and restore playback
- ⚙️ **Configurable** - JSON-based configuration system
- 🔊 **TeamSpeak Native** - Uses TeamSpeak's native audio system for best quality
- 🧩 **VoidTeamspeak SDK** - Native protocol support is an independently
consumable modern C++ library rather than an Echoion-internal component
## Building
@@ -124,7 +129,7 @@ The supported runtime consists of four main components:
1. **EchoionApi** - Shared interfaces and types
2. **EchoionCore** - Core music playback logic (hot-reloadable)
3. **EchoionProtocol** - Native TeamSpeak UDP voice and command protocol
3. **VoidTeamspeak** - Reusable native TeamSpeak SDK-compatible client library
4. **EchoionStandalone** - Daemon host and Core API adapter
`EchoionPlugin` is archived compatibility code. It is excluded from normal
@@ -136,7 +141,7 @@ TeamSpeak client integration.
```
query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → PlaybackEngine
(dual AudioDecoder, gapless handoff) → Core → Standalone interface
→ EchoionProtocol → TeamSpeak
→ VoidTeamspeak → TeamSpeak
```
Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to
@@ -152,6 +157,20 @@ 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:
```bash
scripts/stage-release.sh "$HOME/echoion/releases" 1.2.3 \
build/bin/echoiond build/lib/Echoion.ts
```
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 and room state, disconnects cleanly, and
re-execs the staged binary.
### Adding Commands
To add a new command:
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 4 || $# -gt 5 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION ECHOIOND ECHOION_CORE [MANIFEST]" >&2
exit 2
fi
release_root=$1
version=$2
executable=$3
core=$4
manifest=${5:-"$release_root/pending-release.json"}
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
exit 2
fi
if [[ ! -f $core ]]; then
echo "Core library is missing: $core" >&2
exit 2
fi
mkdir -p "$release_root" "$(dirname "$manifest")"
staging="$release_root/.staging-$version-$$"
destination="$release_root/$version"
trap 'rm -rf -- "$staging"' EXIT
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"
executable_hash=$(sha256sum "$staging/echoiond" | cut -d' ' -f1)
core_hash=$(sha256sum "$staging/Echoion.ts" | cut -d' ' -f1)
mv "$staging" "$destination"
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"
trap - EXIT
echo "staged release $version"
echo "manifest: $manifest"
+2
View File
@@ -22,6 +22,8 @@ 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
+9
View File
@@ -0,0 +1,9 @@
{
"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"
}
}