diff --git a/CMakeLists.txt b/CMakeLists.txt index 0089cdb..221ccb7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/EchoionApi b/EchoionApi index e7573fb..295542a 160000 --- a/EchoionApi +++ b/EchoionApi @@ -1 +1 @@ -Subproject commit e7573fbcd0b4778c347e6af865057200e35d3a64 +Subproject commit 295542ab9e80c609de3babdc2540025ae094d8bb diff --git a/EchoionCore b/EchoionCore index 5c036d9..01362d2 160000 --- a/EchoionCore +++ b/EchoionCore @@ -1 +1 @@ -Subproject commit 5c036d91fb4666ba072137e839c448b03892270d +Subproject commit 01362d2e513bdbdb993a0ec5701ebc1fdc1ffb8c diff --git a/EchoionHost/CMakeLists.txt b/EchoionHost/CMakeLists.txt index 2ef59d0..6388601 100644 --- a/EchoionHost/CMakeLists.txt +++ b/EchoionHost/CMakeLists.txt @@ -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 ) diff --git a/EchoionHost/include/echoion/host/CoreLoader.hpp b/EchoionHost/include/echoion/host/CoreLoader.hpp index e9c634a..3946d94 100644 --- a/EchoionHost/include/echoion/host/CoreLoader.hpp +++ b/EchoionHost/include/echoion/host/CoreLoader.hpp @@ -1,11 +1,11 @@ #pragma once -#include "echoion/host/FileWatcher.hpp" +#include +#include #include #include #include #include #include -#include #include #include #include @@ -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 + checkpoint(const std::filesystem::path& destination); + Api::Result + 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; + using HotReloadPrepareCallback = std::function; + 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 loadLibraryInternal(const std::filesystem::path& path); Api::Result unloadLibraryInternal(); - [[nodiscard]] Api::SerializedState saveStateInternal(); - [[nodiscard]] Api::Result - restoreStateInternal(const Api::SerializedState& state); - [[nodiscard]] std::filesystem::path - getTempLibraryPath(const std::filesystem::path& original) const; - void cleanupTempFiles(); + [[nodiscard]] Api::Result refreshCoreHandle(); - std::unique_ptr 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 loaded_{false}; std::atomic hotReloading_{false}; // Auto reload - FileWatcher fileWatcher_; + Void::FileSystem::FileWatcher fileWatcher_; std::atomic 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(); diff --git a/EchoionHost/include/echoion/host/FileWatcher.hpp b/EchoionHost/include/echoion/host/FileWatcher.hpp deleted file mode 100644 index a3e1af7..0000000 --- a/EchoionHost/include/echoion/host/FileWatcher.hpp +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -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; - - 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 watching_{false}; - std::atomic 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 diff --git a/EchoionHost/src/CoreLoader.cpp b/EchoionHost/src/CoreLoader.cpp index b11f578..85c5b35 100644 --- a/EchoionHost/src/CoreLoader.cpp +++ b/EchoionHost/src/CoreLoader.cpp @@ -1,5 +1,6 @@ #include -#include "dylib.hpp" +#include +#include #include "echoion/host/CoreLoader.hpp" #include #include @@ -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(&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 CoreLoader::load(const std::filesystem::path& libraryPath) { - std::lock_guard lock(mutex_); + std::unique_lock 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 lock(mutex_); - auto result = unloadLibraryInternal(); - - if (!tempLibraryPath_.empty()) { - std::error_code ec; - std::filesystem::remove(tempLibraryPath_, ec); - } - - return result; + return unloadLibraryInternal(); } Api::Result - CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) + CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { - std::lock_guard lock(mutex_); + std::unique_lock 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 + CoreLoader::checkpoint(const std::filesystem::path& destination) + { + std::lock_guard 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((value >> shift) & 0xffU)); + } + }; + appendU32(state.version); + appendU32(static_cast(state.timestamp.size())); + bytes.append(state.timestamp); + bytes.append(reinterpret_cast(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 + CoreLoader::restoreCheckpoint(const std::filesystem::path& source) + { + std::lock_guard 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((*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(dataOffset), contents->end()); + return core_->restoreState(state); + } + Api::Result 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( - path.string(), dylib::decorations::none()); - - auto createFunc = - library_->get_function("CreateCore"); - auto versionFunc = - library_->get_function("GetApiVersion"); - auto compatibleFunc = - library_->get_function( - "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 CoreLoader::refreshCoreHandle() + { + auto pin = std::make_shared( + pluginManager_.acquire(pluginName_)); + if (!*pin) { + return Api::fail(Api::ErrorCode::PluginError, + "Core plugin disappeared from the registry"); + } + auto* interface = dynamic_cast(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 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( - 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::this_thread::get_id())); -#else - auto tempName = std::format( - "echoion_{}_{}.ts", ms, - std::hash{}(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 diff --git a/EchoionHost/src/FileWatcher.cpp b/EchoionHost/src/FileWatcher.cpp deleted file mode 100644 index 2c92ace..0000000 --- a/EchoionHost/src/FileWatcher.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include "echoion/host/FileWatcher.hpp" -#include -#include -#include - -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 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 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 diff --git a/EchoionProtocol/CMakeLists.txt b/EchoionProtocol/CMakeLists.txt deleted file mode 100644 index a8579cf..0000000 --- a/EchoionProtocol/CMakeLists.txt +++ /dev/null @@ -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() diff --git a/EchoionProtocol/README.md b/EchoionProtocol/README.md deleted file mode 100644 index f6a6fda..0000000 --- a/EchoionProtocol/README.md +++ /dev/null @@ -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. diff --git a/EchoionProtocol/include/echoion/protocol/Command.hpp b/EchoionProtocol/include/echoion/protocol/Command.hpp deleted file mode 100644 index 9238eba..0000000 --- a/EchoionProtocol/include/echoion/protocol/Command.hpp +++ /dev/null @@ -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 -#include -#include - -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; - - struct ParsedCommand { - std::string name; - CommandParams params; // first group - std::vector 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 diff --git a/EchoionProtocol/include/echoion/protocol/Crypto.hpp b/EchoionProtocol/include/echoion/protocol/Crypto.hpp deleted file mode 100644 index c399691..0000000 --- a/EchoionProtocol/include/echoion/protocol/Crypto.hpp +++ /dev/null @@ -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 -#include -#include -#include -#include -#include - -namespace Echoion::Protocol::Crypto -{ - - using Bytes = std::vector; - using ByteView = std::span; - - 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 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 DUMMY_KEY = { - 'c', ':', '\\', 'w', 'i', 'n', 'd', 'o', - 'w', 's', '\\', 's', 'y', 's', 't', 'e'}; - inline constexpr std::array 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 sha1(ByteView data); - std::array sha256(ByteView data); - std::array 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 a, ByteView b, size_t len); - - // --- AES-128-CMAC (OMAC1) ---------------------------------------------- - // 16-byte MAC over `data` under the 16-byte `key`. - std::array cmac(ByteView key, ByteView data); - - // --- AES-128-EAX -------------------------------------------------------- - struct EaxResult { - Bytes ciphertext; - std::array 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 eaxDecrypt(ByteView key, ByteView nonce, - ByteView header, ByteView ciphertext, - ByteView mac); - - // --- Per-packet key/nonce derivation ----------------------------------- - struct KeyNonce { - std::array key; - std::array 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 diff --git a/EchoionProtocol/include/echoion/protocol/Identity.hpp b/EchoionProtocol/include/echoion/protocol/Identity.hpp deleted file mode 100644 index 3d20cad..0000000 --- a/EchoionProtocol/include/echoion/protocol/Identity.hpp +++ /dev/null @@ -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 -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - - class Identity - { - public: - - using Bytes = std::vector; - using ByteView = std::span; - - // 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 "V" 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 pkey_; - std::string publicKeyString_; - std::string uid_; - uint64_t keyOffset_ = 0; - }; - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/License.hpp b/EchoionProtocol/include/echoion/protocol/License.hpp deleted file mode 100644 index 4891655..0000000 --- a/EchoionProtocol/include/echoion/protocol/License.hpp +++ /dev/null @@ -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 -#include -#include -#include - -namespace Echoion::Protocol -{ - - using Bytes = std::vector; - using ByteView = std::span; - - struct LicenseBlock { - std::array key; - std::array hash; // first 32 bytes of SHA-512(content) - uint8_t type = 0; - }; - - struct TempKey { - std::array publicKey; - std::array privateKey; - }; - - // Parse the server license blob into its chain of blocks. - std::vector parseLicense(ByteView data); - - // Walk the chain from the root key to the final server public key (32 bytes). - std::array - deriveLicenseKey(const std::vector& 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 - getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey); - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/QuickLz.hpp b/EchoionProtocol/include/echoion/protocol/QuickLz.hpp deleted file mode 100644 index dda4429..0000000 --- a/EchoionProtocol/include/echoion/protocol/QuickLz.hpp +++ /dev/null @@ -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 -#include -#include - -namespace Echoion::Protocol -{ - - using Bytes = std::vector; - using ByteView = std::span; - - 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 diff --git a/EchoionProtocol/include/echoion/protocol/TsClient.hpp b/EchoionProtocol/include/echoion/protocol/TsClient.hpp deleted file mode 100644 index 444c66c..0000000 --- a/EchoionProtocol/include/echoion/protocol/TsClient.hpp +++ /dev/null @@ -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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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 onConnected; - std::function onDisconnected; - std::function onError; - std::function onCommand; - std::function onTextMessage; - std::function)> onVoice; - std::function onDebug; - }; - - struct CommandResult { - std::vector 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 opus); - // Whisper the frame to the given channel/client targets. - void sendWhisper(std::span opus, - const std::vector& channelIds, - const std::vector& 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 raw); - void sendOutgoing(std::span data, PacketType type, - uint8_t extraFlags = 0); - std::vector buildRawPacket(std::span data, - PacketType type, - uint16_t packetId, - uint8_t flags); - void encryptPacket(std::vector& raw, PacketType type, - uint16_t packetId, uint32_t gen, uint8_t flags, - std::span data); - std::vector decryptPacket(std::span raw, - PacketType type, - uint16_t packetId, uint32_t gen, - uint8_t flags, bool& ok); - void sendRawLocked(const std::vector& raw); - void sendInitPacket(const std::vector& data); - - // ---- handshake / commands ---- - std::vector buildInit0(); - void handleInit(std::span data); - void handleCommandData(std::span data, uint8_t flags); - void processCommand(std::span 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 state_{ClientState::Disconnected}; - std::atomic clientId_{0}; - - std::thread thread_; - std::atomic 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 packetCounter_{}; - std::array generationCounter_{}; - - bool cryptoInitComplete_ = false; - std::vector ivStruct_; - std::array fakeSignature_{}; - std::vector alphaTmp_; - - // resend tracking - struct Resend { - std::vector raw; - uint16_t packetId = 0; - int64_t firstSend = 0; - int64_t lastSend = 0; - }; - std::map resendMap_; - std::unique_ptr initResend_; - int64_t lastMessageTime_ = 0; - int64_t lastPing_ = 0; - int64_t connectStart_ = 0; - - // fragment reassembly - std::vector fragmentBuffer_; - bool fragmenting_ = false; - uint8_t fragmentFlags_ = 0; - - // channel map for auto-move - std::map channelMap_; - - struct PendingRequest { - CommandResult result; - std::string returnCode; - bool completed = false; - std::condition_variable cv; - }; - std::mutex requestSerialMutex_; - std::mutex pendingMutex_; - std::deque> pendingRequests_; - std::atomic requestId_{0}; - std::atomic transferId_{0}; - }; - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/Util.hpp b/EchoionProtocol/include/echoion/protocol/Util.hpp deleted file mode 100644 index 7a6125f..0000000 --- a/EchoionProtocol/include/echoion/protocol/Util.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -// Small dependency-free encoding helpers shared across the protocol modules. - -#include -#include -#include -#include - -namespace Echoion::Protocol::Util -{ - - using Bytes = std::vector; - using ByteView = std::span; - - // 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 diff --git a/EchoionProtocol/src/Command.cpp b/EchoionProtocol/src/Command.cpp deleted file mode 100644 index 6b77518..0000000 --- a/EchoionProtocol/src/Command.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#include "echoion/protocol/Command.hpp" - -#include -#include - -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 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 diff --git a/EchoionProtocol/src/Crypto.cpp b/EchoionProtocol/src/Crypto.cpp deleted file mode 100644 index ae44a8f..0000000 --- a/EchoionProtocol/src/Crypto.cpp +++ /dev/null @@ -1,253 +0,0 @@ -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include - -#include -#include - -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 aesEncryptBlock( - ByteView key, std::span block) - { - EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); - if (!ctx) { - throw std::runtime_error("EVP_CIPHER_CTX_new failed"); - } - std::array 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(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 doubleBlock( - const std::array& buf) - { - std::array out{}; - uint8_t carry = 0; - for (int i = BLOCK_SIZE - 1; i >= 0; --i) { - uint16_t tmp = static_cast((buf[i] << 1) | carry); - out[i] = static_cast(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 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 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(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(total) + len); - return out; - } - } // namespace - - std::array sha1(ByteView data) - { - std::array out{}; - ::SHA1(data.data(), data.size(), out.data()); - return out; - } - - std::array sha256(ByteView data) - { - std::array out{}; - ::SHA256(data.data(), data.size(), out.data()); - return out; - } - - std::array sha512(ByteView data) - { - std::array 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 a, ByteView b, size_t len) - { - for (size_t i = 0; i < len; ++i) { - a[i] ^= b[i]; - } - } - - std::array cmac(ByteView key, ByteView data) - { - const std::array zero{}; - auto L = aesEncryptBlock(key, std::span( - 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 x{}; - for (size_t i = 0; i + 1 < numBlocks; ++i) { - std::array 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( - block.data(), BLOCK_SIZE)); - } - - std::array 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( - 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(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 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 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(tag[i] ^ (i < mac.size() ? mac[i] : 0)); - } - if (diff != 0 || mac.size() < MAC_LEN) { - return std::nullopt; - } - return aesCtr(key, - std::span(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((generationId >> 24) & 0xff); - tmp[3] = static_cast((generationId >> 16) & 0xff); - tmp[4] = static_cast((generationId >> 8) & 0xff); - tmp[5] = static_cast(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((packetId >> 8) & 0xff); - out.key[1] ^= static_cast(packetId & 0xff); - return out; - } - - std::string hashPassword(const std::string& password) - { - if (password.empty()) { - return ""; - } - auto digest = sha1(ByteView( - reinterpret_cast(password.data()), password.size())); - return Util::base64Encode(ByteView(digest.data(), digest.size())); - } - -} // namespace Echoion::Protocol::Crypto diff --git a/EchoionProtocol/src/Identity.cpp b/EchoionProtocol/src/Identity.cpp deleted file mode 100644 index 899a69c..0000000 --- a/EchoionProtocol/src/Identity.cpp +++ /dev/null @@ -1,675 +0,0 @@ -#include "echoion/protocol/Identity.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - using Bytes = std::vector; - - [[noreturn]] void fail(const char* what) - { - throw std::runtime_error(std::string("Identity: ") + what); - } - - EVP_PKEY* asPkey(const std::shared_ptr& p) - { - return static_cast(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(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 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(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 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(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(len)}; - } - if (len < 0x100) { - return {0x81, static_cast(len)}; - } - return {0x82, static_cast((len >> 8) & 0xff), - static_cast(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(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 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(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(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(input)), - std::istreambuf_iterator()); - // TeamSpeak's exported value is V. 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(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(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(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(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("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(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(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(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(in)), - std::istreambuf_iterator()); - - BIO* mem = BIO_new_mem_buf(pem.data(), static_cast(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(pkey, PKeyDeleter{}); - - auto uidHash = Crypto::sha1(Crypto::ByteView( - reinterpret_cast(id.publicKeyString_.data()), - id.publicKeyString_.size())); - id.uid_ = Util::base64Encode( - Crypto::ByteView(uidHash.data(), uidHash.size())); - return id; - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/License.cpp b/EchoionProtocol/src/License.cpp deleted file mode 100644 index 735237a..0000000 --- a/EchoionProtocol/src/License.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "echoion/protocol/License.hpp" -#include "echoion/protocol/Crypto.hpp" - -#include - -#include -#include -#include - -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 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 parseLicense(ByteView data) - { - if (data.size() < 1) { - fail("license too short"); - } - if (data[0] != 1) { - fail("unsupported license version"); - } - - std::vector 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 - deriveLicenseKey(const std::vector& blocks) - { - ensureSodium(); - std::array parentKey = LICENSE_ROOT_KEY; - - for (const auto& block : blocks) { - // Clamp the block hash into an Ed25519 scalar. - std::array scalar = block.hash; - scalar[0] &= 0xf8; - scalar[31] &= 0x3f; - scalar[31] |= 0x40; - - std::array mul{}; - if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(), - block.key.data()) != 0) { - fail("ed25519 scalarmult failed"); - } - std::array 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 getSharedSecret2(ByteView serverDerivedKey, - ByteView tempPrivateKey) - { - ensureSodium(); - if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) { - fail("bad key length for shared secret"); - } - std::array priv{}; - std::memcpy(priv.data(), tempPrivateKey.data(), 32); - priv[31] &= 0x7f; - - std::array 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 diff --git a/EchoionProtocol/src/QuickLz.cpp b/EchoionProtocol/src/QuickLz.cpp deleted file mode 100644 index ceedc9f..0000000 --- a/EchoionProtocol/src/QuickLz.cpp +++ /dev/null @@ -1,158 +0,0 @@ -#include "echoion/protocol/QuickLz.hpp" - -#include -#include - -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(b[off]) | - (static_cast(b[off + 1]) << 8) | - (static_cast(b[off + 2]) << 16) | - (static_cast(b[off + 3]) << 24); - } - - int32_t readI32LE(ByteView b, size_t off) - { - return static_cast(readU32LE(b, off)); - } - - uint32_t read24(const Bytes& b, size_t off) - { - return static_cast(b[off]) | - (static_cast(b[off + 1]) << 8) | - (static_cast(b[off + 2]) << 16); - } - - int hashVal(uint32_t value) - { - return static_cast(((value >> 12) ^ value) & 0xfff); - } - } // namespace - - uint32_t qlzDecompressedSize(ByteView data) - { - return (data[0] & 0x02) != 0 - ? static_cast(readI32LE(data, 5)) - : data[2]; - } - - uint32_t qlzCompressedSize(ByteView data) - { - return (data[0] & 0x02) != 0 - ? static_cast(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 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(nextHashed); - for (size_t i = nextHashed + 1; i < end; ++i) { - nxt = (nxt >> 8) | - (static_cast(dest[i + 2]) << 16); - hashtable[hashVal(nxt)] = static_cast(i); - } - } - nextHashed = destPos; - } else if (destPos >= - std::max(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(nextHashed); - for (size_t i = nextHashed + 1; i < end; ++i) { - nxt = (nxt >> 8) | - (static_cast(dest[i + 2]) << 16); - hashtable[hashVal(nxt)] = static_cast(i); - } - } - nextHashed = std::max(nextHashed, end); - } - } - - return dest; - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/TsClient.cpp b/EchoionProtocol/src/TsClient.cpp deleted file mode 100644 index 23cfe0b..0000000 --- a/EchoionProtocol/src/TsClient.cpp +++ /dev/null @@ -1,1214 +0,0 @@ -#include "echoion/protocol/TsClient.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/License.hpp" -#include "echoion/protocol/QuickLz.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - constexpr uint8_t FLAG_FRAGMENTED = 0x10; - constexpr uint8_t FLAG_NEWPROTOCOL = 0x20; - constexpr uint8_t FLAG_COMPRESSED = 0x40; - constexpr uint8_t FLAG_UNENCRYPTED = 0x80; - - constexpr size_t MAC_LEN = 8; - constexpr size_t C2S_HEADER_LEN = 5; // PId(2) + CId(2) + PT(1) - constexpr size_t S2C_HEADER_LEN = 3; // PId(2) + PT(1) - constexpr size_t MAX_PACKET_SIZE = 500; - constexpr size_t MAX_OUT_CONTENT = - MAX_PACKET_SIZE - MAC_LEN - C2S_HEADER_LEN; - - constexpr const char* VS_PLATFORM = "Linux"; - constexpr const char* VS_VERSION = "3.?.? [Build: 5680278000]"; - constexpr const char* VS_SIGN = - "Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2" - "gSwRuZi0R+8Laan5ts5CQ=="; - - int64_t nowMs() - { - return std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - } - - void putU16BE(std::vector& b, size_t off, uint16_t v) - { - b[off] = static_cast((v >> 8) & 0xff); - b[off + 1] = static_cast(v & 0xff); - } - uint16_t getU16BE(std::span b, size_t off) - { - return static_cast((b[off] << 8) | b[off + 1]); - } - - // y = x^(2^level) mod n, all big-endian 64-byte. - std::vector rsaPuzzle(std::span x, - std::span n, int32_t level) - { - BN_CTX* ctx = BN_CTX_new(); - BIGNUM* bx = BN_bin2bn(x.data(), static_cast(x.size()), - nullptr); - BIGNUM* bn = BN_bin2bn(n.data(), static_cast(n.size()), - nullptr); - BIGNUM* exp = BN_new(); - BIGNUM* one = BN_new(); - BN_one(one); - BN_lshift(exp, one, level); // 2^level - BIGNUM* y = BN_new(); - BN_mod_exp(y, bx, exp, bn, ctx); - std::vector out(64, 0); - BN_bn2binpad(y, out.data(), 64); - BN_free(y); - BN_free(exp); - BN_free(one); - BN_free(bn); - BN_free(bx); - BN_CTX_free(ctx); - return out; - } - } // namespace - - TsClient::TsClient() = default; - - TsClient::~TsClient() - { - forceClose(); - if (thread_.joinable()) { - thread_.join(); - } - } - - void TsClient::debug(const std::string& msg) - { - if (cb_.onDebug) { - cb_.onDebug(msg); - } - } - - TsClient::Counter TsClient::getCounter(PacketType type) - { - if (type == PacketType::Init1) { - return {101, 0}; - } - auto i = static_cast(type); - return {packetCounter_[i], generationCounter_[i]}; - } - - void TsClient::incCounter(PacketType type) - { - if (type == PacketType::Init1) { - return; - } - auto i = static_cast(type); - if (++packetCounter_[i] == 0) { - ++generationCounter_[i]; - } - } - - void TsClient::connect(const TsClientOptions& opts) - { - if (thread_.joinable()) { - forceClose(); - thread_.join(); - } - std::lock_guard lock(mu_); - if (!opts.identity) { - throw std::runtime_error("TsClient: identity is required"); - } - opts_ = opts; - - // Resolve host and open a connected UDP socket. - addrinfo hints{}; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_DGRAM; - hints.ai_protocol = IPPROTO_UDP; - addrinfo* res = nullptr; - std::string portStr = std::to_string(opts.port); - if (getaddrinfo(opts.host.c_str(), portStr.c_str(), &hints, &res) != 0 || - !res) { - throw std::runtime_error("TsClient: cannot resolve host " + - opts.host); - } - sock_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (sock_ < 0) { - freeaddrinfo(res); - throw std::runtime_error("TsClient: socket() failed"); - } - if (::connect(sock_, res->ai_addr, res->ai_addrlen) != 0) { - freeaddrinfo(res); - ::close(sock_); - sock_ = -1; - throw std::runtime_error("TsClient: connect() failed"); - } - freeaddrinfo(res); - - // Reset all per-connection state. - state_ = ClientState::Init; - clientId_ = 0; - cryptoInitComplete_ = false; - ivStruct_.clear(); - fakeSignature_.fill(0); - alphaTmp_.clear(); - packetCounter_.fill(0); - generationCounter_.fill(0); - resendMap_.clear(); - initResend_.reset(); - fragmentBuffer_.clear(); - fragmenting_ = false; - fragmentFlags_ = 0; - channelMap_.clear(); - disconnectDeadline_ = 0; - lastMessageTime_ = nowMs(); - lastPing_ = nowMs(); - connectStart_ = nowMs(); - - // Reserve command counter (old clientinitiv behaviour), then Init0. - incCounter(PacketType::Command); - sendInitPacket(buildInit0()); - - running_ = true; - thread_ = std::thread([this] { loopThread(); }); - } - - void TsClient::loopThread() - { - while (running_.load()) { - pollfd pfd{}; - pfd.fd = sock_; - pfd.events = POLLIN; - int rc = ::poll(&pfd, 1, 100); - if (!running_.load()) { - break; - } - std::lock_guard lock(mu_); - if (rc > 0 && (pfd.revents & POLLIN)) { - uint8_t buf[2048]; - ssize_t n = ::recv(sock_, buf, sizeof(buf), 0); - if (n > 0) { - handleIncomingPacket( - std::span(buf, static_cast(n))); - } - } - resendTick(); - } - std::lock_guard lock(mu_); - if (sock_ >= 0) { - ::close(sock_); - sock_ = -1; - } - } - - // ---- Outgoing ---------------------------------------------------------- - - std::vector TsClient::buildInit0() - { - std::vector buf(4 + 1 + 4 + 4 + 8, 0); - putU16BE(buf, 0, static_cast((Crypto::INIT_VERSION >> 16))); - putU16BE(buf, 2, static_cast(Crypto::INIT_VERSION & 0xffff)); - buf[4] = 0x00; // step 0 - uint32_t ts = static_cast( - std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count()); - buf[5] = (ts >> 24) & 0xff; - buf[6] = (ts >> 16) & 0xff; - buf[7] = (ts >> 8) & 0xff; - buf[8] = ts & 0xff; - RAND_bytes(buf.data() + 9, 4); - return buf; - } - - void TsClient::sendInitPacket(const std::vector& data) - { - auto raw = buildRawPacket(data, PacketType::Init1, 101, - FLAG_UNENCRYPTED); - std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN); - initResend_ = std::make_unique( - Resend{raw, 101, nowMs(), nowMs()}); - sendRawLocked(raw); - } - - std::vector TsClient::buildRawPacket(std::span data, - PacketType type, - uint16_t packetId, - uint8_t flags) - { - std::vector raw(MAC_LEN + C2S_HEADER_LEN + data.size(), 0); - putU16BE(raw, MAC_LEN, packetId); - putU16BE(raw, MAC_LEN + 2, clientId_.load()); - raw[MAC_LEN + 4] = - static_cast((flags & 0xf0) | - (static_cast(type) & 0x0f)); - std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(), - data.size()); - return raw; - } - - void TsClient::encryptPacket(std::vector& raw, PacketType type, - uint16_t packetId, uint32_t gen, uint8_t flags, - std::span data) - { - if (type == PacketType::Init1) { - std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN); - return; - } - if (flags & FLAG_UNENCRYPTED) { - std::memcpy(raw.data(), fakeSignature_.data(), MAC_LEN); - return; - } - - Crypto::KeyNonce kn; - if (!cryptoInitComplete_ || ivStruct_.empty()) { - std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16); - std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16); - } else { - kn = Crypto::deriveKeyNonce( - false, packetId, gen, static_cast(type), - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - } - - Crypto::ByteView header(raw.data() + MAC_LEN, C2S_HEADER_LEN); - auto enc = Crypto::eaxEncrypt( - Crypto::ByteView(kn.key.data(), 16), - Crypto::ByteView(kn.nonce.data(), 16), header, data); - std::memcpy(raw.data(), enc.mac.data(), MAC_LEN); - std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, enc.ciphertext.data(), - enc.ciphertext.size()); - } - - void TsClient::sendOutgoing(std::span dataIn, PacketType type, - uint8_t extraFlags) - { - auto ctr = getCounter(type); - incCounter(type); - - std::vector data(dataIn.begin(), dataIn.end()); - uint8_t flags = extraFlags; - switch (type) { - case PacketType::Voice: - case PacketType::VoiceWhisper: - if (data.size() >= 2) { - putU16BE(data, 0, ctr.id); - } - break; - case PacketType::Command: - case PacketType::CommandLow: - flags |= FLAG_NEWPROTOCOL; - break; - case PacketType::Ping: - case PacketType::Pong: - flags |= FLAG_UNENCRYPTED; - break; - default: - break; - } - - auto raw = buildRawPacket(data, type, ctr.id, flags); - encryptPacket(raw, type, ctr.id, ctr.gen, flags, data); - - if (type == PacketType::Command || type == PacketType::CommandLow) { - resendMap_[ctr.id] = Resend{raw, ctr.id, nowMs(), nowMs()}; - } - sendRawLocked(raw); - } - - void TsClient::sendRawLocked(const std::vector& raw) - { - if (sock_ < 0) { - return; - } - ::send(sock_, raw.data(), raw.size(), 0); - } - - void TsClient::sendCommand(const std::string& cmd) - { - std::lock_guard lock(mu_); - std::span data( - reinterpret_cast(cmd.data()), cmd.size()); - if (data.size() <= MAX_OUT_CONTENT) { - sendOutgoing(data, PacketType::Command); - return; - } - // Fragment: FLAG_FRAGMENTED on first and last fragment only. - size_t total = data.size(); - size_t count = (total + MAX_OUT_CONTENT - 1) / MAX_OUT_CONTENT; - for (size_t i = 0, idx = 0; i < total; i += MAX_OUT_CONTENT, ++idx) { - size_t len = std::min(MAX_OUT_CONTENT, total - i); - bool first = idx == 0; - bool last = idx == count - 1; - uint8_t extra = (first || last) ? FLAG_FRAGMENTED : 0; - sendOutgoing(data.subspan(i, len), PacketType::Command, extra); - } - } - - CommandResult TsClient::requestCommand( - const std::string& cmd, std::chrono::milliseconds timeout) - { - if (std::this_thread::get_id() == thread_.get_id()) { - return {{}, -1, "requestCommand cannot block the receive thread"}; - } - // TeamSpeak returns data records without a request identifier; keep one - // response-bearing command in flight so those records remain unambiguous. - std::unique_lock serialLock(requestSerialMutex_); - auto pending = std::make_shared(); - pending->returnCode = "echoion-" + std::to_string(++requestId_); - { - // Keep queue insertion and wire send in the same order when callers - // issue requests concurrently. - std::lock_guard sendLock(mu_); - if (state_.load() != ClientState::Connected) { - return {{}, -1, "client is not connected"}; - } - { - std::lock_guard pendingLock(pendingMutex_); - pendingRequests_.push_back(pending); - } - sendCommand(cmd + " return_code=" + pending->returnCode); - } - - std::unique_lock lock(pendingMutex_); - if (!pending->cv.wait_for(lock, timeout, - [&pending] { return pending->completed; })) { - const auto entry = - std::find(pendingRequests_.begin(), pendingRequests_.end(), pending); - if (entry != pendingRequests_.end()) { - pendingRequests_.erase(entry); - } - return {{}, -1, "command timed out"}; - } - return pending->result; - } - - CommandResult TsClient::downloadFile( - const std::string& remotePath, const std::string& destination, - uint64_t channelId, const std::string& channelPassword, - std::chrono::milliseconds timeout) - { - CommandParams parameters; - parameters["cid"] = std::to_string(channelId); - parameters["cpw"] = channelPassword; - parameters["name"] = remotePath; - parameters["clientftfid"] = std::to_string(++transferId_); - parameters["seekpos"] = "0"; - auto result = requestCommand(buildCommand("ftinitdownload", parameters), - timeout); - if (!result.ok() || result.records.empty()) { - if (result.ok()) { - result.errorId = -1; - result.errorMessage = "file transfer returned no connection data"; - } - return result; - } - const auto& record = result.records.front(); - auto value = [&record](const char* name) -> std::string { - const auto entry = record.find(name); - return entry == record.end() ? std::string{} : entry->second; - }; - const auto transferKey = value("ftkey"); - const auto portText = value("port"); - const auto sizeText = value("size"); - if (transferKey.empty() || portText.empty() || sizeText.empty()) { - return {{}, -1, "file transfer response is incomplete"}; - } - - addrinfo hints{}; - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - addrinfo* addresses = nullptr; - if (getaddrinfo(opts_.host.c_str(), portText.c_str(), &hints, - &addresses) != 0 || !addresses) { - return {{}, -1, "cannot resolve file-transfer endpoint"}; - } - int transferSocket = -1; - for (auto* address = addresses; address; address = address->ai_next) { - transferSocket = - ::socket(address->ai_family, address->ai_socktype, - address->ai_protocol); - if (transferSocket >= 0 && - ::connect(transferSocket, address->ai_addr, address->ai_addrlen) == - 0) { - break; - } - if (transferSocket >= 0) { - ::close(transferSocket); - transferSocket = -1; - } - } - freeaddrinfo(addresses); - if (transferSocket < 0) { - return {{}, -1, "cannot connect to file-transfer endpoint"}; - } - - const auto temporary = destination + ".part"; - if (const auto parent = std::filesystem::path(destination).parent_path(); - !parent.empty()) { - std::error_code directoryError; - std::filesystem::create_directories(parent, directoryError); - if (directoryError) { - ::close(transferSocket); - return {{}, -1, "cannot create file-transfer destination"}; - } - } - std::ofstream output(temporary, std::ios::binary | std::ios::trunc); - timeval socketTimeout{}; - socketTimeout.tv_sec = static_cast( - std::max(1, timeout.count() / 1000)); - setsockopt(transferSocket, SOL_SOCKET, SO_RCVTIMEO, &socketTimeout, - sizeof(socketTimeout)); - size_t keySent = 0; - while (keySent < transferKey.size()) { - const auto count = ::send(transferSocket, transferKey.data() + keySent, - transferKey.size() - keySent, 0); - if (count <= 0) { - break; - } - keySent += static_cast(count); - } - if (!output || keySent != transferKey.size()) { - ::close(transferSocket); - std::filesystem::remove(temporary); - return {{}, -1, "cannot start file transfer"}; - } - std::array buffer{}; - uint64_t received = 0; - while (true) { - const auto count = ::recv(transferSocket, buffer.data(), buffer.size(), 0); - if (count == 0) { - break; - } - if (count < 0) { - output.close(); - ::close(transferSocket); - std::filesystem::remove(temporary); - return {{}, -1, "file transfer was interrupted"}; - } - output.write(buffer.data(), count); - received += static_cast(count); - } - ::close(transferSocket); - output.close(); - uint64_t expected = 0; - try { - expected = std::stoull(sizeText); - } catch (const std::exception&) { - std::filesystem::remove(temporary); - return {{}, -1, "invalid file-transfer size"}; - } - if (!output || received != expected) { - std::filesystem::remove(temporary); - return {{}, -1, "file transfer size mismatch"}; - } - std::error_code renameError; - std::filesystem::rename(temporary, destination, renameError); - if (renameError) { - std::filesystem::remove(temporary); - return {{}, -1, "cannot install downloaded file"}; - } - return {}; - } - - void TsClient::sendVoice(std::span opus) - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - std::vector buf(3 + opus.size(), 0); - buf[2] = 5; // CODEC_OPUS_MUSIC - std::memcpy(buf.data() + 3, opus.data(), opus.size()); - sendOutgoing(buf, PacketType::Voice); - } - - void TsClient::sendVoiceStop() - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - std::vector buf(3, 0); - buf[2] = 5; - sendOutgoing(buf, PacketType::Voice); - } - - void TsClient::sendWhisper(std::span opus, - const std::vector& channelIds, - const std::vector& clientIds) - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - if (channelIds.empty() && clientIds.empty()) { - sendVoice(opus); - return; - } - // VoiceWhisper C2S: voiceId(2) + codec(1) + nChan(1) + nClient(1) - // + channelIds(u64 BE each) + clientIds(u16 BE each) - // + opus. voiceId filled by sendOutgoing. - std::vector buf; - buf.resize(3 + 2 + channelIds.size() * 8 + clientIds.size() * 2 + - opus.size()); - size_t p = 0; - p += 2; // voiceId placeholder - buf[p++] = 5; // codec - buf[p++] = static_cast(channelIds.size()); - buf[p++] = static_cast(clientIds.size()); - for (uint64_t cid : channelIds) { - for (int s = 56; s >= 0; s -= 8) { - buf[p++] = static_cast((cid >> s) & 0xff); - } - } - for (uint16_t clid : clientIds) { - buf[p++] = static_cast((clid >> 8) & 0xff); - buf[p++] = static_cast(clid & 0xff); - } - std::memcpy(buf.data() + p, opus.data(), opus.size()); - sendOutgoing(buf, PacketType::VoiceWhisper); - } - - // ---- Incoming ---------------------------------------------------------- - - std::vector TsClient::decryptPacket(std::span raw, - PacketType type, - uint16_t packetId, - uint32_t gen, uint8_t flags, - bool& ok) - { - ok = false; - if (type == PacketType::Init1) { - if (std::memcmp(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN) != 0) { - return {}; - } - ok = true; - return std::vector(raw.begin() + MAC_LEN + S2C_HEADER_LEN, - raw.end()); - } - if (flags & FLAG_UNENCRYPTED) { - if (cryptoInitComplete_ && - std::memcmp(raw.data(), fakeSignature_.data(), MAC_LEN) != 0) { - return {}; - } - ok = true; - return std::vector(raw.begin() + MAC_LEN + S2C_HEADER_LEN, - raw.end()); - } - - Crypto::ByteView header(raw.data() + MAC_LEN, S2C_HEADER_LEN); - Crypto::ByteView mac(raw.data(), MAC_LEN); - Crypto::ByteView ct(raw.data() + MAC_LEN + S2C_HEADER_LEN, - raw.size() - MAC_LEN - S2C_HEADER_LEN); - - for (bool dummy : {!cryptoInitComplete_, cryptoInitComplete_}) { - Crypto::KeyNonce kn; - if (dummy || ivStruct_.empty()) { - std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16); - std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16); - } else { - kn = Crypto::deriveKeyNonce( - true, packetId, gen, static_cast(type), - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - } - auto dec = Crypto::eaxDecrypt(Crypto::ByteView(kn.key.data(), 16), - Crypto::ByteView(kn.nonce.data(), 16), - header, ct, mac); - if (dec) { - ok = true; - return *dec; - } - } - return {}; - } - - void TsClient::handleIncomingPacket(std::span raw) - { - if (raw.size() < MAC_LEN + S2C_HEADER_LEN) { - return; - } - uint16_t packetId = getU16BE(raw, MAC_LEN); - uint8_t ptByte = raw[MAC_LEN + 2]; - auto type = static_cast(ptByte & 0x0f); - uint8_t flags = ptByte & 0xf0; - lastMessageTime_ = nowMs(); - - bool ok = false; - auto data = decryptPacket(raw, type, packetId, 0, flags, ok); - if (!ok) { - debug("failed to decrypt packet"); - return; - } - std::span d(data.data(), data.size()); - - switch (type) { - case PacketType::Init1: - handleInit(d); - break; - case PacketType::Command: - case PacketType::CommandLow: - sendAck(packetId, type == PacketType::Command ? PacketType::Ack - : PacketType::AckLow); - handleCommandData(d, flags); - break; - case PacketType::Ack: - if (data.size() >= 2) { - resendMap_.erase(getU16BE(d, 0)); - } - break; - case PacketType::Ping: - handlePing(packetId); - break; - case PacketType::Voice: - case PacketType::VoiceWhisper: - if (cb_.onVoice) { - cb_.onVoice(d); - } - break; - default: - break; - } - } - - void TsClient::sendAck(uint16_t ackId, PacketType ackType) - { - std::vector buf(2, 0); - putU16BE(buf, 0, ackId); - sendOutgoing(buf, ackType); - } - - void TsClient::handlePing(uint16_t packetId) - { - std::vector buf(2, 0); - putU16BE(buf, 0, packetId); - sendOutgoing(buf, PacketType::Pong); - } - - // ---- Handshake --------------------------------------------------------- - - void TsClient::handleInit(std::span data) - { - if (data.empty()) { - return; - } - uint8_t step = data[0]; - debug("init step " + std::to_string(step)); - - if (step == 1) { - if (data.size() < 21) { - return; - } - std::vector init2(4 + 1 + 16 + 4, 0); - putU16BE(init2, 0, - static_cast(Crypto::INIT_VERSION >> 16)); - putU16BE(init2, 2, - static_cast(Crypto::INIT_VERSION & 0xffff)); - init2[4] = 0x02; - std::memcpy(init2.data() + 5, data.data() + 1, 20); - initResend_.reset(); - sendInitPacket(init2); - } else if (step == 3) { - if (data.size() < 1 + 64 + 64 + 4 + 100) { - return; - } - state_ = ClientState::Handshake; - initResend_.reset(); - - std::span x = data.subspan(1, 64); - std::span n = data.subspan(65, 64); - int32_t level = static_cast( - (data[129] << 24) | (data[130] << 16) | (data[131] << 8) | - data[132]); - std::span serverData = data.subspan(133, 100); - debug("RSA puzzle level=" + std::to_string(level)); - - auto y = rsaPuzzle(x, n, level); - - // alpha = 10 random bytes (base64); omega = identity pubkey string. - alphaTmp_.assign(10, 0); - RAND_bytes(alphaTmp_.data(), 10); - std::string alpha = Util::base64Encode( - Crypto::ByteView(alphaTmp_.data(), alphaTmp_.size())); - - CommandParams p; - p["alpha"] = alpha; - p["omega"] = opts_.identity->publicKeyString(); - p["ot"] = "1"; - p["ip"] = ""; - std::string initAdd = buildCommand("clientinitiv", p); - std::span textBytes( - reinterpret_cast(initAdd.data()), - initAdd.size()); - - std::vector init4(4 + 1 + 64 + 64 + 4 + 100 + 64 + - textBytes.size(), - 0); - putU16BE(init4, 0, - static_cast(Crypto::INIT_VERSION >> 16)); - putU16BE(init4, 2, - static_cast(Crypto::INIT_VERSION & 0xffff)); - init4[4] = 0x04; - std::memcpy(init4.data() + 5, x.data(), 64); - std::memcpy(init4.data() + 69, n.data(), 64); - init4[133] = (level >> 24) & 0xff; - init4[134] = (level >> 16) & 0xff; - init4[135] = (level >> 8) & 0xff; - init4[136] = level & 0xff; - std::memcpy(init4.data() + 137, serverData.data(), 100); - std::memcpy(init4.data() + 237, y.data(), 64); - std::memcpy(init4.data() + 301, textBytes.data(), textBytes.size()); - - sendInitPacket(init4); - } else if (step == 0x7f) { - debug("server requested restart"); - initResend_.reset(); - sendInitPacket(buildInit0()); - } - } - - void TsClient::handleCommandData(std::span data, - uint8_t flags) - { - if (flags & FLAG_FRAGMENTED) { - if (!fragmenting_) { - fragmenting_ = true; - fragmentFlags_ = flags; - fragmentBuffer_.assign(data.begin(), data.end()); - } else { - fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(), - data.end()); - uint8_t saved = fragmentFlags_; - fragmenting_ = false; - fragmentFlags_ = 0; - auto merged = std::move(fragmentBuffer_); - fragmentBuffer_.clear(); - processCommand( - std::span(merged.data(), merged.size()), - saved); - } - return; - } - if (fragmenting_) { - fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(), - data.end()); - return; - } - processCommand(data, flags); - } - - void TsClient::processCommand(std::span data, uint8_t flags) - { - std::vector decompressed; - if (flags & FLAG_COMPRESSED) { - try { - decompressed = qlzDecompress(data); - data = std::span(decompressed.data(), - decompressed.size()); - } catch (const std::exception& e) { - debug(std::string("decompression failed: ") + e.what()); - return; - } - } - - std::string cmdStr(reinterpret_cast(data.data()), - data.size()); - auto parsed = parseCommand(cmdStr); - if (cb_.onCommand) { - cb_.onCommand(parsed); - } - - const std::string& name = parsed.name; - if (name == "error") { - std::shared_ptr pending; - { - std::lock_guard lock(pendingMutex_); - const auto returnCode = parsed.params.find("return_code"); - if (!pendingRequests_.empty() && - returnCode != parsed.params.end() && - returnCode->second == pendingRequests_.front()->returnCode) { - pending = pendingRequests_.front(); - pendingRequests_.pop_front(); - if (const auto id = parsed.params.find("id"); - id != parsed.params.end()) { - try { - pending->result.errorId = std::stoi(id->second); - } catch (const std::exception&) { - pending->result.errorId = -1; - } - } - if (const auto message = parsed.params.find("msg"); - message != parsed.params.end()) { - pending->result.errorMessage = message->second; - } - pending->completed = true; - } - } - if (pending) { - pending->cv.notify_all(); - } - } else if (!name.starts_with("notify") && name != "initivexpand" && - name != "initivexpand2" && name != "initserver") { - std::lock_guard lock(pendingMutex_); - if (!pendingRequests_.empty()) { - auto& records = pendingRequests_.front()->result.records; - if (parsed.groups.empty()) { - records.push_back(parsed.params); - } else { - records.insert(records.end(), parsed.groups.begin(), - parsed.groups.end()); - } - } - } - if (name == "initivexpand") { - handleInitIvExpand(parsed.params); - } else if (name == "initivexpand2") { - handleInitIvExpand2(parsed.params); - } else if (name == "initserver") { - handleInitServer(parsed.params); - } else if (name == "channellist") { - handleChannelList(parsed); - } else if (name == "channellistfinished") { - handleChannelListFinished(); - } else if (name == "notifyclientleftview") { - auto it = parsed.params.find("clid"); - if (it != parsed.params.end() && - static_cast(std::stoul(it->second)) == - clientId_.load()) { - cleanup(); - } - } else if (name == "notifytextmessage") { - if (cb_.onTextMessage) { - cb_.onTextMessage(parsed.params); - } - } else if (name == "error") { - int errId = 0; - auto it = parsed.params.find("id"); - if (it != parsed.params.end()) { - errId = std::stoi(it->second); - } - if (errId == 2568 || errId == 3329 || errId == 1796) { - std::string msg = "unknown error"; - auto m = parsed.params.find("msg"); - if (m != parsed.params.end()) { - msg = m->second; - } - if (cb_.onError) { - cb_.onError("TS3 error " + std::to_string(errId) + ": " + - msg); - } - disconnect(); - } - } - } - - void TsClient::handleInitIvExpand(const CommandParams& params) - { - initResend_.reset(); - auto ai = params.find("alpha"); - auto bi = params.find("beta"); - auto oi = params.find("omega"); - if (ai == params.end() || bi == params.end() || oi == params.end()) { - if (cb_.onError) { - cb_.onError("missing initivexpand parameters"); - } - return; - } - auto beta = Util::base64Decode(bi->second); - auto omega = Util::base64Decode(oi->second); - auto sharedKey = opts_.identity->sharedSecret( - Crypto::ByteView(omega.data(), omega.size())); - - ivStruct_.assign(10 + beta.size(), 0); - for (size_t i = 0; i < 10; ++i) { - ivStruct_[i] = sharedKey[i] ^ alphaTmp_[i]; - } - for (size_t i = 0; i < beta.size(); ++i) { - ivStruct_[10 + i] = sharedKey[10 + i] ^ beta[i]; - } - auto sig = Crypto::sha1( - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN); - cryptoInitComplete_ = true; - alphaTmp_.clear(); - sendClientInit(); - } - - void TsClient::handleInitIvExpand2(const CommandParams& params) - { - if (cryptoInitComplete_ || alphaTmp_.empty()) { - return; - } - initResend_.reset(); - auto li = params.find("l"); - auto bi = params.find("beta"); - auto oi = params.find("omega"); - if (li == params.end() || bi == params.end() || oi == params.end()) { - if (cb_.onError) { - cb_.onError("missing initivexpand2 parameters"); - } - return; - } - try { - auto beta = Util::base64Decode(bi->second); - auto license = Util::base64Decode(li->second); - auto blocks = - parseLicense(ByteView(license.data(), license.size())); - auto serverKey = deriveLicenseKey(blocks); - auto temp = generateTemporaryKey(); - - std::string ek = Util::base64Encode( - Crypto::ByteView(temp.publicKey.data(), 32)); - std::vector toSign(temp.publicKey.begin(), - temp.publicKey.end()); - toSign.insert(toSign.end(), beta.begin(), beta.end()); - auto sigBuf = opts_.identity->sign( - Crypto::ByteView(toSign.data(), toSign.size())); - std::string proof = Util::base64Encode( - Crypto::ByteView(sigBuf.data(), sigBuf.size())); - - CommandParams ck; - ck["ek"] = ek; - ck["proof"] = proof; - sendCommand(buildCommand("clientek", ck)); - - auto shared = getSharedSecret2( - ByteView(serverKey.data(), serverKey.size()), - ByteView(temp.privateKey.data(), 32)); - - ivStruct_.assign(shared.begin(), shared.end()); - for (size_t i = 0; i < 10 && i < ivStruct_.size(); ++i) { - ivStruct_[i] ^= alphaTmp_[i]; - } - for (size_t i = 0; i < beta.size() && (10 + i) < ivStruct_.size(); - ++i) { - ivStruct_[10 + i] ^= beta[i]; - } - auto sig = Crypto::sha1( - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN); - cryptoInitComplete_ = true; - alphaTmp_.clear(); - sendClientInit(); - } catch (const std::exception& e) { - if (cb_.onError) { - cb_.onError(std::string("initivexpand2 failed: ") + e.what()); - } - } - } - - void TsClient::sendClientInit() - { - debug("sending clientinit"); - CommandParams p; - p["client_nickname"] = opts_.nickname; - p["client_version"] = VS_VERSION; - p["client_platform"] = VS_PLATFORM; - p["client_input_hardware"] = "1"; - p["client_output_hardware"] = "1"; - p["client_default_channel"] = opts_.defaultChannel; - p["client_default_channel_password"] = - opts_.channelPassword.empty() - ? "" - : Crypto::hashPassword(opts_.channelPassword); - p["client_server_password"] = - opts_.serverPassword.empty() - ? "" - : Crypto::hashPassword(opts_.serverPassword); - p["client_meta_data"] = ""; - p["client_version_sign"] = VS_SIGN; - p["client_key_offset"] = std::to_string(opts_.identity->keyOffset()); - p["client_nickname_phonetic"] = ""; - p["client_default_token"] = ""; - p["hwid"] = ""; - sendCommand(buildCommand("clientinit", p)); - } - - void TsClient::handleInitServer(const CommandParams& params) - { - auto it = params.find("aclid"); - uint16_t id = 0; - if (it != params.end()) { - id = static_cast(std::stoul(it->second)); - } - clientId_ = id; - state_ = ClientState::Connected; - lastPing_ = nowMs(); - debug("connected, clientId=" + std::to_string(id)); - if (cb_.onConnected) { - cb_.onConnected(); - } - } - - void TsClient::handleChannelList(const ParsedCommand& parsed) - { - const auto& entries = - parsed.groups.empty() - ? std::vector{parsed.params} - : parsed.groups; - for (const auto& e : entries) { - auto ci = e.find("cid"); - auto ni = e.find("channel_name"); - if (ci != e.end() && ni != e.end()) { - channelMap_[ni->second] = - static_cast(std::stoull(ci->second)); - } - } - } - - void TsClient::handleChannelListFinished() - { - const std::string& target = opts_.defaultChannel; - if (target.empty() || clientId_.load() == 0) { - return; - } - uint64_t cid = 0; - bool numeric = !target.empty() && - target.find_first_not_of("0123456789") == - std::string::npos; - if (numeric) { - cid = std::stoull(target); - } else { - auto it = channelMap_.find(target); - if (it != channelMap_.end()) { - cid = it->second; - } - } - if (cid == 0) { - debug("default channel not found: " + target); - return; - } - CommandParams p; - p["cid"] = std::to_string(cid); - p["clid"] = std::to_string(clientId_.load()); - p["cpw"] = opts_.channelPassword; - sendCommand(buildCommand("clientmove", p)); - } - - // ---- Timers / teardown ------------------------------------------------- - - void TsClient::resendTick() - { - int64_t now = nowMs(); - - if (disconnectDeadline_ != 0 && now >= disconnectDeadline_) { - cleanup(); - return; - } - - if (initResend_) { - if (now - initResend_->firstSend > 30000) { - if (cb_.onError) { - cb_.onError("init timeout"); - } - cleanup(); - return; - } - if (now - initResend_->lastSend > 1000) { - initResend_->lastSend = now; - sendRawLocked(initResend_->raw); - } - } - - for (auto& [id, pkt] : resendMap_) { - if (now - pkt.firstSend > 30000) { - if (cb_.onError) { - cb_.onError("packet " + std::to_string(id) + " timeout"); - } - cleanup(); - return; - } - if (now - pkt.lastSend > 1000) { - pkt.lastSend = now; - sendRawLocked(pkt.raw); - } - } - - if (state_.load() == ClientState::Connected && - now - lastPing_ >= 1000) { - lastPing_ = now; - std::vector empty; - sendOutgoing(empty, PacketType::Ping); - } - - if (now - lastMessageTime_ > 30000) { - if (cb_.onError) { - cb_.onError("connection timeout - no response"); - } - cleanup(); - } - } - - void TsClient::disconnect() - { - std::lock_guard lock(mu_); - if (state_.load() == ClientState::Connected) { - state_ = ClientState::Disconnecting; - CommandParams p; - p["reasonid"] = "8"; - p["reasonmsg"] = "leaving"; - sendCommand(buildCommand("clientdisconnect", p)); - } - disconnectDeadline_ = nowMs() + 500; - } - - void TsClient::forceClose() - { - std::lock_guard lock(mu_); - if (state_.load() == ClientState::Disconnected && !running_.load()) { - return; - } - state_ = ClientState::Disconnected; - running_ = false; - if (sock_ >= 0) { - ::shutdown(sock_, SHUT_RDWR); - } - cancelPendingRequests("connection closed"); - } - - void TsClient::cleanup() - { - if (state_.load() == ClientState::Disconnected) { - return; - } - state_ = ClientState::Disconnected; - running_ = false; - cancelPendingRequests("connection closed"); - if (cb_.onDisconnected) { - cb_.onDisconnected(); - } - } - - void TsClient::cancelPendingRequests(const std::string& reason) - { - std::deque> pending; - { - std::lock_guard lock(pendingMutex_); - pending.swap(pendingRequests_); - for (const auto& request : pending) { - request->result.errorId = -1; - request->result.errorMessage = reason; - request->completed = true; - } - } - for (const auto& request : pending) { - request->cv.notify_all(); - } - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/Util.cpp b/EchoionProtocol/src/Util.cpp deleted file mode 100644 index 07eb3b0..0000000 --- a/EchoionProtocol/src/Util.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "echoion/protocol/Util.hpp" - -#include -#include - -namespace Echoion::Protocol::Util -{ - namespace - { - constexpr char kEnc[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - std::array makeDecodeTable() - { - std::array t{}; - t.fill(-1); - for (int i = 0; i < 64; ++i) { - t[static_cast(kEnc[i])] = static_cast(i); - } - return t; - } - const std::array 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(data[i]) << 16) | - (static_cast(data[i + 1]) << 8) | - static_cast(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(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(data[i]) << 16) | - (static_cast(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(c)]; - if (v < 0) { - throw std::runtime_error("invalid base64 character"); - } - buf = (buf << 6) | static_cast(v); - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((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((nib(hex[i]) << 4) | - nib(hex[i + 1]))); - } - return out; - } - -} // namespace Echoion::Protocol::Util diff --git a/EchoionProtocol/tests/CMakeLists.txt b/EchoionProtocol/tests/CMakeLists.txt deleted file mode 100644 index b610293..0000000 --- a/EchoionProtocol/tests/CMakeLists.txt +++ /dev/null @@ -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) diff --git a/EchoionProtocol/tests/check.hpp b/EchoionProtocol/tests/check.hpp deleted file mode 100644 index 0c81a5f..0000000 --- a/EchoionProtocol/tests/check.hpp +++ /dev/null @@ -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 -#include -#include -#include - -namespace echotest -{ - struct Case { - std::string name; - std::function fn; - }; - - inline std::vector& registry() - { - static std::vector cases; - return cases; - } - - inline int& failures() - { - static int f = 0; - return f; - } - - struct Registrar { - Registrar(const std::string& name, std::function 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) diff --git a/EchoionProtocol/tests/test_command.cpp b/EchoionProtocol/tests/test_command.cpp deleted file mode 100644 index 6be30ab..0000000 --- a/EchoionProtocol/tests/test_command.cpp +++ /dev/null @@ -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")); -} diff --git a/EchoionProtocol/tests/test_crypto.cpp b/EchoionProtocol/tests/test_crypto.cpp deleted file mode 100644 index 7a45ce2..0000000 --- a/EchoionProtocol/tests/test_crypto.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include - -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& b) - { - return Util::toHex(ByteView(b.data(), b.size())); - } - template std::string hx(const std::array& 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(abc.data()), abc.size())); - CHECK_EQ(hx(s1), - std::string("a9993e364706816aba3e25717850c26c9cd0d89d")); - - // base64 round-trip + known value. - CHECK_EQ(Util::base64Encode(ByteView( - reinterpret_cast("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)); -} diff --git a/EchoionProtocol/tests/test_identity.cpp b/EchoionProtocol/tests/test_identity.cpp deleted file mode 100644 index c0c7bc1..0000000 --- a/EchoionProtocol/tests/test_identity.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Identity.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include -#include -#include - -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(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(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 der{0x30, 0x0a, 0x03, 0x02, 0x06, 0xc0, - 0x02, 0x01, 0x20, 0x02, 0x01, 0x01}; - const auto decoded = Util::base64Encode(der); - std::vector 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(' ')); - for (size_t i = 20; i < obfuscated.size(); ++i) { - obfuscated[i] ^= static_cast(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(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("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()); -} diff --git a/EchoionProtocol/tests/test_main.cpp b/EchoionProtocol/tests/test_main.cpp deleted file mode 100644 index 9c8670f..0000000 --- a/EchoionProtocol/tests/test_main.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "check.hpp" - -int main() -{ - return echotest::run(); -} diff --git a/EchoionProtocol/tests/test_quicklz.cpp b/EchoionProtocol/tests/test_quicklz.cpp deleted file mode 100644 index 04044f8..0000000 --- a/EchoionProtocol/tests/test_quicklz.cpp +++ /dev/null @@ -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(3 + payload.size())); // compressed size - buf.push_back(static_cast(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); -} diff --git a/EchoionStandalone/CMakeLists.txt b/EchoionStandalone/CMakeLists.txt index d0d01c9..70a5284 100644 --- a/EchoionStandalone/CMakeLists.txt +++ b/EchoionStandalone/CMakeLists.txt @@ -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=\"$\"") + 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" + $) endif() diff --git a/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp b/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp new file mode 100644 index 0000000..ed484f3 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include +#include +#include +#include + +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 callbacks_; + std::size_t activeDispatches_{0}; + bool accepting_{true}; + }; +} diff --git a/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp b/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp new file mode 100644 index 0000000..d68c675 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include + +#include +#include + +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 + load(const std::filesystem::path& manifestPath); + [[nodiscard]] Api::Result validate() const; + }; +} diff --git a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp index b22c08a..479f6ea 100644 --- a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp @@ -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 -#include "echoion/protocol/Identity.hpp" -#include "echoion/protocol/TsClient.hpp" +#include "echoion/standalone/EventCallbackGate.hpp" +#include #include #include @@ -85,6 +85,14 @@ namespace Echoion::Standalone sendAudioData(const std::span& data) override; Api::Result setWhisperList(const std::vector& clientIds) override; + [[nodiscard]] Api::Result + createAudioStream(const AudioStreamOptions& options) override; + Api::Result destroyAudioStream(AudioStreamId id) override; + Api::Result sendAudioDataToStream( + AudioStreamId id, const std::span& data) override; + Api::Result setAudioStreamRecipients( + AudioStreamId id, + const std::vector& recipients) override; // Connection Api::Result @@ -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& 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 - commandResult(const Protocol::CommandResult& result) const; + [[nodiscard]] Api::Result commandResult( + const Void::Result::Result& result) const; StandaloneSettings settings_; - std::unique_ptr identity_; - std::unique_ptr client_; + std::shared_ptr identity_; + std::unique_ptr client_; std::unique_ptr encoder_; Api::ServerConfig currentConfig_{}; @@ -128,10 +141,13 @@ namespace Echoion::Standalone std::map avatarUrls_; std::map avatarPaths_; std::vector whisperList_; + struct AudioStreamRuntime; + std::map> audioStreams_; + std::atomic nextAudioStreamId_{1}; + mutable std::mutex audioStreamsMutex_; std::jthread snapshotThread_; - std::mutex cbMutex_; - std::vector callbacks_; + EventCallbackGate eventCallbacks_; }; } // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/EventCallbackGate.cpp b/EchoionStandalone/src/EventCallbackGate.cpp new file mode 100644 index 0000000..ddf6f45 --- /dev/null +++ b/EchoionStandalone/src/EventCallbackGate.cpp @@ -0,0 +1,42 @@ +#include "echoion/standalone/EventCallbackGate.hpp" + +#include + +#include + +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 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); + } + } +} diff --git a/EchoionStandalone/src/ReleaseManifest.cpp b/EchoionStandalone/src/ReleaseManifest.cpp new file mode 100644 index 0000000..9775af5 --- /dev/null +++ b/EchoionStandalone/src/ReleaseManifest.cpp @@ -0,0 +1,127 @@ +#include "echoion/standalone/ReleaseManifest.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + namespace + { + Api::Result 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; + 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 buffer{}; + while (input) { + input.read(buffer.data(), static_cast(buffer.size())); + if (const auto count = input.gcount(); count > 0 && + EVP_DigestUpdate(context.get(), buffer.data(), + static_cast(count)) != 1) { + return Api::fail(Api::ErrorCode::UnknownError, + "cannot hash release artifact"); + } + } + std::array 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(digest[index]); + } + return output.str(); + } + } + + Api::Result + 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 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 {}; + } +} diff --git a/EchoionStandalone/src/StandaloneClientInterface.cpp b/EchoionStandalone/src/StandaloneClientInterface.cpp index 8f1598e..d54746a 100644 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ b/EchoionStandalone/src/StandaloneClientInterface.cpp @@ -2,18 +2,27 @@ #include "echoion/standalone/AudioEncoder.hpp" #include "echoion/standalone/MessageChunker.hpp" -#include "echoion/protocol/Command.hpp" - #include +#include +#include #include #include #include +#include #include #include namespace Echoion::Standalone { + struct StandaloneClientInterface::AudioStreamRuntime { + std::mutex mutex; + std::shared_ptr identity; + std::unique_ptr client; + std::unique_ptr encoder; + std::vector 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(settings_.opusBitrate); - client_ = std::make_unique(); + client_ = std::make_unique(); Void::Log::info(LOG, "Standalone client interface initialized"); return {}; } @@ -81,8 +90,19 @@ namespace Echoion::Standalone if (!initialized_.exchange(false)) { return {}; } + std::vector> streams; + { + std::lock_guard 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::load(idPath.string())); + identity_ = std::make_shared( + 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::generate(settings_.securityLevel)); + identity_ = std::make_shared( + 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 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) { + cb.voice = [this](std::span) { 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 StandaloneClientInterface::commandResult( - const Protocol::CommandResult& result) const + const Void::Result::Result& 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{} + : 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 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& records) { - const auto& groups = - p.groups.empty() - ? std::vector{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 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 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 cbs; - { - std::lock_guard 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 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::max()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); + } + return commandResult(client_->move( + Void::TeamSpeak::ClientId{static_cast(clientId)}, + Void::TeamSpeak::ChannelId{channelId})); } Api::Result @@ -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::max()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); + } + return commandResult(client_->kick( + Void::TeamSpeak::ClientId{static_cast(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 @@ -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& 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 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 clients; - clients.reserve(whisper.size()); + Void::TeamSpeak::WhisperTargets targets; + targets.clients.reserve(whisper.size()); for (uint64_t c : whisper) { - clients.push_back(static_cast(c)); + targets.clients.push_back(Void::TeamSpeak::ClientId{ + static_cast(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 + 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::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(); + 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::load(identityPath.string())); + } else { + std::filesystem::create_directories(identityPath.parent_path()); + runtime->identity = std::make_shared( + Void::TeamSpeak::Identity::generate(settings_.securityLevel)); + runtime->identity->save(identityPath.string()); + } + runtime->encoder = std::make_unique(settings_.opusBitrate); + runtime->client = std::make_unique(); + 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 lock(audioStreamsMutex_); + audioStreams_.emplace(id, std::move(runtime)); + return id; + } + + Api::Result + StandaloneClientInterface::destroyAudioStream(AudioStreamId id) + { + std::shared_ptr stream; + { + std::lock_guard 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 StandaloneClientInterface::sendAudioDataToStream( + AudioStreamId id, const std::span& data) + { + std::shared_ptr stream; + { + std::lock_guard 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(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 StandaloneClientInterface::setAudioStreamRecipients( + AudioStreamId id, const std::vector& recipients) + { + if (std::ranges::any_of(recipients, [](uint64_t clientId) { + return clientId == 0 || + clientId > std::numeric_limits::max(); + })) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "stream recipient is outside the TeamSpeak client ID range"); + } + std::shared_ptr stream; + { + std::lock_guard 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 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 lock(cbMutex_); - callbacks_.clear(); + quiesceEventCallbacks(); + } + + void StandaloneClientInterface::quiesceEventCallbacks() + { + eventCallbacks_.quiesce(); } } // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/main.cpp b/EchoionStandalone/src/main.cpp index ee96500..f9603f1 100644 --- a/EchoionStandalone/src/main.cpp +++ b/EchoionStandalone/src/main.cpp @@ -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 #include #include +#include +#include +#include +#include #include #include @@ -30,6 +34,7 @@ namespace { std::atomic g_stop{false}; + std::atomic 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 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 releaseWatcher; + std::optional releaseManifestPath; + if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) { + releaseManifestPath = manifest; + releaseWatcher = std::make_unique(); + 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 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 pendingRelease; + std::filesystem::path checkpointPath; + while (!g_stop.load() && !pendingRelease) { + { + std::unique_lock 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 arguments; + arguments.reserve(static_cast(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; } diff --git a/EchoionStandalone/tests/test_core_loader_reload.cpp b/EchoionStandalone/tests/test_core_loader_reload.cpp new file mode 100644 index 0000000..6461392 --- /dev/null +++ b/EchoionStandalone/tests/test_core_loader_reload.cpp @@ -0,0 +1,97 @@ +#include "echoion/host/CoreLoader.hpp" + +#include +#include +#include +#include +#include + +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; +} diff --git a/EchoionStandalone/tests/test_event_callback_gate.cpp b/EchoionStandalone/tests/test_event_callback_gate.cpp new file mode 100644 index 0000000..6bedd97 --- /dev/null +++ b/EchoionStandalone/tests/test_event_callback_gate.cpp @@ -0,0 +1,59 @@ +#include "echoion/standalone/EventCallbackGate.hpp" + +#include +#include +#include +#include +#include +#include +#include + +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 calls{0}; + auto lifetime = std::make_shared(42); + std::weak_ptr 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); +} diff --git a/EchoionStandalone/tests/test_release_manifest.cpp b/EchoionStandalone/tests/test_release_manifest.cpp new file mode 100644 index 0000000..64ce918 --- /dev/null +++ b/EchoionStandalone/tests/test_release_manifest.cpp @@ -0,0 +1,38 @@ +#include "echoion/standalone/ReleaseManifest.hpp" + +#include +#include + +#include + +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; +} diff --git a/EchoionStandalone/tests/test_stage_release.sh b/EchoionStandalone/tests/test_stage_release.sh new file mode 100755 index 0000000..02cd823 --- /dev/null +++ b/EchoionStandalone/tests/test_stage_release.sh @@ -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 diff --git a/EchoionWeb/frontend/src/App.tsx b/EchoionWeb/frontend/src/App.tsx index 4981d18..4ed3544 100644 --- a/EchoionWeb/frontend/src/App.tsx +++ b/EchoionWeb/frontend/src/App.tsx @@ -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 = { now: ['Now Playing', 'What Echoion is streaming to the channel'], @@ -26,6 +27,7 @@ const HEADS: Record = { 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' && } {s.view === 'library' && } {s.view === 'stats' && } + {s.view === 'rooms' && } {/* The watch view stays mounted so the embedded player and room connection survive view switches (the old UI only toggled `hidden`). */} diff --git a/EchoionWeb/frontend/src/components/Sidebar.tsx b/EchoionWeb/frontend/src/components/Sidebar.tsx index 09046ed..0dcd65c 100644 --- a/EchoionWeb/frontend/src/components/Sidebar.tsx +++ b/EchoionWeb/frontend/src/components/Sidebar.tsx @@ -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: , label: 'Search' }, { view: 'library', icon: , label: 'Library' }, { view: 'stats', icon: , label: 'History & Stats' }, + { view: 'rooms', icon: , label: 'Listening Rooms' }, { view: 'watch', icon: , label: 'Watch Together' }, { view: 'server', icon: , label: 'Server & Admin' }, { view: 'rpc', icon: , label: 'RPC / API' }, diff --git a/EchoionWeb/frontend/src/components/icons.tsx b/EchoionWeb/frontend/src/components/icons.tsx index ee82d0a..1aab3f3 100644 --- a/EchoionWeb/frontend/src/components/icons.tsx +++ b/EchoionWeb/frontend/src/components/icons.tsx @@ -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' ); diff --git a/EchoionWeb/frontend/src/i18n/ru.ts b/EchoionWeb/frontend/src/i18n/ru.ts index e703aa3..25b7d64 100644 --- a/EchoionWeb/frontend/src/i18n/ru.ts +++ b/EchoionWeb/frontend/src/i18n/ru.ts @@ -10,6 +10,9 @@ export const ru: Record = { '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 = { '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': 'Встраиваемый плеер — только просмотр', diff --git a/EchoionWeb/frontend/src/lib/app.ts b/EchoionWeb/frontend/src/lib/app.ts index c8b1d1f..9370410 100644 --- a/EchoionWeb/frontend/src/lib/app.ts +++ b/EchoionWeb/frontend/src/lib/app.ts @@ -22,6 +22,7 @@ export type ViewName = | 'search' | 'library' | 'stats' + | 'rooms' | 'watch' | 'server' | 'rpc'; diff --git a/EchoionWeb/frontend/src/lib/auditMethods.test.ts b/EchoionWeb/frontend/src/lib/auditMethods.test.ts new file mode 100644 index 0000000..3e407a7 --- /dev/null +++ b/EchoionWeb/frontend/src/lib/auditMethods.test.ts @@ -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'); + }); +}); diff --git a/EchoionWeb/frontend/src/lib/auditMethods.ts b/EchoionWeb/frontend/src/lib/auditMethods.ts index a85c36b..5143ef3 100644 --- a/EchoionWeb/frontend/src/lib/auditMethods.ts +++ b/EchoionWeb/frontend/src/lib/auditMethods.ts @@ -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 { diff --git a/EchoionWeb/frontend/src/lib/router.ts b/EchoionWeb/frontend/src/lib/router.ts index c88c8a1..96b5208 100644 --- a/EchoionWeb/frontend/src/lib/router.ts +++ b/EchoionWeb/frontend/src/lib/router.ts @@ -13,6 +13,7 @@ const VIEWS: readonly ViewName[] = [ 'search', 'library', 'stats', + 'rooms', 'watch', 'server', 'rpc', diff --git a/EchoionWeb/frontend/src/lib/rpc.test.ts b/EchoionWeb/frontend/src/lib/rpc.test.ts index c1be43c..b78b0ab 100644 --- a/EchoionWeb/frontend/src/lib/rpc.test.ts +++ b/EchoionWeb/frontend/src/lib/rpc.test.ts @@ -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([]); + }); }); diff --git a/EchoionWeb/frontend/src/lib/rpc.ts b/EchoionWeb/frontend/src/lib/rpc.ts index a6ad4eb..284cf4a 100644 --- a/EchoionWeb/frontend/src/lib/rpc.ts +++ b/EchoionWeb/frontend/src/lib/rpc.ts @@ -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) { diff --git a/EchoionWeb/frontend/src/lib/types.ts b/EchoionWeb/frontend/src/lib/types.ts index d91349b..3c5b4e6 100644 --- a/EchoionWeb/frontend/src/lib/types.ts +++ b/EchoionWeb/frontend/src/lib/types.ts @@ -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; diff --git a/EchoionWeb/frontend/src/styles/style.css b/EchoionWeb/frontend/src/styles/style.css index 4c606b4..5c695c6 100644 --- a/EchoionWeb/frontend/src/styles/style.css +++ b/EchoionWeb/frontend/src/styles/style.css @@ -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 { diff --git a/EchoionWeb/frontend/src/views/RoomsView.tsx b/EchoionWeb/frontend/src/views/RoomsView.tsx new file mode 100644 index 0000000..beac4ca --- /dev/null +++ b/EchoionWeb/frontend/src/views/RoomsView.tsx @@ -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([]); + const [currentRoom, setCurrentRoom] = useState(null); + const [queue, setQueue] = useState([]); + 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('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 ( +
+
+
+ {t('MULTI-STREAM')} +

