Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-11 16:30:05 +03:00
1 parent c9a52b73ac
commit 2d1d03db1e
22 files changed
+2040 -102

No files matched your search

+10 -9
View File
@@ -103,7 +103,7 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Options # Options
option(BUILD_API "Build EchoionApi" ON) option(BUILD_API "Build EchoionApi" ON)
option(BUILD_CORE "Build EchoionCore" ON) option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build EchoionPlugin" ON) option(BUILD_PLUGIN "Build archived EchoionPlugin compatibility target" OFF)
option(BUILD_DESKTOP "Build EchoionDesktop" ON) option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON) option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
option(BUILD_PROTOCOL "Build EchoionProtocol (native TeamSpeak UDP client)" ON) option(BUILD_PROTOCOL "Build EchoionProtocol (native TeamSpeak UDP client)" ON)
@@ -112,6 +112,10 @@ option(BUILD_TESTS "Build tests" OFF)
option(BUILD_SHARED_LIBS "Build shared libraries" ON) option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON) option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
if(BUILD_TESTS)
enable_testing()
endif()
# Static linking configuration # Static linking configuration
if(ECHOION_STATIC_LINK) if(ECHOION_STATIC_LINK)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE) set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
@@ -127,6 +131,10 @@ if(BUILD_API)
add_subdirectory(EchoionApi) add_subdirectory(EchoionApi)
endif() endif()
if(BUILD_PLUGIN OR BUILD_STANDALONE)
add_subdirectory(EchoionHost)
endif()
if(BUILD_CORE) if(BUILD_CORE)
add_subdirectory(EchoionCore) add_subdirectory(EchoionCore)
endif() endif()
@@ -151,8 +159,7 @@ if(BUILD_PROTOCOL OR BUILD_STANDALONE)
add_subdirectory(EchoionProtocol) add_subdirectory(EchoionProtocol)
endif() endif()
# EchoionStandalone: reuses the plugin's CoreLoader, so it needs EchoionPlugin's # EchoionStandalone links the host-common loader and native protocol client.
# sources present. It links the Api + EchoionProtocol and loads Core at runtime.
if(BUILD_STANDALONE) if(BUILD_STANDALONE)
add_subdirectory(EchoionStandalone) add_subdirectory(EchoionStandalone)
endif() endif()
@@ -161,12 +168,6 @@ if(BUILD_DESKTOP)
add_subdirectory(EchoionDesktop) add_subdirectory(EchoionDesktop)
endif() endif()
# Tests
if(BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
# Packaging configuration # Packaging configuration
include(CPack) include(CPack)
set(CPACK_PACKAGE_NAME "Echoion") set(CPACK_PACKAGE_NAME "Echoion")
+42
View File
@@ -0,0 +1,42 @@
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)
target_compile_features(EchoionHost PUBLIC cxx_std_26)
set_target_properties(EchoionHost PROPERTIES POSITION_INDEPENDENT_CODE ON)
target_include_directories(EchoionHost PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(EchoionHost
PUBLIC
Echoion::ApiBase
Echoion::ApiConfig
Echoion::ApiPlugin
Echoion::ApiOpaque
Echoion::ApiCoreInterface
dylib
PRIVATE
Echoion::ApiLogger
Void::Data
Void::Log
Void::Stacktrace
Threads::Threads
)
if(NOT MSVC)
target_compile_options(EchoionHost PRIVATE
-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow)
endif()
@@ -0,0 +1,95 @@
#pragma once
#include "echoion/host/FileWatcher.hpp"
#include <CoreInterface.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <dylib.hpp>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
namespace Echoion::Host
{
class CoreLoader
{
public:
CoreLoader();
~CoreLoader();
Api::Result<void> load(const std::filesystem::path& libraryPath);
Api::Result<void> unload();
Api::Result<void>
hotReload(const std::filesystem::path& newLibraryPath);
[[nodiscard]] bool isLoaded() const noexcept;
[[nodiscard]] Api::CoreInterfacePtr getCore() const;
void setConfigPath(const std::filesystem::path& configPath);
[[nodiscard]] std::filesystem::path getConfigPath() const;
[[nodiscard]] bool isHotReloading() const noexcept;
// Automatic hot reload
void enableAutoReload();
void disableAutoReload();
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
// Callback for hot reload completion (called after auto-reload
// finishes)
using HotReloadCallback = std::function<void()>;
void setHotReloadCallback(HotReloadCallback callback)
{
hotReloadCallback_ = std::move(callback);
}
private:
Api::Result<void>
loadLibraryInternal(const std::filesystem::path& path);
Api::Result<void> unloadLibraryInternal();
[[nodiscard]] Api::SerializedState saveStateInternal();
[[nodiscard]] Api::Result<void>
restoreStateInternal(const Api::SerializedState& state);
[[nodiscard]] std::filesystem::path
getTempLibraryPath(const std::filesystem::path& original) const;
void cleanupTempFiles();
std::unique_ptr<dylib::library> library_;
Api::CoreInterfacePtr core_;
std::filesystem::path currentLibraryPath_;
std::filesystem::path tempLibraryPath_;
std::filesystem::path configPath_;
mutable std::mutex mutex_;
std::atomic<bool> loaded_{false};
std::atomic<bool> hotReloading_{false};
// Auto reload
FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
// Deferred reload - waits for current track to finish
std::thread deferredReloadThread_;
std::atomic<bool> hasPendingReload_{false};
std::atomic<bool> stopDeferredReload_{false};
std::condition_variable deferredReloadCv_;
std::filesystem::path pendingReloadPath_;
std::string pendingTrackId_; // Track ID that was playing when
// reload scheduled
mutable std::mutex pendingReloadMutex_;
// Hot reload completion callback
HotReloadCallback hotReloadCallback_;
void onCoreFileChanged();
void waitForTrackAndReload(const std::filesystem::path& targetPath,
const std::string& trackId);
[[nodiscard]] bool isPlaybackActive() const;
[[nodiscard]] bool
isSameTrackPlaying(const std::string& trackId) const;
};
} // namespace Echoion::Host
@@ -0,0 +1,65 @@
#pragma once
#include <atomic>
#include <chrono>
#include <filesystem>
#include <functional>
#include <mutex>
#include <thread>
namespace Echoion::Host
{
/**
* @brief Simple file watcher that monitors a file for changes
* and triggers a callback when the file is modified.
*/
class FileWatcher
{
public:
using ChangeCallback = std::function<void()>;
FileWatcher();
~FileWatcher();
// Disable copy
FileWatcher(const FileWatcher&) = delete;
FileWatcher& operator=(const FileWatcher&) = delete;
/**
* @brief Start watching a file for changes
* @param filePath Path to the file to watch
* @param callback Function to call when file changes
* @param intervalMs Polling interval in milliseconds
*/
void startWatching(const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs =
std::chrono::milliseconds(1000));
/**
* @brief Stop watching
*/
void stopWatching();
[[nodiscard]] bool isWatching() const noexcept;
private:
void watchLoop();
std::filesystem::path watchedPath_;
ChangeCallback callback_;
std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
std::atomic<bool> stopRequested_{false};
std::thread watchThread_;
std::mutex mutex_;
// Store last modification time
std::filesystem::file_time_type lastWriteTime_;
std::uint64_t lastFileSize_ = 0;
};
} // namespace Echoion::Host
+517
View File
@@ -0,0 +1,517 @@
#include <Void/Log/Log.hpp>
#include "dylib.hpp"
#include "echoion/host/CoreLoader.hpp"
#include <chrono>
#include <format>
#include <fstream>
#include <iostream>
#include <thread>
namespace Echoion::Host
{
CoreLoader::CoreLoader() { cleanupTempFiles(); }
void CoreLoader::enableAutoReload()
{
if (autoReloadEnabled_.exchange(true)) {
return; // Already enabled
}
std::lock_guard<std::mutex> lock(mutex_);
if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) {
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.startWatching(currentLibraryPath_,
[this]() { onCoreFileChanged(); });
}
}
void CoreLoader::disableAutoReload()
{
autoReloadEnabled_ = false;
fileWatcher_.stopWatching();
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
}
bool CoreLoader::isAutoReloadEnabled() const noexcept
{
return autoReloadEnabled_.load();
}
void CoreLoader::onCoreFileChanged()
{
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
return;
}
Void::Log::info("CoreLoader", "{}",
"Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Check if playback is active - if so, defer reload
if (isPlaybackActive()) {
std::string currentTrackId;
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = true;
pendingReloadPath_ = currentLibraryPath_;
// Capture current track ID
auto state = core_->getPlaybackSummary();
if (state && state->currentTrack.has_value()) {
pendingTrackId_ = state->currentTrack->id;
currentTrackId = pendingTrackId_;
}
}
Void::Log::info("CoreLoader", "{}",
std::format("Playback active (track: {}), deferring reload "
"until track finishes",
currentTrackId));
// Start background thread to wait for track end
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
deferredReloadThread_ = std::thread([this, currentTrackId]() {
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
});
} else {
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
}
bool CoreLoader::isPlaybackActive() const
{
if (!core_) {
return false;
}
auto state = core_->getPlaybackSummary();
if (!state) {
return false;
}
// Check if currently playing a track
return state->isPlaying && state->currentTrack.has_value();
}
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
{
if (!core_ || trackId.empty()) {
return false;
}
auto state = core_->getPlaybackSummary();
if (!state || !state->currentTrack.has_value()) {
return false;
}
return state->currentTrack->id == trackId;
}
void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId)
{
Void::Log::info("CoreLoader", "{}", std::format(
"Waiting for track {} to finish before reload...", trackId));
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS
// track). The wait is interruptible so the destructor can join this
// thread instead of detaching it (detaching risks use-after-free when
// the plugin unloads mid-wait).
while (isSameTrackPlaying(trackId)) {
std::unique_lock<std::mutex> lock(pendingReloadMutex_);
if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) {
Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)");
return;
}
}
if (stopDeferredReload_.load()) {
return;
}
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
// Clear pending flag
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = false;
pendingTrackId_.clear();
}
// Now do the reload
auto result = hotReload(targetPath);
if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
CoreLoader::~CoreLoader()
{
// Signal the deferred reload thread to stop and wait for it. It must
// never outlive this object: it dereferences core_ and this.
stopDeferredReload_ = true;
deferredReloadCv_.notify_all();
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
if (auto result = unload(); !result) {
Void::Log::warn("CoreLoader", "{}",
std::format("Unload from destructor failed: {}",
result.error().message));
}
cleanupTempFiles();
}
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
{
std::lock_guard<std::mutex> lock(mutex_);
if (loaded_) {
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already loaded");
}
if (!std::filesystem::exists(libraryPath)) {
return Api::fail(
Api::ErrorCode::NotFound,
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_);
if (result) {
currentLibraryPath_ = libraryPath;
} else {
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
}
return result;
}
Api::Result<void> CoreLoader::unload()
{
std::lock_guard<std::mutex> lock(mutex_);
auto result = unloadLibraryInternal();
if (!tempLibraryPath_.empty()) {
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
}
return result;
}
Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!loaded_) {
return Api::fail(Api::ErrorCode::NotFound,
"No core loaded to reload");
}
hotReloading_ = true;
Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file...");
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
Api::StateBlob stateBlob;
if (core_) {
stateBlob = core_->saveState();
Void::Log::info("CoreLoader", "{}",
std::format("Saved state: version={}, size={} bytes",
stateBlob.version, stateBlob.size()));
}
auto targetPath =
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
if (!std::filesystem::exists(targetPath)) {
hotReloading_ = false;
return Api::fail(
Api::ErrorCode::NotFound,
std::format("New library not found: {}", targetPath.string()));
}
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
try {
std::filesystem::copy_file(
targetPath, newTempPath,
std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) {
hotReloading_ = false;
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return Api::fail(Api::ErrorCode::UnknownError,
std::format("Failed to copy new library to temp: {}",
e.what()));
}
auto unloadResult = unloadLibraryInternal();
if (!unloadResult) {
hotReloading_ = false;
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return unloadResult;
}
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");
}
} 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
}
}
currentLibraryPath_ = targetPath;
hotReloading_ = false;
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
return {};
}
bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
Api::CoreInterfacePtr CoreLoader::getCore() const
{
std::lock_guard<std::mutex> lock(mutex_);
return core_;
}
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
{
std::lock_guard<std::mutex> lock(mutex_);
configPath_ = configPath;
}
std::filesystem::path CoreLoader::getConfigPath() const
{
std::lock_guard<std::mutex> lock(mutex_);
return configPath_;
}
bool CoreLoader::isHotReloading() const noexcept
{
return hotReloading_.load();
}
Api::Result<void>
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
{
try {
std::cout << std::format("[Echoion] Loading core library: {}",
path.string())
<< '\n';
// Use no decorations - the path already has the correct extension
// (.ts)
library_ = std::make_unique<dylib::library>(
path.string(), dylib::decorations::none());
auto createFunc =
library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
auto versionFunc =
library_->get_function<const char*()>("GetApiVersion");
auto compatibleFunc =
library_->get_function<bool(uint32_t, uint32_t)>(
"IsApiCompatible");
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
library_.reset();
return Api::fail(
Api::ErrorCode::InvalidArgument,
std::format("API version mismatch. Expected {}.{}, got {}",
Api::VERSION_MAJOR, Api::VERSION_MINOR,
versionFunc()));
}
core_ = createFunc();
if (!core_) {
library_.reset();
return Api::fail(Api::ErrorCode::UnknownError,
"Failed to create core instance");
}
auto initResult = core_->initialize(configPath_);
if (!initResult) {
core_.reset();
library_.reset();
return initResult;
}
loaded_ = true;
Void::Log::info("CoreLoader", "{}", std::format(
"Core library loaded (API version: {})", versionFunc()));
return {};
} catch (const dylib::load_error& e) {
return Api::fail(
Api::ErrorCode::PluginError,
std::format("Failed to load library: {}", e.what()));
} catch (const dylib::symbol_error& e) {
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()));
}
}
Api::Result<void> CoreLoader::unloadLibraryInternal()
{
if (!loaded_) {
return {};
}
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();
}
library_.reset();
loaded_ = false;
std::cout << "[Echoion] Core library unloaded" << '\n';
return {};
}
std::filesystem::path CoreLoader::getTempLibraryPath(
const std::filesystem::path& original) const
{
auto tempDir = std::filesystem::temp_directory_path();
auto filename = original.filename().string();
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
// Use the same extension as the original file (.ts for TeamSpeak plugin)
#ifdef _WIN32
auto tempName = std::format(
"echoion_{}_{}.dll", ms,
std::hash<std::thread::id>{}(std::this_thread::get_id()));
#else
auto tempName = std::format(
"echoion_{}_{}.ts", ms,
std::hash<std::thread::id>{}(std::this_thread::get_id()));
#endif
return tempDir / tempName;
}
void CoreLoader::cleanupTempFiles()
{
auto tempDir = std::filesystem::temp_directory_path();
std::error_code ec;
for (const auto& entry :
std::filesystem::directory_iterator(tempDir, ec)) {
if (entry.is_regular_file()) {
auto name = entry.path().filename().string();
if (name.starts_with("echoion_") &&
(name.ends_with(".dll") || name.ends_with(".so") ||
name.ends_with(".ts"))) {
std::filesystem::remove(entry.path(), ec);
}
}
}
}
} // namespace Echoion::Host
+98
View File
@@ -0,0 +1,98 @@
#include "echoion/host/FileWatcher.hpp"
#include <chrono>
#include <format>
#include <iostream>
namespace Echoion::Host
{
FileWatcher::FileWatcher() = default;
FileWatcher::~FileWatcher() { stopWatching(); }
void FileWatcher::startWatching(const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs)
{
std::lock_guard<std::mutex> lock(mutex_);
if (watching_.load()) {
stopWatching();
}
watchedPath_ = filePath;
callback_ = std::move(callback);
intervalMs_ = intervalMs;
stopRequested_ = false;
// Get initial file state
if (std::filesystem::exists(watchedPath_)) {
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
lastFileSize_ = std::filesystem::file_size(watchedPath_);
}
watching_ = true;
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
}
void FileWatcher::stopWatching()
{
stopRequested_ = true;
if (watchThread_.joinable()) {
watchThread_.join();
}
watching_ = false;
}
bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
void FileWatcher::watchLoop()
{
while (!stopRequested_.load()) {
// Sleep first to avoid checking immediately
std::this_thread::sleep_for(intervalMs_);
if (stopRequested_.load()) {
break;
}
std::lock_guard<std::mutex> lock(mutex_);
if (!std::filesystem::exists(watchedPath_)) {
continue;
}
try {
auto currentWriteTime =
std::filesystem::last_write_time(watchedPath_);
auto currentFileSize = std::filesystem::file_size(watchedPath_);
// Check if file has changed (time or size)
if (currentWriteTime != lastWriteTime_ ||
currentFileSize != lastFileSize_) {
// Update stored values
lastWriteTime_ = currentWriteTime;
lastFileSize_ = currentFileSize;
// Trigger callback
if (callback_) {
try {
callback_();
} catch (const std::exception& e) {
std::cerr
<< std::format("FileWatcher callback error: {}",
e.what())
<< '\n';
}
}
}
} catch (const std::exception& e) {
// Ignore errors (file might be locked during write)
}
}
}
} // namespace Echoion::Host
@@ -28,6 +28,9 @@ namespace Echoion::Protocol
// Load / save the identity to a small text file: // Load / save the identity to a small text file:
// privateKeyPem, publicKeyString, keyOffset (one per line). // privateKeyPem, publicKeyString, keyOffset (one per line).
static Identity load(const std::string& path); static Identity load(const std::string& path);
// Import an identity exported by the TeamSpeak client. The export is
// an INI file containing its obfuscated "<offset>V<base64>" key.
static Identity importTeamSpeakIni(const std::string& path);
void save(const std::string& path) const; void save(const std::string& path) const;
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv). // libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
@@ -12,7 +12,10 @@
#include "echoion/protocol/Identity.hpp" #include "echoion/protocol/Identity.hpp"
#include <atomic> #include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint> #include <cstdint>
#include <deque>
#include <functional> #include <functional>
#include <map> #include <map>
#include <memory> #include <memory>
@@ -66,6 +69,14 @@ namespace Echoion::Protocol
std::function<void(const std::string&)> onDebug; std::function<void(const std::string&)> onDebug;
}; };
struct CommandResult {
std::vector<CommandParams> records;
int errorId = 0;
std::string errorMessage;
[[nodiscard]] bool ok() const noexcept { return errorId == 0; }
};
class TsClient class TsClient
{ {
public: public:
@@ -100,6 +111,16 @@ namespace Echoion::Protocol
// Send a raw pre-built TS3 command line (fragmented if large). // Send a raw pre-built TS3 command line (fragmented if large).
void sendCommand(const std::string& cmd); 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: private:
@@ -139,6 +160,7 @@ namespace Echoion::Protocol
void resendTick(); void resendTick();
void debug(const std::string& msg); void debug(const std::string& msg);
void cleanup(); void cleanup();
void cancelPendingRequests(const std::string& reason);
// counters / crypto // counters / crypto
struct Counter { struct Counter {
@@ -190,6 +212,18 @@ namespace Echoion::Protocol
// channel map for auto-move // channel map for auto-move
std::map<std::string, uint64_t> channelMap_; std::map<std::string, uint64_t> channelMap_;
struct PendingRequest {
CommandResult result;
std::string returnCode;
bool completed = false;
std::condition_variable cv;
};
std::mutex requestSerialMutex_;
std::mutex pendingMutex_;
std::deque<std::shared_ptr<PendingRequest>> pendingRequests_;
std::atomic<uint64_t> requestId_{0};
std::atomic<uint16_t> transferId_{0};
}; };
} // namespace Echoion::Protocol } // namespace Echoion::Protocol
+6 -2
View File
@@ -57,7 +57,9 @@ namespace Echoion::Protocol::Crypto
{ {
Bytes input(BLOCK_SIZE + data.size(), 0); Bytes input(BLOCK_SIZE + data.size(), 0);
input[BLOCK_SIZE - 1] = tag; input[BLOCK_SIZE - 1] = tag;
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size()); if (!data.empty()) {
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size());
}
return cmac(key, input); return cmac(key, input);
} }
@@ -160,7 +162,9 @@ namespace Echoion::Protocol::Crypto
} }
} else { } else {
const size_t rem = n - off; const size_t rem = n - off;
std::memcpy(last.data(), data.data() + off, rem); if (rem != 0) {
std::memcpy(last.data(), data.data() + off, rem);
}
last[rem] = 0x80; last[rem] = 0x80;
for (size_t j = 0; j < BLOCK_SIZE; ++j) { for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= K2[j]; last[j] ^= K2[j];
+250 -1
View File
@@ -4,13 +4,20 @@
#include <openssl/bn.h> #include <openssl/bn.h>
#include <openssl/core_names.h> #include <openssl/core_names.h>
#include <openssl/ec.h>
#include <openssl/evp.h> #include <openssl/evp.h>
#include <openssl/param_build.h> #include <openssl/param_build.h>
#include <openssl/pem.h> #include <openssl/pem.h>
#include <algorithm>
#include <array>
#include <filesystem>
#include <fstream> #include <fstream>
#include <regex>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <string_view>
#include <utility>
namespace Echoion::Protocol namespace Echoion::Protocol
{ {
@@ -28,6 +35,151 @@ namespace Echoion::Protocol
return static_cast<EVP_PKEY*>(p.get()); return static_cast<EVP_PKEY*>(p.get());
} }
struct ParsedPrivateKey {
BIGNUM* privateKey = nullptr;
BIGNUM* publicX = nullptr;
BIGNUM* publicY = nullptr;
~ParsedPrivateKey()
{
BN_free(privateKey);
BN_free(publicX);
BN_free(publicY);
}
ParsedPrivateKey() = default;
ParsedPrivateKey(const ParsedPrivateKey&) = delete;
ParsedPrivateKey& operator=(const ParsedPrivateKey&) = delete;
ParsedPrivateKey(ParsedPrivateKey&& other) noexcept
: privateKey(std::exchange(other.privateKey, nullptr)),
publicX(std::exchange(other.publicX, nullptr)),
publicY(std::exchange(other.publicY, nullptr))
{
}
};
size_t readDerLength(Crypto::ByteView der, size_t& position)
{
if (position >= der.size()) {
fail("truncated DER length");
}
const auto first = der[position++];
if (first < 0x80) {
return first;
}
const auto bytes = static_cast<size_t>(first & 0x7f);
if (bytes == 0 || bytes > sizeof(size_t) ||
position + bytes > der.size()) {
fail("invalid DER length");
}
size_t length = 0;
for (size_t i = 0; i < bytes; ++i) {
length = (length << 8) | der[position++];
}
return length;
}
ParsedPrivateKey parsePrivateKeyDer(Crypto::ByteView der)
{
if (der.empty() || der.front() != 0x30) {
fail("imported key is not a DER sequence");
}
size_t position = 1;
const auto sequenceLength = readDerLength(der, position);
if (position + sequenceLength != der.size()) {
fail("invalid imported key length");
}
uint8_t keyKind = 0;
std::vector<BIGNUM*> integers;
while (position < der.size()) {
const auto tag = der[position++];
const auto length = readDerLength(der, position);
if (position + length > der.size()) {
for (auto* value : integers) {
BN_free(value);
}
fail("truncated imported key");
}
if (tag == 0x03) {
if (length < 2) {
fail("invalid imported key flags");
}
keyKind = der[position + 1];
} else if (tag == 0x02) {
integers.push_back(BN_bin2bn(
der.data() + position, static_cast<int>(length), nullptr));
}
position += length;
}
ParsedPrivateKey parsed;
// INTEGER lists exclude the bit string. Public+private is
// [32, x, y, d]; private-only is [32, d].
if (keyKind == 0x80 && integers.size() == 4) {
parsed.publicX = integers[1];
parsed.publicY = integers[2];
parsed.privateKey = integers[3];
BN_free(integers[0]);
} else if (keyKind == 0xc0 && integers.size() == 2) {
parsed.privateKey = integers[1];
BN_free(integers[0]);
} else {
for (auto* value : integers) {
BN_free(value);
}
fail("unsupported imported identity key");
}
return parsed;
}
EVP_PKEY* makePrivateKey(ParsedPrivateKey& parsed)
{
std::array<uint8_t, 65> publicPoint{};
publicPoint[0] = 0x04;
if (!parsed.publicX || !parsed.publicY) {
EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
EC_POINT* point = group ? EC_POINT_new(group) : nullptr;
if (!group || !point ||
EC_POINT_mul(group, point, parsed.privateKey, nullptr, nullptr,
nullptr) != 1 ||
EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED,
publicPoint.data(), publicPoint.size(), nullptr) !=
publicPoint.size()) {
EC_POINT_free(point);
EC_GROUP_free(group);
fail("cannot derive imported public key");
}
EC_POINT_free(point);
EC_GROUP_free(group);
} else {
if (BN_bn2binpad(parsed.publicX, publicPoint.data() + 1, 32) != 32 ||
BN_bn2binpad(parsed.publicY, publicPoint.data() + 33, 32) != 32) {
fail("invalid imported public key");
}
}
OSSL_PARAM_BLD* builder = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME,
"prime256v1", 0);
OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY,
publicPoint.data(), publicPoint.size());
OSSL_PARAM_BLD_push_BN(builder, OSSL_PKEY_PARAM_PRIV_KEY,
parsed.privateKey);
OSSL_PARAM* params = OSSL_PARAM_BLD_to_param(builder);
EVP_PKEY_CTX* context =
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
EVP_PKEY* key = nullptr;
const bool ok = context && EVP_PKEY_fromdata_init(context) == 1 &&
EVP_PKEY_fromdata(context, &key, EVP_PKEY_KEYPAIR, params) == 1;
EVP_PKEY_CTX_free(context);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(builder);
if (!ok) {
fail("cannot construct imported private key");
}
return key;
}
// Minimal big-endian encoding of a BIGNUM (no leading zeros). // Minimal big-endian encoding of a BIGNUM (no leading zeros).
Bytes bnBytes(const BIGNUM* bn) Bytes bnBytes(const BIGNUM* bn)
{ {
@@ -199,6 +351,85 @@ namespace Echoion::Protocol
EVP_PKEY_free(static_cast<EVP_PKEY*>(p)); EVP_PKEY_free(static_cast<EVP_PKEY*>(p));
} }
Identity Identity::importTeamSpeakIni(const std::string& path)
{
std::ifstream input(path, std::ios::binary);
if (!input) {
fail("cannot open TeamSpeak identity export");
}
const std::string contents((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// TeamSpeak's exported value is <valid-key-offset>V<base64>. It may
// appear quoted or as the value of an INI property.
const std::regex pattern{R"((\d+)V([A-Za-z0-9+/]+={0,2}))"};
std::smatch match;
if (!std::regex_search(contents, match, pattern)) {
fail("TeamSpeak export does not contain an identity");
}
uint64_t offset = 0;
try {
offset = std::stoull(match[1].str());
} catch (const std::exception&) {
fail("invalid TeamSpeak key offset");
}
auto obfuscated = Util::base64Decode(match[2].str());
if (obfuscated.size() < 20) {
fail("TeamSpeak identity is too short");
}
const auto payloadBegin = obfuscated.begin() + 20;
const auto nullPosition =
std::find(payloadBegin, obfuscated.end(), uint8_t{0});
const auto hash = Crypto::sha1(Crypto::ByteView(
&*payloadBegin, static_cast<size_t>(nullPosition - payloadBegin)));
for (size_t i = 0; i < hash.size(); ++i) {
obfuscated[i] ^= hash[i];
}
constexpr std::string_view obfuscationKey =
"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802"
"01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e";
const auto xorLength = std::min(obfuscated.size(), size_t{100});
for (size_t i = 0; i < xorLength; ++i) {
obfuscated[i] ^= static_cast<uint8_t>(obfuscationKey[i]);
}
std::string encoded(obfuscated.begin(), obfuscated.end());
if (const auto nul = encoded.find('\0'); nul != std::string::npos) {
encoded.resize(nul);
}
const auto der = Util::base64Decode(encoded);
auto parsed = parsePrivateKeyDer(der);
EVP_PKEY* key = makePrivateKey(parsed);
EVP_PKEY_CTX* checkContext = EVP_PKEY_CTX_new(key, nullptr);
const bool valid = checkContext &&
EVP_PKEY_private_check(checkContext) == 1 &&
EVP_PKEY_pairwise_check(checkContext) == 1;
EVP_PKEY_CTX_free(checkContext);
if (!valid) {
EVP_PKEY_free(key);
fail("TeamSpeak identity key pair is inconsistent");
}
Identity identity;
identity.pkey_ = std::shared_ptr<void>(key, PKeyDeleter{});
const auto point = pubPoint(key);
if (point.size() != 65 || point.front() != 0x04) {
fail("unexpected imported public key format");
}
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
identity.publicKeyString_ = buildPublicKeyString(x, y);
BN_free(x);
BN_free(y);
identity.keyOffset_ = offset;
const auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(identity.publicKeyString_.data()),
identity.publicKeyString_.size()));
identity.uid_ = Util::base64Encode(uidHash);
return identity;
}
Identity Identity::generate(int securityLevel) Identity Identity::generate(int securityLevel)
{ {
EVP_PKEY* pkey = nullptr; EVP_PKEY* pkey = nullptr;
@@ -375,7 +606,9 @@ namespace Echoion::Protocol
std::string pem(data, static_cast<size_t>(n)); std::string pem(data, static_cast<size_t>(n));
BIO_free(mem); BIO_free(mem);
std::ofstream out(path, std::ios::trunc); const std::filesystem::path destination{path};
const auto temporary = destination.string() + ".tmp";
std::ofstream out(temporary, std::ios::binary | std::ios::trunc);
if (!out) { if (!out) {
fail("cannot open identity file for writing"); fail("cannot open identity file for writing");
} }
@@ -384,6 +617,22 @@ namespace Echoion::Protocol
out << publicKeyString_ << "\n"; out << publicKeyString_ << "\n";
out << "-----PRIVATE-----\n"; out << "-----PRIVATE-----\n";
out << pem; 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) Identity Identity::load(const std::string& path)
+234
View File
@@ -13,8 +13,12 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
#include <algorithm>
#include <array>
#include <chrono> #include <chrono>
#include <cstring> #include <cstring>
#include <filesystem>
#include <fstream>
#include <stdexcept> #include <stdexcept>
namespace Echoion::Protocol namespace Echoion::Protocol
@@ -122,6 +126,10 @@ namespace Echoion::Protocol
void TsClient::connect(const TsClientOptions& opts) void TsClient::connect(const TsClientOptions& opts)
{ {
if (thread_.joinable()) {
forceClose();
thread_.join();
}
std::lock_guard<std::recursive_mutex> lock(mu_); std::lock_guard<std::recursive_mutex> lock(mu_);
if (!opts.identity) { if (!opts.identity) {
throw std::runtime_error("TsClient: identity is required"); throw std::runtime_error("TsClient: identity is required");
@@ -352,6 +360,172 @@ namespace Echoion::Protocol
} }
} }
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<std::mutex> serialLock(requestSerialMutex_);
auto pending = std::make_shared<PendingRequest>();
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<std::recursive_mutex> sendLock(mu_);
if (state_.load() != ClientState::Connected) {
return {{}, -1, "client is not connected"};
}
{
std::lock_guard<std::mutex> pendingLock(pendingMutex_);
pendingRequests_.push_back(pending);
}
sendCommand(cmd + " return_code=" + pending->returnCode);
}
std::unique_lock<std::mutex> 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<long>(
std::max<int64_t>(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<size_t>(count);
}
if (!output || keySent != transferKey.size()) {
::close(transferSocket);
std::filesystem::remove(temporary);
return {{}, -1, "cannot start file transfer"};
}
std::array<char, 81920> 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<uint64_t>(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<const uint8_t> opus) void TsClient::sendVoice(std::span<const uint8_t> opus)
{ {
std::lock_guard<std::recursive_mutex> lock(mu_); std::lock_guard<std::recursive_mutex> lock(mu_);
@@ -660,6 +834,47 @@ namespace Echoion::Protocol
} }
const std::string& name = parsed.name; const std::string& name = parsed.name;
if (name == "error") {
std::shared_ptr<PendingRequest> pending;
{
std::lock_guard<std::mutex> 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<std::mutex> 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") { if (name == "initivexpand") {
handleInitIvExpand(parsed.params); handleInitIvExpand(parsed.params);
} else if (name == "initivexpand2") { } else if (name == "initivexpand2") {
@@ -963,6 +1178,7 @@ namespace Echoion::Protocol
if (sock_ >= 0) { if (sock_ >= 0) {
::shutdown(sock_, SHUT_RDWR); ::shutdown(sock_, SHUT_RDWR);
} }
cancelPendingRequests("connection closed");
} }
void TsClient::cleanup() void TsClient::cleanup()
@@ -972,9 +1188,27 @@ namespace Echoion::Protocol
} }
state_ = ClientState::Disconnected; state_ = ClientState::Disconnected;
running_ = false; running_ = false;
cancelPendingRequests("connection closed");
if (cb_.onDisconnected) { if (cb_.onDisconnected) {
cb_.onDisconnected(); cb_.onDisconnected();
} }
} }
void TsClient::cancelPendingRequests(const std::string& reason)
{
std::deque<std::shared_ptr<PendingRequest>> pending;
{
std::lock_guard<std::mutex> 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 } // namespace Echoion::Protocol
+73
View File
@@ -4,6 +4,8 @@
#include "echoion/protocol/Util.hpp" #include "echoion/protocol/Util.hpp"
#include <cstdio> #include <cstdio>
#include <filesystem>
#include <fstream>
#include <string> #include <string>
using namespace Echoion::Protocol; using namespace Echoion::Protocol;
@@ -50,3 +52,74 @@ TEST_CASE(identity_save_load_roundtrip)
CHECK_EQ(loaded.keyOffset(), id.keyOffset()); CHECK_EQ(loaded.keyOffset(), id.keyOffset());
std::remove(path.c_str()); std::remove(path.c_str());
} }
namespace
{
std::string teamSpeakExportForScalarOne(uint64_t offset)
{
// libtomcrypt private-only key: flags 0xc0, 256 bits, scalar d=1.
const std::vector<uint8_t> der{0x30, 0x0a, 0x03, 0x02, 0x06, 0xc0,
0x02, 0x01, 0x20, 0x02, 0x01, 0x01};
const auto decoded = Util::base64Encode(der);
std::vector<uint8_t> obfuscated(decoded.begin(), decoded.end());
constexpr std::string_view key =
"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802"
"01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e";
// Real exported identities are longer than 20 bytes. Pad the base64
// text with whitespace, which the decoder accepts, to exercise the
// exact TeamSpeak obfuscation algorithm.
obfuscated.resize(32, static_cast<uint8_t>(' '));
for (size_t i = 20; i < obfuscated.size(); ++i) {
obfuscated[i] ^= static_cast<uint8_t>(key[i]);
}
const auto hash = Crypto::sha1(Crypto::ByteView(
obfuscated.data() + 20, obfuscated.size() - 20));
for (size_t i = 0; i < 20; ++i) {
obfuscated[i] ^=
static_cast<uint8_t>(key[i]) ^ hash[i];
}
return std::to_string(offset) + "V" + Util::base64Encode(obfuscated);
}
}
TEST_CASE(identity_import_teamspeak_ini)
{
const std::string exportPath = "/tmp/echoion_ts_identity.ini";
const std::string nativePath = "/tmp/echoion_imported_identity.txt";
{
std::ofstream output(exportPath);
output << "[Identity]\nidentity=\"" << teamSpeakExportForScalarOne(42)
<< "\"\n";
}
const auto imported = Identity::importTeamSpeakIni(exportPath);
CHECK_EQ(imported.keyOffset(), uint64_t{42});
CHECK(!imported.uid().empty());
CHECK(!imported.sign({reinterpret_cast<const uint8_t*>("x"), 1}).empty());
imported.save(nativePath);
const auto loaded = Identity::load(nativePath);
CHECK_EQ(loaded.uid(), imported.uid());
const auto permissions = std::filesystem::status(nativePath).permissions();
CHECK((permissions & std::filesystem::perms::group_all) ==
std::filesystem::perms::none);
CHECK((permissions & std::filesystem::perms::others_all) ==
std::filesystem::perms::none);
std::remove(exportPath.c_str());
std::remove(nativePath.c_str());
}
TEST_CASE(identity_import_rejects_malformed_export)
{
const std::string path = "/tmp/echoion_bad_identity.ini";
{
std::ofstream output(path);
output << "[Identity]\nidentity=not-a-private-key\n";
}
bool rejected = false;
try {
(void)Identity::importTeamSpeakIni(path);
} catch (const std::exception&) {
rejected = true;
}
CHECK(rejected);
std::remove(path.c_str());
}
+17 -23
View File
@@ -1,9 +1,7 @@
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client. # EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
# #
# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load # It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core,
# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's # and implements IPluginInterface with EchoionProtocol's native UDP client.
# native UDP client. Built with PLUGIN=1 so it shares the plugin's minimal-API
# ABI contract with Core (self-contained ServerConfig, no ConfigTypes).
cmake_minimum_required(VERSION 4.0.0) cmake_minimum_required(VERSION 4.0.0)
project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX) project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX)
@@ -12,41 +10,25 @@ set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
# dylib for the Core hot-reload loader (same version the plugin uses).
CPMAddPackage(
NAME dylib
GITHUB_REPOSITORY martin-olivier/dylib
GIT_TAG "v3.0.1"
)
find_package(PkgConfig REQUIRED) find_package(PkgConfig REQUIRED)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil) pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil)
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
set(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin")
add_executable(EchoionStandalone add_executable(EchoionStandalone
src/main.cpp src/main.cpp
src/StandaloneClientInterface.cpp src/StandaloneClientInterface.cpp
src/AudioEncoder.cpp src/AudioEncoder.cpp
# Reused, TeamSpeak-independent loader from the plugin (transition shim; src/MessageChunker.cpp
# a shared EchoionHostCommon lib can extract these later).
"${PLUGIN_DIR}/src/CoreLoader.cpp"
"${PLUGIN_DIR}/src/FileWatcher.cpp"
) )
# PLUGIN=1 gives the self-contained ServerConfig + minimal API, matching the
# ABI Core was built against for the plugin path.
target_compile_definitions(EchoionStandalone PRIVATE PLUGIN=1)
target_include_directories(EchoionStandalone PRIVATE target_include_directories(EchoionStandalone PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include"
"${PLUGIN_DIR}/include"
) )
target_link_libraries(EchoionStandalone PRIVATE target_link_libraries(EchoionStandalone PRIVATE
Echoion::Protocol Echoion::Protocol
Echoion::Host
Echoion::ApiBase Echoion::ApiBase
Echoion::ApiPlugin Echoion::ApiPlugin
Echoion::ApiOpaque Echoion::ApiOpaque
@@ -56,7 +38,6 @@ target_link_libraries(EchoionStandalone PRIVATE
Void::Data Void::Data
Void::Log Void::Log
Void::Stacktrace Void::Stacktrace
dylib
Threads::Threads Threads::Threads
PkgConfig::SWRESAMPLE PkgConfig::SWRESAMPLE
PkgConfig::OPUS PkgConfig::OPUS
@@ -68,3 +49,16 @@ set_target_properties(EchoionStandalone PROPERTIES
) )
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin) install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
if(BUILD_TESTS)
add_executable(echoion_standalone_message_tests
tests/test_message_chunker.cpp
src/MessageChunker.cpp
)
target_include_directories(echoion_standalone_message_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20)
add_test(NAME echoion_standalone_message_tests
COMMAND echoion_standalone_message_tests)
endif()
@@ -0,0 +1,13 @@
#pragma once
#include <cstddef>
#include <string>
#include <vector>
namespace Echoion::Standalone
{
// Split TeamSpeak messages on UTF-8/line boundaries while preserving each
// complete markdown-it `:::details ... :::` container in one message.
[[nodiscard]] std::vector<std::string>
chunkMessage(const std::string& message, std::size_t limit = 900);
}
@@ -16,6 +16,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <thread>
#include <vector> #include <vector>
namespace Echoion::Standalone namespace Echoion::Standalone
@@ -28,6 +29,7 @@ namespace Echoion::Standalone
// required. // required.
struct StandaloneSettings { struct StandaloneSettings {
std::string identityPath; // where to load/persist the TS identity std::string identityPath; // where to load/persist the TS identity
std::string avatarCachePath;
int securityLevel = 8; int securityLevel = 8;
int opusBitrate = 96000; int opusBitrate = 96000;
}; };
@@ -48,6 +50,15 @@ namespace Echoion::Standalone
getClients() override; getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>> [[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override; getClient(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientIp(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarPath(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarUrl(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
requestClientAvatar(uint64_t clientId,
const std::string& destDir) override;
Api::Result<void> moveClient(uint64_t clientId, Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override; uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId, Api::Result<void> kickClient(uint64_t clientId,
@@ -96,6 +107,10 @@ namespace Echoion::Standalone
void broadcast(const Api::PluginEvent& event); void broadcast(const Api::PluginEvent& event);
void upsertClientGroup(const Protocol::CommandParams& p, void upsertClientGroup(const Protocol::CommandParams& p,
bool emitConnected); bool emitConnected);
void refreshClient(const Protocol::CommandParams& params);
void loadInitialSnapshot();
[[nodiscard]] Api::Result<void>
commandResult(const Protocol::CommandResult& result) const;
StandaloneSettings settings_; StandaloneSettings settings_;
std::unique_ptr<Protocol::Identity> identity_; std::unique_ptr<Protocol::Identity> identity_;
@@ -108,7 +123,12 @@ namespace Echoion::Standalone
mutable std::mutex mirrorMutex_; mutable std::mutex mirrorMutex_;
std::map<uint64_t, Api::ClientInfo> clients_; std::map<uint64_t, Api::ClientInfo> clients_;
std::map<uint64_t, Api::ChannelInfo> channels_; std::map<uint64_t, Api::ChannelInfo> channels_;
std::map<uint64_t, std::string> clientIps_;
std::map<uint64_t, std::string> avatarHashes_;
std::map<uint64_t, std::string> avatarUrls_;
std::map<uint64_t, std::string> avatarPaths_;
std::vector<uint64_t> whisperList_; std::vector<uint64_t> whisperList_;
std::jthread snapshotThread_;
std::mutex cbMutex_; std::mutex cbMutex_;
std::vector<Api::EventCallback> callbacks_; std::vector<Api::EventCallback> callbacks_;
+86
View File
@@ -0,0 +1,86 @@
#include "echoion/standalone/MessageChunker.hpp"
#include <string_view>
namespace Echoion::Standalone
{
std::vector<std::string> chunkMessage(const std::string& message,
std::size_t limit)
{
if (limit == 0 || message.empty()) {
return message.empty() ? std::vector<std::string>{}
: std::vector<std::string>{message};
}
if (message.size() <= limit) {
return {message};
}
const auto isBlank = [](const std::string& value) {
return value.find_first_not_of(" \t\r\n") == std::string::npos;
};
std::vector<std::string> chunks;
std::string current;
int detailsDepth = 0;
const auto flush = [&] {
if (!current.empty() && !isBlank(current)) {
chunks.push_back(current);
}
current.clear();
};
std::size_t position = 0;
while (position < message.size()) {
const auto newline = message.find('\n', position);
std::string line = newline == std::string::npos
? message.substr(position)
: message.substr(position, newline - position + 1);
position = newline == std::string::npos ? message.size() : newline + 1;
const bool opens = line.starts_with(":::details");
std::string_view trimmed = line;
while (!trimmed.empty() &&
(trimmed.back() == '\n' || trimmed.back() == '\r' ||
trimmed.back() == ' ' || trimmed.back() == '\t')) {
trimmed.remove_suffix(1);
}
const bool closes = trimmed == ":::";
if (detailsDepth == 0 && !current.empty() &&
(opens || current.size() + line.size() > limit)) {
flush();
}
// A details block must remain syntactically complete even if it is
// longer than the preferred message limit. Normal lines are split at
// a UTF-8 code-point boundary.
if (detailsDepth == 0 && !opens) {
while (line.size() > limit) {
std::size_t cut = limit;
while (cut > 0 &&
(static_cast<unsigned char>(line[cut]) & 0xc0) == 0x80) {
--cut;
}
if (cut == 0) {
cut = limit;
}
flush();
auto piece = line.substr(0, cut);
if (!isBlank(piece)) {
chunks.push_back(std::move(piece));
}
line.erase(0, cut);
}
}
current += line;
if (opens) {
++detailsDepth;
}
if (closes && detailsDepth > 0) {
--detailsDepth;
}
}
flush();
return chunks;
}
}
@@ -1,12 +1,16 @@
#include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp"
#include "echoion/standalone/AudioEncoder.hpp" #include "echoion/standalone/AudioEncoder.hpp"
#include "echoion/standalone/MessageChunker.hpp"
#include "echoion/protocol/Command.hpp" #include "echoion/protocol/Command.hpp"
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <algorithm>
#include <chrono> #include <chrono>
#include <filesystem> #include <filesystem>
#include <limits>
#include <sstream>
namespace Echoion::Standalone namespace Echoion::Standalone
{ {
@@ -28,6 +32,26 @@ namespace Echoion::Standalone
auto it = p.find(k); auto it = p.find(k);
return it == p.end() ? std::string{} : it->second; return it == p.end() ? std::string{} : it->second;
} }
bool isTrue(const std::string& value)
{
return value == "1" || value == "true";
}
std::vector<uint64_t> parseIds(const std::string& value)
{
std::vector<uint64_t> result;
std::istringstream input(value);
std::string item;
while (std::getline(input, item, ',')) {
const auto id = toU64(item);
if (id != 0) {
result.push_back(id);
}
}
return result;
}
} // namespace } // namespace
StandaloneClientInterface::StandaloneClientInterface( StandaloneClientInterface::StandaloneClientInterface(
@@ -59,6 +83,12 @@ namespace Echoion::Standalone
} }
if (client_) { if (client_) {
client_->forceClose(); client_->forceClose();
}
if (snapshotThread_.joinable()) {
snapshotThread_.request_stop();
snapshotThread_.join();
}
if (client_) {
client_.reset(); client_.reset();
} }
encoder_.reset(); encoder_.reset();
@@ -129,15 +159,20 @@ namespace Echoion::Standalone
{ {
Protocol::TsClientCallbacks cb; Protocol::TsClientCallbacks cb;
cb.onConnected = [this] { cb.onConnected = [this] {
// Ask the server to reveal all clients so the presence mirror fills. if (snapshotThread_.joinable()) {
client_->sendCommand("channelsubscribeall"); snapshotThread_.request_stop();
Api::PluginEvent ev; snapshotThread_.join();
ev.type = Api::PluginEventType::ConnectionEstablished; }
ev.timestamp = std::chrono::system_clock::now(); snapshotThread_ = std::jthread([this] { loadInitialSnapshot(); });
broadcast(ev);
}; };
cb.onDisconnected = [this] { cb.onDisconnected = [this] {
Void::Log::warn(LOG, "Disconnected from server"); Void::Log::warn(LOG, "Disconnected from server");
std::lock_guard<std::mutex> lock(mirrorMutex_);
clients_.clear();
channels_.clear();
clientIps_.clear();
avatarHashes_.clear();
avatarUrls_.clear();
}; };
cb.onError = [](const std::string& msg) { cb.onError = [](const std::string& msg) {
Void::Log::error(LOG, "Protocol error: {}", msg); Void::Log::error(LOG, "Protocol error: {}", msg);
@@ -151,9 +186,60 @@ namespace Echoion::Standalone
cb.onDebug = [](const std::string& msg) { cb.onDebug = [](const std::string& msg) {
Void::Log::debug(LOG, "{}", msg); Void::Log::debug(LOG, "{}", msg);
}; };
cb.onVoice = [this](std::span<const uint8_t>) {
Api::PluginEvent event;
event.type = Api::PluginEventType::VoiceDataReceived;
event.timestamp = std::chrono::system_clock::now();
broadcast(event);
};
client_->setCallbacks(std::move(cb)); client_->setCallbacks(std::move(cb));
} }
Api::Result<void> StandaloneClientInterface::commandResult(
const Protocol::CommandResult& result) const
{
if (result.ok()) {
return {};
}
return Api::fail(Api::ErrorCode::NetworkError,
"TeamSpeak error " + std::to_string(result.errorId) + ": " +
result.errorMessage);
}
void StandaloneClientInterface::loadInitialSnapshot()
{
if (!client_) {
return;
}
auto clients = client_->requestCommand(
"clientlist -uid -groups -voice -away -times -info -country -ip");
if (clients.ok()) {
for (const auto& record : clients.records) {
refreshClient(record);
}
} else {
Void::Log::warn(LOG, "Initial client snapshot failed: {}",
clients.errorMessage);
}
auto channels = client_->requestCommand(
"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});
} else {
Void::Log::warn(LOG, "Initial channel snapshot failed: {}",
channels.errorMessage);
}
client_->sendCommand("channelsubscribeall");
Api::PluginEvent event;
event.type = Api::PluginEventType::ConnectionEstablished;
event.timestamp = std::chrono::system_clock::now();
broadcast(event);
}
Api::Result<void> StandaloneClientInterface::disconnectFromServer() Api::Result<void> StandaloneClientInterface::disconnectFromServer()
{ {
if (client_) { if (client_) {
@@ -187,19 +273,11 @@ namespace Echoion::Standalone
{ {
std::lock_guard<std::mutex> lock(mirrorMutex_); std::lock_guard<std::mutex> lock(mirrorMutex_);
info = clients_[clid]; info = clients_[clid];
info.id = clid; }
if (auto n = get(p, "client_nickname"); !n.empty()) { refreshClient(p);
info.nickname = n; {
} std::lock_guard<std::mutex> lock(mirrorMutex_);
if (auto u = get(p, "client_unique_identifier"); !u.empty()) { info = clients_[clid];
info.uniqueIdentifier = u;
}
if (auto c = get(p, "ctid"); !c.empty()) {
info.channelId = toU64(c);
} else if (auto cid = get(p, "cid"); !cid.empty()) {
info.channelId = toU64(cid);
}
clients_[clid] = info;
} }
if (emitConnected) { if (emitConnected) {
Api::PluginEvent ev; Api::PluginEvent ev;
@@ -211,6 +289,63 @@ namespace Echoion::Standalone
} }
} }
void StandaloneClientInterface::refreshClient(
const Protocol::CommandParams& params)
{
const auto idText = !get(params, "clid").empty()
? get(params, "clid")
: get(params, "client_id");
const auto clientId = toU64(idText);
if (clientId == 0) {
return;
}
std::lock_guard<std::mutex> lock(mirrorMutex_);
auto& info = clients_[clientId];
info.id = clientId;
if (const auto value = get(params, "client_nickname"); !value.empty()) {
info.nickname = value;
}
if (const auto value = get(params, "client_unique_identifier");
!value.empty()) {
info.uniqueIdentifier = value;
}
if (const auto value = get(params, "ctid"); !value.empty()) {
info.channelId = toU64(value);
} else if (const auto value = get(params, "cid"); !value.empty()) {
info.channelId = toU64(value);
}
if (const auto value = get(params, "client_servergroups");
!value.empty()) {
info.serverGroups = parseIds(value);
}
if (const auto value = get(params, "client_input_muted"); !value.empty()) {
info.isMuted = isTrue(value);
}
if (const auto value = get(params, "client_output_muted"); !value.empty()) {
info.isDeafened = isTrue(value);
}
if (const auto value = get(params, "client_flag_talking"); !value.empty()) {
info.isTalking = isTrue(value);
} else if (const auto value = get(params, "status"); !value.empty()) {
info.isTalking = isTrue(value);
}
if (const auto value = get(params, "connection_client_ip"); !value.empty()) {
clientIps_[clientId] = value;
}
if (const auto value = get(params, "client_flag_avatar"); !value.empty()) {
avatarHashes_[clientId] = value;
}
const auto avatar = !get(params, "client_myteamspeak_avatar").empty()
? get(params, "client_myteamspeak_avatar")
: get(params, "client_myts_avatar");
if (const auto comma = avatar.find(','); comma != std::string::npos) {
const auto url = avatar.substr(comma + 1);
if (url.starts_with("https://") || url.starts_with("http://")) {
avatarUrls_[clientId] = url;
}
}
}
void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p) void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p)
{ {
const auto& groups = const auto& groups =
@@ -218,9 +353,11 @@ namespace Echoion::Standalone
? std::vector<Protocol::CommandParams>{p.params} ? std::vector<Protocol::CommandParams>{p.params}
: p.groups; : p.groups;
if (p.name == "notifycliententerview") { if (p.name == "notifycliententerview" || p.name == "clientlist" ||
p.name == "clientinfo" || p.name == "notifyclientupdated" ||
p.name == "notifytalkstatuschange") {
for (const auto& g : groups) { for (const auto& g : groups) {
upsertClientGroup(g, true); upsertClientGroup(g, p.name == "notifycliententerview");
} }
} else if (p.name == "notifyclientleftview") { } else if (p.name == "notifyclientleftview") {
for (const auto& g : groups) { for (const auto& g : groups) {
@@ -263,7 +400,15 @@ namespace Echoion::Standalone
ev.timestamp = std::chrono::system_clock::now(); ev.timestamp = std::chrono::system_clock::now();
broadcast(ev); broadcast(ev);
} }
} else if (p.name == "channellist" || p.name == "notifychannellist") { } else if (p.name == "notifychanneldeleted") {
std::lock_guard<std::mutex> lock(mirrorMutex_);
for (const auto& group : groups) {
channels_.erase(toU64(get(group, "cid")));
}
} else if (p.name == "channellist" || p.name == "notifychannellist" ||
p.name == "notifychannelcreated" ||
p.name == "notifychanneledited" ||
p.name == "notifychannelmoved") {
std::lock_guard<std::mutex> lock(mirrorMutex_); std::lock_guard<std::mutex> lock(mirrorMutex_);
for (const auto& g : groups) { for (const auto& g : groups) {
uint64_t cid = toU64(get(g, "cid")); uint64_t cid = toU64(get(g, "cid"));
@@ -276,8 +421,17 @@ namespace Echoion::Standalone
ch.name = n; ch.name = n;
} }
if (auto pid = get(g, "pid"); !pid.empty()) { if (auto pid = get(g, "pid"); !pid.empty()) {
ch.parentId = toU64(pid); const auto parent = toU64(pid);
ch.parentId = parent == 0 ? std::optional<uint64_t>{}
: std::optional<uint64_t>{parent};
} }
ch.order = toU64(get(g, "channel_order"));
ch.isDefault = isTrue(get(g, "channel_flag_default"));
ch.hasPassword = isTrue(get(g, "channel_flag_password"));
ch.maxClients = static_cast<uint32_t>(
toU64(get(g, "channel_maxclients")));
ch.currentClients = static_cast<uint32_t>(
toU64(get(g, "total_clients")));
channels_[cid] = ch; channels_[cid] = ch;
} }
} }
@@ -339,6 +493,124 @@ namespace Echoion::Standalone
return std::optional<Api::ClientInfo>{it->second}; return std::optional<Api::ClientInfo>{it->second};
} }
Api::Result<std::optional<std::string>>
StandaloneClientInterface::getClientIp(uint64_t clientId)
{
if (!client_ || !isConnected()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
}
Protocol::CommandParams 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));
}
if (!result.ok()) {
return Api::fail(Api::ErrorCode::NetworkError, result.errorMessage);
}
for (const auto& record : result.records) {
refreshClient(record);
}
std::lock_guard<std::mutex> lock(mirrorMutex_);
const auto entry = clientIps_.find(clientId);
return entry == clientIps_.end()
? std::optional<std::string>{}
: std::optional<std::string>{entry->second};
}
Api::Result<std::optional<std::string>>
StandaloneClientInterface::getClientAvatarPath(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
const auto entry = avatarPaths_.find(clientId);
if (entry == avatarPaths_.end() ||
!std::filesystem::exists(entry->second)) {
return std::optional<std::string>{};
}
return std::optional<std::string>{entry->second};
}
Api::Result<std::optional<std::string>>
StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId)
{
if (client_ && isConnected()) {
Protocol::CommandParams 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) {
refreshClient(record);
}
}
}
std::lock_guard<std::mutex> lock(mirrorMutex_);
const auto entry = avatarUrls_.find(clientId);
return entry == avatarUrls_.end()
? std::optional<std::string>{}
: std::optional<std::string>{entry->second};
}
Api::Result<std::optional<std::string>>
StandaloneClientInterface::requestClientAvatar(uint64_t clientId,
const std::string& destDir)
{
if (!client_ || !isConnected()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
}
Protocol::CommandParams 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);
}
for (const auto& record : info.records) {
refreshClient(record);
}
std::string hash;
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
if (const auto entry = avatarHashes_.find(clientId);
entry != avatarHashes_.end()) {
hash = entry->second;
}
}
if (hash.empty()) {
return std::optional<std::string>{};
}
if (hash.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") !=
std::string::npos) {
return Api::fail(Api::ErrorCode::ParseError,
"server returned an unsafe avatar hash");
}
const auto directory = destDir.empty() ? settings_.avatarCachePath : destDir;
std::error_code directoryError;
std::filesystem::create_directories(directory, directoryError);
if (directoryError) {
return Api::fail(Api::ErrorCode::PluginError,
"cannot create avatar cache directory");
}
const auto destination =
(std::filesystem::path(directory) / ("avatar_" + hash)).string();
if (!std::filesystem::exists(destination)) {
const auto result =
client_->downloadFile("/avatar_" + hash, destination);
if (!result.ok()) {
return Api::fail(Api::ErrorCode::NetworkError,
result.errorMessage);
}
}
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
avatarPaths_[clientId] = destination;
}
return std::optional<std::string>{destination};
}
Api::Result<std::vector<Api::ChannelInfo>> Api::Result<std::vector<Api::ChannelInfo>>
StandaloneClientInterface::getChannels() const StandaloneClientInterface::getChannels() const
{ {
@@ -371,8 +643,8 @@ namespace Echoion::Standalone
Protocol::CommandParams p; Protocol::CommandParams p;
p["clid"] = std::to_string(clientId); p["clid"] = std::to_string(clientId);
p["cid"] = std::to_string(channelId); p["cid"] = std::to_string(channelId);
client_->sendCommand(Protocol::buildCommand("clientmove", p)); return commandResult(
return {}; client_->requestCommand(Protocol::buildCommand("clientmove", p)));
} }
Api::Result<void> Api::Result<void>
@@ -386,8 +658,8 @@ namespace Echoion::Standalone
p["clid"] = std::to_string(clientId); p["clid"] = std::to_string(clientId);
p["reasonid"] = "5"; // kick from server p["reasonid"] = "5"; // kick from server
p["reasonmsg"] = reason; p["reasonmsg"] = reason;
client_->sendCommand(Protocol::buildCommand("clientkick", p)); return commandResult(
return {}; client_->requestCommand(Protocol::buildCommand("clientkick", p)));
} }
// ---- Messaging --------------------------------------------------------- // ---- Messaging ---------------------------------------------------------
@@ -399,11 +671,20 @@ namespace Echoion::Standalone
if (!client_) { if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
} }
Protocol::CommandParams p; for (const auto& chunk : chunkMessage(message)) {
p["targetmode"] = "1"; // client Protocol::CommandParams p;
p["target"] = std::to_string(targetId); p["targetmode"] = "1"; // client
p["msg"] = message; p["target"] = std::to_string(targetId);
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); p["msg"] = chunk;
if (auto result = commandResult(client_->requestCommand(
Protocol::buildCommand("sendtextmessage", p)));
!result) {
Void::Log::warn(LOG,
"Failed to send help/reply chunk ({} bytes): {}",
chunk.size(), result.error().message);
return result;
}
}
return {}; return {};
} }
@@ -418,8 +699,8 @@ namespace Echoion::Standalone
p["targetmode"] = "2"; // channel p["targetmode"] = "2"; // channel
p["target"] = std::to_string(channelId); p["target"] = std::to_string(channelId);
p["msg"] = message; p["msg"] = message;
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); return commandResult(client_->requestCommand(
return {}; Protocol::buildCommand("sendtextmessage", p)));
} }
Api::Result<void> Api::Result<void>
@@ -431,8 +712,8 @@ namespace Echoion::Standalone
Protocol::CommandParams p; Protocol::CommandParams p;
p["targetmode"] = "3"; // server p["targetmode"] = "3"; // server
p["msg"] = message; p["msg"] = message;
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); return commandResult(client_->requestCommand(
return {}; Protocol::buildCommand("sendtextmessage", p)));
} }
// ---- Audio ------------------------------------------------------------- // ---- Audio -------------------------------------------------------------
@@ -442,7 +723,7 @@ namespace Echoion::Standalone
{ {
if (!client_ || !encoder_ || if (!client_ || !encoder_ ||
client_->state() != Protocol::ClientState::Connected) { client_->state() != Protocol::ClientState::Connected) {
return {}; return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected");
} }
std::vector<uint64_t> whisper; std::vector<uint64_t> whisper;
{ {
@@ -468,6 +749,12 @@ namespace Echoion::Standalone
Api::Result<void> StandaloneClientInterface::setWhisperList( Api::Result<void> StandaloneClientInterface::setWhisperList(
const std::vector<uint64_t>& clientIds) const std::vector<uint64_t>& clientIds)
{ {
if (std::ranges::any_of(clientIds, [](uint64_t clientId) {
return clientId > std::numeric_limits<uint16_t>::max();
})) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"whisper client ID exceeds protocol range");
}
std::lock_guard<std::mutex> lock(mirrorMutex_); std::lock_guard<std::mutex> lock(mirrorMutex_);
whisperList_ = clientIds; whisperList_ = clientIds;
return {}; return {};
+70 -4
View File
@@ -6,7 +6,8 @@
// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no // TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no
// TeamSpeak client, no Weston/RDP, no plugin directory. // TeamSpeak client, no Weston/RDP, no plugin directory.
#include "echoion/plugin/CoreLoader.hpp" #include "echoion/host/CoreLoader.hpp"
#include "echoion/protocol/Identity.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp"
#include <CoreInterface.hpp> #include <CoreInterface.hpp>
@@ -22,7 +23,9 @@
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional>
#include <string> #include <string>
#include <string_view>
namespace namespace
{ {
@@ -80,6 +83,62 @@ namespace
} }
return "./Echoion.ts"; return "./Echoion.ts";
} }
int importIdentity(int argc, char** argv,
const std::filesystem::path& defaultIdentityPath)
{
std::optional<std::filesystem::path> source;
auto destination = defaultIdentityPath;
bool force = false;
bool importRequested = false;
for (int i = 1; i < argc; ++i) {
const std::string_view argument{argv[i]};
if (argument == "--help") {
std::cout
<< "Usage: echoiond [--config PATH]\n"
" echoiond --import-identity EXPORT.ini "
"[--identity-path PATH] [--force]\n";
return 0;
}
if (argument == "--import-identity") {
importRequested = true;
if (i + 1 < argc &&
!std::string_view{argv[i + 1]}.starts_with("--")) {
source = argv[++i];
}
} else if (argument == "--identity-path" && i + 1 < argc) {
destination = argv[++i];
} else if (argument == "--force") {
force = true;
}
}
if (!importRequested) {
return -1;
}
if (!source) {
std::cerr << "--import-identity requires an exported INI path.\n";
return 2;
}
try {
if (std::filesystem::exists(destination) && !force) {
std::cerr << "Identity already exists at " << destination
<< "; pass --force to replace it.\n";
return 2;
}
const auto identity =
Echoion::Protocol::Identity::importTeamSpeakIni(source->string());
if (const auto parent = destination.parent_path(); !parent.empty()) {
std::filesystem::create_directories(parent);
}
identity.save(destination.string());
std::cout << "Imported TeamSpeak identity " << identity.uid()
<< " to " << destination << '\n';
return 0;
} catch (const std::exception& error) {
std::cerr << "Identity import failed: " << error.what() << '\n';
return 2;
}
}
} // namespace } // namespace
int main(int argc, char** argv) int main(int argc, char** argv)
@@ -92,6 +151,12 @@ int main(int argc, char** argv)
std::filesystem::path cfgDir = configDir(); std::filesystem::path cfgDir = configDir();
std::filesystem::path cfgPath = cfgDir / "config.json"; std::filesystem::path cfgPath = cfgDir / "config.json";
const auto identityPath = std::filesystem::path(envOr(
"ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()));
if (const auto importResult = importIdentity(argc, argv, identityPath);
importResult >= 0) {
return importResult;
}
// Optional CLI: --config <path> // Optional CLI: --config <path>
for (int i = 1; i + 1 < argc; ++i) { for (int i = 1; i + 1 < argc; ++i) {
if (std::string(argv[i]) == "--config") { if (std::string(argv[i]) == "--config") {
@@ -100,8 +165,8 @@ int main(int argc, char** argv)
} }
Echoion::Standalone::StandaloneSettings settings; Echoion::Standalone::StandaloneSettings settings;
settings.identityPath = settings.identityPath = identityPath.string();
envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()); settings.avatarCachePath = (cfgDir / "avatars").string();
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
@@ -113,7 +178,7 @@ int main(int argc, char** argv)
return 1; return 1;
} }
Echoion::Plugin::CoreLoader loader; Echoion::Host::CoreLoader loader;
loader.setConfigPath(cfgPath); loader.setConfigPath(cfgPath);
auto corePathResolved = corePath(); auto corePathResolved = corePath();
@@ -137,6 +202,7 @@ int main(int argc, char** argv)
loader.setHotReloadCallback([&loader, interface] { loader.setHotReloadCallback([&loader, interface] {
if (auto c = loader.getCore()) { if (auto c = loader.getCore()) {
c->setPluginInterface(interface); c->setPluginInterface(interface);
interface->unregisterEventCallback({});
interface->registerEventCallback( interface->registerEventCallback(
[c](const Echoion::Api::PluginEvent& ev) { [c](const Echoion::Api::PluginEvent& ev) {
std::ignore = c->onPluginEvent(ev); std::ignore = c->onPluginEvent(ev);
@@ -0,0 +1,41 @@
#include "echoion/standalone/MessageChunker.hpp"
#include <iostream>
#include <string>
namespace
{
bool check(bool condition, const char* message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
}
return condition;
}
}
int main()
{
using Echoion::Standalone::chunkMessage;
bool passed = true;
const std::string header = "# Help\n\n> [!TIP] Prefix is `!`\n\n";
const std::string details =
":::details ▶ Play — commands\n\n" + std::string(1100, 'x') +
"\n\n`!play` query\n> description\n:::\n\n";
const auto helpChunks = chunkMessage(header + details, 900);
passed &= check(helpChunks.size() == 2,
"help header and details block should be separate messages");
passed &= check(helpChunks.size() > 1 &&
helpChunks[1] == details.substr(0, details.size() - 1),
"details container must remain complete even above the limit");
const std::string utf8Line = std::string(899, 'a') + "я" + "tail";
const auto utf8Chunks = chunkMessage(utf8Line, 900);
passed &= check(utf8Chunks.size() == 2,
"long ordinary line should be split");
passed &= check(!utf8Chunks.empty() && utf8Chunks.front().size() == 899,
"UTF-8 sequence should not be split in the middle");
return passed ? 0 : 1;
}
+31 -16
View File
@@ -27,7 +27,7 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
- Qt6 (for desktop client) - Qt6 (for desktop client)
- FFmpeg (for audio decoding) - FFmpeg (for audio decoding)
- Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url) - Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url)
- TeamSpeak 3 Client SDK - OpenSSL, libsodium, Opus, FFmpeg, and Boost development packages
### Build Instructions ### Build Instructions
@@ -44,10 +44,8 @@ cmake .. -DBUILD_TESTS=ON
cmake --build . && ctest cmake --build . && ctest
``` ```
The suite covers the decoder (against generated audio fixtures), the queue The protocol suite covers command escaping/parsing, packet crypto, QuickLZ,
and shuffle bookkeeping, the gapless playback engine (asserting a seamless identity generation and persistence, and TeamSpeak identity-export import.
track boundary), and the source router (fall-through, hedging and stream
caching).
## Configuration ## Configuration
@@ -72,13 +70,24 @@ Edit the configuration file with your server details:
## Installation ## Installation
### TeamSpeak Plugin ### Standalone daemon
1. Build the project 1. Build the project and install `echoiond` together with `Echoion.ts`.
2. Copy the plugin to your TeamSpeak plugins folder: 2. Copy `systemd/echoion-standalone.service` to your user systemd directory,
- **Linux**: `~/.ts3client/plugins/` adjust its paths, and enable it.
- **Windows**: `%APPDATA%\TS3Client\plugins\` 3. On first start, Echoion generates `~/.config/echoion/identity.txt`.
3. Enable the plugin in TeamSpeak's plugins menu
To preserve the permissions and UID of an existing TeamSpeak client identity,
export it from TeamSpeak's Identity Manager and import it before first start:
```bash
echoiond --import-identity identity.ini
# Choose a non-default destination or replace an existing identity explicitly:
echoiond --import-identity identity.ini --identity-path /path/to/identity.txt --force
```
The identity file contains a private key. Keep both the TeamSpeak export and
the converted file private.
## Commands ## Commands
@@ -111,21 +120,27 @@ All commands use the configured prefix (default: `!`)
## Architecture ## Architecture
The bot consists of three main components: The supported runtime consists of four main components:
1. **EchoionApi** - Shared interfaces and types 1. **EchoionApi** - Shared interfaces and types
2. **EchoionCore** - Core music playback logic (hot-reloadable) 2. **EchoionCore** - Core music playback logic (hot-reloadable)
3. **EchoionPlugin** - TeamSpeak plugin wrapper 3. **EchoionProtocol** - Native TeamSpeak UDP voice and command protocol
4. **EchoionStandalone** - Daemon host and Core API adapter
`EchoionPlugin` is archived compatibility code. It is excluded from normal
builds and packages; use `-DBUILD_PLUGIN=ON` only when maintaining the legacy
TeamSpeak client integration.
### Audio Flow ### Audio Flow
``` ```
query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → PlaybackEngine query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → PlaybackEngine
(dual AudioDecoder, gapless handoff) → Core → PluginInterface → TeamSpeak (dual AudioDecoder, gapless handoff) → Core → Standalone interface
→ EchoionProtocol → TeamSpeak
``` ```
Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to
TeamSpeak's custom audio device by a single real-time engine thread. See TeamSpeak's Opus voice protocol by a single real-time engine thread. See
`docs/09-audio-pipeline.md` for details. `docs/09-audio-pipeline.md` for details.
## Development ## Development
@@ -135,7 +150,7 @@ TeamSpeak's custom audio device by a single real-time engine thread. See
The core library can be hot-reloaded without disconnecting from the server: The core library can be hot-reloaded without disconnecting from the server:
1. Build the new core: `cmake --build . --target EchoionCore` 1. Build the new core: `cmake --build . --target EchoionCore`
2. Use the "Reload Core" menu item or send plugin command `reload` 2. Replace `Echoion.ts`; the daemon's host watcher reloads it automatically.
### Adding Commands ### Adding Commands
+9 -10
View File
@@ -1,16 +1,15 @@
# TeamSpeak Echoion Bot - Systemd Service # Echoion Standalone - Systemd Service
This directory contains systemd service files and scripts for running TeamSpeak 3 client with Echoion bot in headless mode using Weston Wayland compositor with RDP backend. The supported service is `echoion-standalone.service`. It runs `echoiond`
directly; no graphical TeamSpeak client, Weston session, or plugin directory is
required.
## Files ## Supported service
- `teamspeak-echoion.service` - System-wide systemd service (runs as root/system) - `echoion-standalone.service` - User service for the standalone daemon.
- `teamspeak-echoion-user.service` - User systemd service (runs as user)
- `run-teamspeak-headless.sh` - Wrapper script for manual execution The `teamspeak-echoion*.service` files and GUI/headless helper scripts remain
- `install-service.sh` - Installation script only as archived compatibility material for `BUILD_PLUGIN=ON` deployments.
- `start-echoion.sh` - Quick start helper script (handles DBus session issues)
- `diagnose-echoion.sh` - Diagnostic tool for troubleshooting
- `start-with-tmux.sh` - Alternative startup using tmux
## Prerequisites ## Prerequisites
+2
View File
@@ -9,6 +9,8 @@
# #
# Identity is generated on first run and persisted to # Identity is generated on first run and persisted to
# ~/.config/echoion/identity.txt (override with ECHOION_IDENTITY_PATH). # ~/.config/echoion/identity.txt (override with ECHOION_IDENTITY_PATH).
# Import an existing TeamSpeak-exported identity before enabling the service:
# echoiond --import-identity identity.ini
[Unit] [Unit]
Description=Echoion Music Bot (standalone TeamSpeak client) Description=Echoion Music Bot (standalone TeamSpeak client)