{t('Your channel, split into listening spaces')}

+

+ {t( + 'Each room has its own queue and bot stream. Join one to hear and control it.' + )} +

+
+
{ + 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(); + } + }} + > + setRoomName(event.target.value)} + placeholder={t('Room name')} + maxLength={48} + /> + +
+
+ +
+
+
+

{t('Live rooms')}

+ +
+ {rooms.length === 0 ? ( + + ) : ( +
+ {rooms.map((room) => { + const selected = room.name === currentRoom; + return ( + + ); + })} +
+ )} +
+ +
+ {!current ? ( +
+ 04 +

{t('Choose a room')}

+

{t('Your TeamSpeak audio follows the room you join.')}

+
+ ) : ( + <> +
+
+ {t('NOW TUNED')} +

{current.name}

+
+
+ + {current.isOwner && ( + + )} +
+
+ +
+ + + +
+ {current.isPlaying ? (current.isPaused ? t('Paused') : t('Streaming now')) : t('Ready')} + {tf('{0} people are tuned in', current.members.length)} +
+
+ +
{ + 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(); } + }} + > + setQuery(event.target.value)} placeholder={t('Paste a URL or search for a track…')} /> + +
+ +
+

{t('Room queue')}

+
+ {tf('{0} tracks', queue.length)} + {!!queue.length && } +
+
+
+ {queue.length ? queue.map((entry, index) => ( + 0 && { icon: , 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: , title: t('Move down'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index + 1 }); await refresh(); } }, + { icon: , title: t('Remove'), cls: 'danger', onClick: async () => { await safeCall('RemoveFromListeningRoomQueue', { room: current.name, queueId: entry.queueId }); await refresh(); } }, + ]} /> + )) : } +
+ + )} +
+
+
+ ); +} diff --git a/README.md b/README.md index d5d78ad..b4be831 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh new file mode 100755 index 0000000..a3040e1 --- /dev/null +++ b/scripts/stage-release.sh @@ -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" diff --git a/systemd/echoion-standalone.service b/systemd/echoion-standalone.service index 5e28b2a..6695af3 100644 --- a/systemd/echoion-standalone.service +++ b/systemd/echoion-standalone.service @@ -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 diff --git a/systemd/release-manifest.example.json b/systemd/release-manifest.example.json new file mode 100644 index 0000000..a37434c --- /dev/null +++ b/systemd/release-manifest.example.json @@ -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" + } +}