feat/standalone-ts-client #1

Merged
faumaray merged 3 commits from feat/standalone-ts-client into main 2026-07-11 12:10:05 +00:00
31 changed files with 4257 additions and 0 deletions

No files matched your search

+13
View File
@@ -106,6 +106,8 @@ option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build EchoionPlugin" ON)
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)
@@ -144,6 +146,17 @@ 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()
# EchoionStandalone: reuses the plugin's CoreLoader, so it needs EchoionPlugin's
# sources present. It links the Api + EchoionProtocol and loads Core at runtime.
if(BUILD_STANDALONE)
add_subdirectory(EchoionStandalone)
endif()
if(BUILD_DESKTOP)
add_subdirectory(EchoionDesktop)
endif()
+49
View File
@@ -0,0 +1,49 @@
# EchoionProtocol — reverse-engineered TeamSpeak 3/6 full-client voice protocol.
#
# Deliberately dependency-isolated: it knows nothing about Echoion::Api, Void or
# reflection. It links only OpenSSL (crypto), libopus (voice) and a vendored
# QuickLZ. This keeps it independently unit-testable and reusable, and lets it
# build with a plain C++20 toolchain even though the rest of Echoion needs
# C++26/reflection.
cmake_minimum_required(VERSION 3.24)
# Allow standalone configuration (own build) as well as add_subdirectory() from
# the Echoion root.
if(NOT DEFINED PROJECT_NAME)
project(EchoionProtocol LANGUAGES CXX)
endif()
option(ECHOIONPROTOCOL_BUILD_TESTS "Build EchoionProtocol unit tests" OFF)
find_package(OpenSSL REQUIRED)
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(OPUS IMPORTED_TARGET opus)
# libsodium provides the raw Ed25519 point arithmetic the TS6 license chain
# (initivexpand2) needs; OpenSSL cannot do it.
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
endif()
file(GLOB ECHOIONPROTOCOL_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
add_library(EchoionProtocol STATIC ${ECHOIONPROTOCOL_SOURCES})
add_library(Echoion::Protocol ALIAS EchoionProtocol)
target_include_directories(EchoionProtocol
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
# This target is standalone C++20 on purpose — do not inherit the tree's C++26.
target_compile_features(EchoionProtocol PUBLIC cxx_std_20)
target_link_libraries(EchoionProtocol PUBLIC OpenSSL::Crypto PkgConfig::SODIUM)
if(TARGET PkgConfig::OPUS)
target_link_libraries(EchoionProtocol PUBLIC PkgConfig::OPUS)
target_compile_definitions(EchoionProtocol PUBLIC ECHOION_HAVE_OPUS=1)
endif()
if(ECHOIONPROTOCOL_BUILD_TESTS OR BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
+47
View File
@@ -0,0 +1,47 @@
# 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.
@@ -0,0 +1,36 @@
#pragma once
// TS3 command wire format: "commandname key=value key=value|key=value".
// Ported from ts6-manager tslib/commands.ts.
#include <map>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
// Escape / unescape a single token per the TS3 rules
// (\\ \/ \s \p \f \n \r \t \v).
std::string tsEscape(const std::string& str);
std::string tsUnescape(const std::string& str);
// Ordered key/value params for a command. std::map keeps a stable order so
// serialization is deterministic (helpful for tests); the server does not
// care about ordering.
using CommandParams = std::map<std::string, std::string>;
struct ParsedCommand {
std::string name;
CommandParams params; // first group
std::vector<CommandParams> groups; // all '|'-separated groups
};
// Serialize "name k=v k=v". Empty values are emitted as "k=".
std::string buildCommand(const std::string& name,
const CommandParams& params);
// Parse a raw command / notify line into name + params (+ pipe groups).
ParsedCommand parseCommand(const std::string& raw);
} // namespace Echoion::Protocol
@@ -0,0 +1,88 @@
#pragma once
// Low-level cryptographic primitives for the TeamSpeak 3/6 full-client voice
// protocol. Ported byte-for-byte from ts6-manager's tslib/crypto.ts (MIT) so the
// on-wire behaviour is identical; implemented over OpenSSL EVP.
//
// The protocol uses AES-128-EAX for per-packet authenticated encryption. OpenSSL
// has no native EAX, so — exactly like the reference — we compose it from
// AES-128-CTR (confidentiality) and AES-128-CMAC / OMAC1 (authenticity).
#include <array>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Crypto
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
inline constexpr size_t BLOCK_SIZE = 16;
inline constexpr size_t MAC_LEN = 8;
// "TS3INIT1" — the fake/static MAC stamped on low-level init packets before a
// shared secret exists.
inline constexpr std::array<uint8_t, 8> INIT_MAC = {'T', 'S', '3', 'I',
'N', 'I', 'T', '1'};
// "c:\\windows\\syste" / "m\\firewall32.cpl" — the fixed key/nonce used to
// (de)crypt command packets during the handshake, before key exchange.
inline constexpr std::array<uint8_t, 16> DUMMY_KEY = {
'c', ':', '\\', 'w', 'i', 'n', 'd', 'o',
'w', 's', '\\', 's', 'y', 's', 't', 'e'};
inline constexpr std::array<uint8_t, 16> DUMMY_NONCE = {
'm', '\\', 'f', 'i', 'r', 'e', 'w', 'a',
'l', 'l', '3', '2', '.', 'c', 'p', 'l'};
// Client version signature used in clientinit (3.5.0 [Stable]).
inline constexpr uint32_t INIT_VERSION = 1566914096u;
// --- Hashes -------------------------------------------------------------
std::array<uint8_t, 20> sha1(ByteView data);
std::array<uint8_t, 32> sha256(ByteView data);
std::array<uint8_t, 64> sha512(ByteView data);
// --- XOR helpers --------------------------------------------------------
// out[i] = a[i] ^ b[i] for i in [0, min(a,b)).
Bytes xorBuffers(ByteView a, ByteView b);
// a[i] ^= b[i] for i in [0, len). Caller guarantees bounds.
void xorInto(std::span<uint8_t> a, ByteView b, size_t len);
// --- AES-128-CMAC (OMAC1) ----------------------------------------------
// 16-byte MAC over `data` under the 16-byte `key`.
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data);
// --- AES-128-EAX --------------------------------------------------------
struct EaxResult {
Bytes ciphertext;
std::array<uint8_t, MAC_LEN> mac;
};
// Encrypt `plaintext` with 16-byte `key`, `nonce` and associated `header`.
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
ByteView plaintext);
// Decrypt/verify; returns nullopt on MAC mismatch.
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
ByteView header, ByteView ciphertext,
ByteView mac);
// --- Per-packet key/nonce derivation -----------------------------------
struct KeyNonce {
std::array<uint8_t, 16> key;
std::array<uint8_t, 16> nonce;
};
// Derive the packet key+nonce from the connection `ivStruct` (20 bytes for
// the SHA1 handshake secret, 64 bytes for the license path), keyed by
// direction, packet id, generation and packet type.
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
uint32_t generationId, uint8_t packetType,
ByteView ivStruct);
// --- Misc ---------------------------------------------------------------
// base64(sha1(utf8(password))); empty string for empty password.
std::string hashPassword(const std::string& password);
} // namespace Echoion::Protocol::Crypto
@@ -0,0 +1,62 @@
#pragma once
// TeamSpeak client identity: an ECDSA P-256 keypair plus the libtomcrypt-style
// public-key export ("omega"), the derived unique-id, and the hashcash
// key-offset that raises the identity's "security level".
// Ported from ts6-manager tslib/identity.ts.
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
class Identity
{
public:
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Generate a fresh identity and raise it to at least `securityLevel`
// leading-zero bits (hashcash over the public key + offset).
static Identity generate(int securityLevel = 8);
// Load / save the identity to a small text file:
// privateKeyPem, publicKeyString, keyOffset (one per line).
static Identity load(const std::string& path);
void save(const std::string& path) const;
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
const std::string& publicKeyString() const { return publicKeyString_; }
// base64(sha1(ascii(publicKeyString))).
const std::string& uid() const { return uid_; }
uint64_t keyOffset() const { return keyOffset_; }
int securityLevel() const;
// ECDSA sign `data` with SHA-256; returns the raw signature.
Bytes sign(ByteView data) const;
// ECDH(this private key, server public key) → SHA-1 of the shared
// x-coordinate. `serverPublicKeyDer` is the libtomcrypt DER blob
// (base64-decoded "omega" from initivexpand).
Bytes sharedSecret(ByteView serverPublicKeyDer) const;
private:
Identity() = default;
struct PKeyDeleter {
void operator()(void* p) const noexcept;
};
// EVP_PKEY* held opaquely so this header stays OpenSSL-free.
std::shared_ptr<void> pkey_;
std::string publicKeyString_;
std::string uid_;
uint64_t keyOffset_ = 0;
};
} // namespace Echoion::Protocol
@@ -0,0 +1,45 @@
#pragma once
// TeamSpeak license chain handling for the modern handshake (initivexpand2).
// The chain is walked with Ed25519 point arithmetic (scalar-mult + point-add),
// which OpenSSL does not expose, so this module uses libsodium.
// Ported from ts6-manager tslib/license.ts.
#include <array>
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
struct LicenseBlock {
std::array<uint8_t, 32> key;
std::array<uint8_t, 32> hash; // first 32 bytes of SHA-512(content)
uint8_t type = 0;
};
struct TempKey {
std::array<uint8_t, 32> publicKey;
std::array<uint8_t, 32> privateKey;
};
// Parse the server license blob into its chain of blocks.
std::vector<LicenseBlock> parseLicense(ByteView data);
// Walk the chain from the root key to the final server public key (32 bytes).
std::array<uint8_t, 32>
deriveLicenseKey(const std::vector<LicenseBlock>& blocks);
// Generate an ephemeral Ed25519 keypair (clamped like the reference).
TempKey generateTemporaryKey();
// initivexpand2 shared secret: SHA-512( tempPriv * serverDerivedKey ),
// 64 bytes. Returns the raw digest.
std::array<uint8_t, 64>
getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey);
} // namespace Echoion::Protocol
@@ -0,0 +1,23 @@
#pragma once
// QuickLZ level-1 decompression, used to inflate compressed command packets.
// Clients send commands uncompressed, so only decompression is needed.
// Ported from ts6-manager tslib/quicklz.ts (itself from TSLib QuickerLz.cs).
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
uint32_t qlzDecompressedSize(ByteView data);
uint32_t qlzCompressedSize(ByteView data);
// Throws std::runtime_error on malformed input or unsupported level.
Bytes qlzDecompress(ByteView data);
} // namespace Echoion::Protocol
@@ -0,0 +1,195 @@
#pragma once
// Full-client connection to a TeamSpeak 3/6 server over the native UDP voice
// protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and
// voice send path. Ported from ts6-manager tslib/client.ts.
//
// Threading: a single background thread runs the receive + timer loop. Public
// send methods are thread-safe (guarded by an internal mutex) so the audio
// thread can call sendVoice() directly. Callbacks fire on the loop thread.
#include "echoion/protocol/Command.hpp"
#include "echoion/protocol/Identity.hpp"
#include <atomic>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <thread>
#include <vector>
namespace Echoion::Protocol
{
enum class PacketType : uint8_t {
Voice = 0,
VoiceWhisper = 1,
Command = 2,
CommandLow = 3,
Ping = 4,
Pong = 5,
Ack = 6,
AckLow = 7,
Init1 = 8,
};
enum class ClientState {
Disconnected,
Init,
Handshake,
Connected,
Disconnecting,
};
struct TsClientOptions {
std::string host;
uint16_t port = 9987;
const Identity* identity = nullptr; // not owned
std::string nickname = "EchoionBot";
std::string serverPassword;
std::string defaultChannel; // channel id or name
std::string channelPassword;
};
// All callbacks fire on the internal loop thread.
struct TsClientCallbacks {
std::function<void()> onConnected;
std::function<void()> onDisconnected;
std::function<void(const std::string&)> onError;
std::function<void(const ParsedCommand&)> onCommand;
std::function<void(const CommandParams&)> onTextMessage;
std::function<void(std::span<const uint8_t>)> onVoice;
std::function<void(const std::string&)> onDebug;
};
class TsClient
{
public:
TsClient();
~TsClient();
TsClient(const TsClient&) = delete;
TsClient& operator=(const TsClient&) = delete;
void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); }
// Begin connecting. Returns immediately; onConnected/onError fire
// asynchronously. Throws only on immediate socket setup failure.
void connect(const TsClientOptions& opts);
// Graceful: send clientdisconnect, then close.
void disconnect();
// Immediate close, no disconnect command.
void forceClose();
ClientState state() const { return state_.load(); }
uint16_t clientId() const { return clientId_.load(); }
// Send one already-Opus-encoded 20 ms frame to the current channel.
void sendVoice(std::span<const uint8_t> opus);
// Whisper the frame to the given channel/client targets.
void sendWhisper(std::span<const uint8_t> opus,
const std::vector<uint64_t>& channelIds,
const std::vector<uint16_t>& clientIds);
// End-of-voice marker (empty frame).
void sendVoiceStop();
// Send a raw pre-built TS3 command line (fragmented if large).
void sendCommand(const std::string& cmd);
private:
// ---- packet path ----
void loopThread();
void handleIncomingPacket(std::span<const uint8_t> raw);
void sendOutgoing(std::span<const uint8_t> data, PacketType type,
uint8_t extraFlags = 0);
std::vector<uint8_t> buildRawPacket(std::span<const uint8_t> data,
PacketType type,
uint16_t packetId,
uint8_t flags);
void encryptPacket(std::vector<uint8_t>& raw, PacketType type,
uint16_t packetId, uint32_t gen, uint8_t flags,
std::span<const uint8_t> data);
std::vector<uint8_t> decryptPacket(std::span<const uint8_t> raw,
PacketType type,
uint16_t packetId, uint32_t gen,
uint8_t flags, bool& ok);
void sendRawLocked(const std::vector<uint8_t>& raw);
void sendInitPacket(const std::vector<uint8_t>& data);
// ---- handshake / commands ----
std::vector<uint8_t> buildInit0();
void handleInit(std::span<const uint8_t> data);
void handleCommandData(std::span<const uint8_t> data, uint8_t flags);
void processCommand(std::span<const uint8_t> data, uint8_t flags);
void handleInitIvExpand(const CommandParams& params);
void handleInitIvExpand2(const CommandParams& params);
void sendClientInit();
void handleInitServer(const CommandParams& params);
void handleChannelList(const ParsedCommand& parsed);
void handleChannelListFinished();
void sendAck(uint16_t ackId, PacketType ackType);
void handlePing(uint16_t packetId);
void resendTick();
void debug(const std::string& msg);
void cleanup();
// counters / crypto
struct Counter {
uint16_t id = 0;
uint32_t gen = 0;
};
Counter getCounter(PacketType type);
void incCounter(PacketType type);
TsClientOptions opts_;
TsClientCallbacks cb_;
int sock_ = -1;
std::atomic<ClientState> state_{ClientState::Disconnected};
std::atomic<uint16_t> clientId_{0};
std::thread thread_;
std::atomic<bool> running_{false};
// Recursive: command handlers running under the loop lock call
// sendCommand()/sendOutgoing() which re-lock.
mutable std::recursive_mutex mu_;
int64_t disconnectDeadline_ = 0;
std::array<uint16_t, 9> packetCounter_{};
std::array<uint32_t, 9> generationCounter_{};
bool cryptoInitComplete_ = false;
std::vector<uint8_t> ivStruct_;
std::array<uint8_t, 8> fakeSignature_{};
std::vector<uint8_t> alphaTmp_;
// resend tracking
struct Resend {
std::vector<uint8_t> raw;
uint16_t packetId = 0;
int64_t firstSend = 0;
int64_t lastSend = 0;
};
std::map<uint16_t, Resend> resendMap_;
std::unique_ptr<Resend> initResend_;
int64_t lastMessageTime_ = 0;
int64_t lastPing_ = 0;
int64_t connectStart_ = 0;
// fragment reassembly
std::vector<uint8_t> fragmentBuffer_;
bool fragmenting_ = false;
uint8_t fragmentFlags_ = 0;
// channel map for auto-move
std::map<std::string, uint64_t> channelMap_;
};
} // namespace Echoion::Protocol
@@ -0,0 +1,24 @@
#pragma once
// Small dependency-free encoding helpers shared across the protocol modules.
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Util
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Standard base64 (RFC 4648) with '+' '/' and '=' padding.
std::string base64Encode(ByteView data);
Bytes base64Decode(const std::string& text);
// Lowercase hex, no separators.
std::string toHex(ByteView data);
Bytes fromHex(const std::string& hex);
} // namespace Echoion::Protocol::Util
+184
View File
@@ -0,0 +1,184 @@
#include "echoion/protocol/Command.hpp"
#include <sstream>
#include <stdexcept>
namespace Echoion::Protocol
{
std::string tsEscape(const std::string& str)
{
std::string out;
out.reserve(str.size());
for (char c : str) {
switch (c) {
case '\\':
out += "\\\\";
break;
case '/':
out += "\\/";
break;
case ' ':
out += "\\s";
break;
case '|':
out += "\\p";
break;
case '\f':
out += "\\f";
break;
case '\n':
out += "\\n";
break;
case '\r':
out += "\\r";
break;
case '\t':
out += "\\t";
break;
case '\v':
out += "\\v";
break;
default:
out.push_back(c);
}
}
return out;
}
std::string tsUnescape(const std::string& str)
{
std::string out;
out.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] == '\\') {
if (++i >= str.size()) {
throw std::runtime_error("invalid escape sequence");
}
switch (str[i]) {
case '\\':
out.push_back('\\');
break;
case '/':
out.push_back('/');
break;
case 's':
out.push_back(' ');
break;
case 'p':
out.push_back('|');
break;
case 'f':
out.push_back('\f');
break;
case 'n':
out.push_back('\n');
break;
case 'r':
out.push_back('\r');
break;
case 't':
out.push_back('\t');
break;
case 'v':
out.push_back('\v');
break;
default:
throw std::runtime_error(std::string("unknown escape: \\") +
str[i]);
}
} else {
out.push_back(str[i]);
}
}
return out;
}
std::string buildCommand(const std::string& name,
const CommandParams& params)
{
std::string cmd = tsEscape(name);
for (const auto& [key, value] : params) {
cmd += ' ';
cmd += key;
cmd += '=';
cmd += tsEscape(value);
}
return cmd;
}
namespace
{
CommandParams parseGroup(const std::string& part)
{
CommandParams params;
std::istringstream iss(part);
std::string token;
while (std::getline(iss, token, ' ')) {
if (token.empty()) {
continue;
}
auto eq = token.find('=');
if (eq != std::string::npos) {
params[token.substr(0, eq)] =
tsUnescape(token.substr(eq + 1));
} else {
params[token] = "";
}
}
return params;
}
std::string trim(const std::string& s)
{
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) {
return "";
}
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
} // namespace
ParsedCommand parseCommand(const std::string& raw)
{
// Split on '|' into groups.
std::vector<std::string> parts;
{
std::string cur;
for (char c : raw) {
if (c == '|') {
parts.push_back(cur);
cur.clear();
} else {
cur.push_back(c);
}
}
parts.push_back(cur);
}
ParsedCommand out;
std::string first = trim(parts[0]);
// The command name is the first whitespace-delimited token.
std::string body;
auto sp = first.find(' ');
if (sp == std::string::npos) {
out.name = tsUnescape(first);
body = "";
} else {
out.name = tsUnescape(first.substr(0, sp));
body = first.substr(sp + 1);
}
out.params = parseGroup(body);
if (parts.size() > 1) {
out.groups.push_back(out.params);
for (size_t g = 1; g < parts.size(); ++g) {
out.groups.push_back(parseGroup(trim(parts[g])));
}
}
return out;
}
} // namespace Echoion::Protocol
+249
View File
@@ -0,0 +1,249 @@
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <cstring>
#include <stdexcept>
namespace Echoion::Protocol::Crypto
{
namespace
{
// Raw single-block AES-128-ECB encryption (no padding). Used to build
// CMAC; matches the reference's aesEncryptBlock().
std::array<uint8_t, BLOCK_SIZE> aesEncryptBlock(
ByteView key, std::span<const uint8_t, BLOCK_SIZE> block)
{
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
}
std::array<uint8_t, BLOCK_SIZE> out{};
int len = 0;
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(),
nullptr) != 1 ||
EVP_CIPHER_CTX_set_padding(ctx, 0) != 1 ||
EVP_EncryptUpdate(ctx, out.data(), &len, block.data(),
static_cast<int>(BLOCK_SIZE)) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-ECB block encrypt failed");
}
EVP_CIPHER_CTX_free(ctx);
return out;
}
// GF(2^128) left-shift-by-one with the 0x87 reduction polynomial.
std::array<uint8_t, BLOCK_SIZE> doubleBlock(
const std::array<uint8_t, BLOCK_SIZE>& buf)
{
std::array<uint8_t, BLOCK_SIZE> out{};
uint8_t carry = 0;
for (int i = BLOCK_SIZE - 1; i >= 0; --i) {
uint16_t tmp = static_cast<uint16_t>((buf[i] << 1) | carry);
out[i] = static_cast<uint8_t>(tmp & 0xff);
carry = (buf[i] >> 7) & 1;
}
if (carry) {
out[BLOCK_SIZE - 1] ^= 0x87;
}
return out;
}
// EAX OMAC over a tag byte prepended in a leading block, then `data`.
std::array<uint8_t, BLOCK_SIZE> eaxOmac(ByteView key, uint8_t tag,
ByteView data)
{
Bytes input(BLOCK_SIZE + data.size(), 0);
input[BLOCK_SIZE - 1] = tag;
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size());
return cmac(key, input);
}
// AES-128-CTR keystream applied to `in`, IV = `nonce`.
Bytes aesCtr(ByteView key, std::span<const uint8_t, BLOCK_SIZE> nonce,
ByteView in)
{
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
}
Bytes out(in.size(), 0);
int len = 0;
int total = 0;
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key.data(),
nonce.data()) != 1 ||
EVP_EncryptUpdate(ctx, out.data(), &len, in.data(),
static_cast<int>(in.size())) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-CTR failed");
}
total = len;
if (EVP_EncryptFinal_ex(ctx, out.data() + total, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("AES-CTR final failed");
}
EVP_CIPHER_CTX_free(ctx);
out.resize(static_cast<size_t>(total) + len);
return out;
}
} // namespace
std::array<uint8_t, 20> sha1(ByteView data)
{
std::array<uint8_t, 20> out{};
::SHA1(data.data(), data.size(), out.data());
return out;
}
std::array<uint8_t, 32> sha256(ByteView data)
{
std::array<uint8_t, 32> out{};
::SHA256(data.data(), data.size(), out.data());
return out;
}
std::array<uint8_t, 64> sha512(ByteView data)
{
std::array<uint8_t, 64> out{};
::SHA512(data.data(), data.size(), out.data());
return out;
}
Bytes xorBuffers(ByteView a, ByteView b)
{
size_t len = std::min(a.size(), b.size());
Bytes out(len, 0);
for (size_t i = 0; i < len; ++i) {
out[i] = a[i] ^ b[i];
}
return out;
}
void xorInto(std::span<uint8_t> a, ByteView b, size_t len)
{
for (size_t i = 0; i < len; ++i) {
a[i] ^= b[i];
}
}
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data)
{
const std::array<uint8_t, BLOCK_SIZE> zero{};
auto L = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
zero.data(), BLOCK_SIZE));
auto K1 = doubleBlock(L);
auto K2 = doubleBlock(K1);
const size_t n = data.size();
const size_t numBlocks = n == 0 ? 1 : (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
const bool lastComplete = n > 0 && n % BLOCK_SIZE == 0;
std::array<uint8_t, BLOCK_SIZE> x{};
for (size_t i = 0; i + 1 < numBlocks; ++i) {
std::array<uint8_t, BLOCK_SIZE> block{};
std::memcpy(block.data(), data.data() + i * BLOCK_SIZE, BLOCK_SIZE);
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
block[j] ^= x[j];
}
x = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
block.data(), BLOCK_SIZE));
}
std::array<uint8_t, BLOCK_SIZE> last{};
const size_t off = (numBlocks - 1) * BLOCK_SIZE;
if (lastComplete) {
std::memcpy(last.data(), data.data() + off, BLOCK_SIZE);
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= K1[j];
}
} else {
const size_t rem = n - off;
std::memcpy(last.data(), data.data() + off, rem);
last[rem] = 0x80;
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= K2[j];
}
}
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
last[j] ^= x[j];
}
return aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
last.data(), BLOCK_SIZE));
}
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
ByteView plaintext)
{
auto N = eaxOmac(key, 0, nonce);
auto H = eaxOmac(key, 1, header);
Bytes ciphertext = aesCtr(
key, std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
plaintext);
auto C = eaxOmac(key, 2, ciphertext);
EaxResult res;
res.ciphertext = std::move(ciphertext);
for (size_t i = 0; i < MAC_LEN; ++i) {
res.mac[i] = N[i] ^ H[i] ^ C[i];
}
return res;
}
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
ByteView header, ByteView ciphertext,
ByteView mac)
{
auto N = eaxOmac(key, 0, nonce);
auto H = eaxOmac(key, 1, header);
auto C = eaxOmac(key, 2, ciphertext);
std::array<uint8_t, MAC_LEN> tag{};
uint8_t diff = 0;
for (size_t i = 0; i < MAC_LEN; ++i) {
tag[i] = N[i] ^ H[i] ^ C[i];
diff |= static_cast<uint8_t>(tag[i] ^ (i < mac.size() ? mac[i] : 0));
}
if (diff != 0 || mac.size() < MAC_LEN) {
return std::nullopt;
}
return aesCtr(key,
std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
ciphertext);
}
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
uint32_t generationId, uint8_t packetType,
ByteView ivStruct)
{
const size_t tmpLen = ivStruct.size() == 20 ? 26 : 70;
Bytes tmp(tmpLen, 0);
tmp[0] = fromServer ? 0x30 : 0x31;
tmp[1] = packetType;
tmp[2] = static_cast<uint8_t>((generationId >> 24) & 0xff);
tmp[3] = static_cast<uint8_t>((generationId >> 16) & 0xff);
tmp[4] = static_cast<uint8_t>((generationId >> 8) & 0xff);
tmp[5] = static_cast<uint8_t>(generationId & 0xff);
std::memcpy(tmp.data() + 6, ivStruct.data(), ivStruct.size());
auto kn = sha256(tmp);
KeyNonce out;
std::memcpy(out.key.data(), kn.data(), 16);
std::memcpy(out.nonce.data(), kn.data() + 16, 16);
out.key[0] ^= static_cast<uint8_t>((packetId >> 8) & 0xff);
out.key[1] ^= static_cast<uint8_t>(packetId & 0xff);
return out;
}
std::string hashPassword(const std::string& password)
{
if (password.empty()) {
return "";
}
auto digest = sha1(ByteView(
reinterpret_cast<const uint8_t*>(password.data()), password.size()));
return Util::base64Encode(ByteView(digest.data(), digest.size()));
}
} // namespace Echoion::Protocol::Crypto
+426
View File
@@ -0,0 +1,426 @@
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/param_build.h>
#include <openssl/pem.h>
#include <fstream>
#include <stdexcept>
#include <string>
namespace Echoion::Protocol
{
namespace
{
using Bytes = std::vector<uint8_t>;
[[noreturn]] void fail(const char* what)
{
throw std::runtime_error(std::string("Identity: ") + what);
}
EVP_PKEY* asPkey(const std::shared_ptr<void>& p)
{
return static_cast<EVP_PKEY*>(p.get());
}
// Minimal big-endian encoding of a BIGNUM (no leading zeros).
Bytes bnBytes(const BIGNUM* bn)
{
int n = BN_num_bytes(bn);
Bytes out(static_cast<size_t>(n < 0 ? 0 : n), 0);
if (n > 0) {
BN_bn2bin(bn, out.data());
}
return out;
}
Bytes derLength(size_t len)
{
if (len < 0x80) {
return {static_cast<uint8_t>(len)};
}
if (len < 0x100) {
return {0x81, static_cast<uint8_t>(len)};
}
return {0x82, static_cast<uint8_t>((len >> 8) & 0xff),
static_cast<uint8_t>(len & 0xff)};
}
// DER INTEGER from a non-negative big-endian magnitude.
Bytes derInteger(Bytes mag)
{
if (mag.empty()) {
mag.push_back(0);
}
if (mag[0] & 0x80) {
mag.insert(mag.begin(), 0x00);
}
Bytes out;
out.push_back(0x02);
Bytes len = derLength(mag.size());
out.insert(out.end(), len.begin(), len.end());
out.insert(out.end(), mag.begin(), mag.end());
return out;
}
Bytes derIntegerFromU64(uint64_t v)
{
BIGNUM* bn = BN_new();
BN_set_word(bn, v);
Bytes r = derInteger(bnBytes(bn));
BN_free(bn);
return r;
}
// libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x),
// INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00)
// plus 0x07 0x00 in the reference; we reproduce it verbatim.
std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y)
{
Bytes content;
const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00};
content.insert(content.end(), std::begin(bitStr), std::end(bitStr));
Bytes i32 = derIntegerFromU64(32);
Bytes ix = derInteger(bnBytes(x));
Bytes iy = derInteger(bnBytes(y));
content.insert(content.end(), i32.begin(), i32.end());
content.insert(content.end(), ix.begin(), ix.end());
content.insert(content.end(), iy.begin(), iy.end());
Bytes der;
der.push_back(0x30);
Bytes len = derLength(content.size());
der.insert(der.end(), len.begin(), len.end());
der.insert(der.end(), content.begin(), content.end());
return Util::base64Encode(Crypto::ByteView(der.data(), der.size()));
}
// Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY.
Bytes pubPoint(EVP_PKEY* pkey)
{
size_t len = 0;
if (EVP_PKEY_get_octet_string_param(
pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) {
fail("cannot read public point length");
}
Bytes buf(len, 0);
if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY,
buf.data(), len, &len) != 1) {
fail("cannot read public point");
}
buf.resize(len);
return buf;
}
int countLeadingZeroBits(Crypto::ByteView data)
{
int count = 0;
for (uint8_t b : data) {
if (b == 0) {
count += 8;
} else {
for (int bit = 0; bit < 8; ++bit) {
if ((b & (1 << bit)) == 0) {
++count;
} else {
return count;
}
}
}
}
return count;
}
int securityLevelFor(const std::string& pubKeyString, uint64_t offset)
{
std::string s = pubKeyString + std::to_string(offset);
auto h = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(s.data()), s.size()));
return countLeadingZeroBits(
Crypto::ByteView(h.data(), h.size()));
}
// libtomcrypt DER parse → the two public-key INTEGERs (x, y). See
// reference parseDerSequence: collected = [bitByte, 32, x, y].
void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y)
{
size_t pos = 0;
auto readLen = [&](size_t& p) -> size_t {
uint8_t first = der[p++];
if (first < 0x80) {
return first;
}
int nb = first & 0x7f;
size_t len = 0;
for (int i = 0; i < nb; ++i) {
len = (len << 8) | der[p++];
}
return len;
};
if (der.empty() || der[pos++] != 0x30) {
fail("server key: expected SEQUENCE");
}
readLen(pos);
std::vector<BIGNUM*> ints;
while (pos < der.size()) {
uint8_t tag = der[pos++];
size_t len = readLen(pos);
if (tag == 0x02) {
ints.push_back(
BN_bin2bn(der.data() + pos, static_cast<int>(len),
nullptr));
}
pos += len;
}
// ints = [32, x, y]; guard against short input.
if (ints.size() < 3) {
for (auto* b : ints) {
BN_free(b);
}
fail("server key: too few integers");
}
*x = ints[1];
*y = ints[2];
for (size_t i = 0; i < ints.size(); ++i) {
if (i != 1 && i != 2) {
BN_free(ints[i]);
}
}
}
} // namespace
void Identity::PKeyDeleter::operator()(void* p) const noexcept
{
EVP_PKEY_free(static_cast<EVP_PKEY*>(p));
}
Identity Identity::generate(int securityLevel)
{
EVP_PKEY* pkey = nullptr;
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!ctx) {
fail("keygen ctx");
}
if (EVP_PKEY_keygen_init(ctx) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen init");
}
OSSL_PARAM params[2] = {
OSSL_PARAM_construct_utf8_string(
OSSL_PKEY_PARAM_GROUP_NAME,
const_cast<char*>("prime256v1"), 0),
OSSL_PARAM_construct_end()};
EVP_PKEY_CTX_set_params(ctx, params);
if (EVP_PKEY_keygen(ctx, &pkey) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen");
}
EVP_PKEY_CTX_free(ctx);
Identity id;
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
Bytes point = pubPoint(pkey);
if (point.size() != 65 || point[0] != 0x04) {
fail("unexpected public point format");
}
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
id.publicKeyString_ = buildPublicKeyString(x, y);
BN_free(x);
BN_free(y);
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
// Hashcash: find the offset giving the most leading-zero bits, up to
// the requested level.
if (securityLevel > 0) {
uint64_t offset = 0;
int best = securityLevelFor(id.publicKeyString_, offset);
uint64_t checked = 0;
while (best < securityLevel) {
++checked;
int curr = securityLevelFor(id.publicKeyString_, checked);
if (curr > best) {
best = curr;
offset = checked;
}
}
id.keyOffset_ = offset;
}
return id;
}
int Identity::securityLevel() const
{
return securityLevelFor(publicKeyString_, keyOffset_);
}
Identity::Bytes Identity::sign(ByteView data) const
{
EVP_PKEY* pkey = asPkey(pkey_);
EVP_MD_CTX* md = EVP_MD_CTX_new();
if (!md) {
fail("sign ctx");
}
size_t siglen = 0;
if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 ||
EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign init");
}
Bytes sig(siglen, 0);
if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign");
}
sig.resize(siglen);
EVP_MD_CTX_free(md);
return sig;
}
Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const
{
BIGNUM* x = nullptr;
BIGNUM* y = nullptr;
parseServerPub(serverPublicKeyDer, &x, &y);
// Build uncompressed point 0x04 || x(32) || y(32).
Bytes point(65, 0);
point[0] = 0x04;
BN_bn2binpad(x, point.data() + 1, 32);
BN_bn2binpad(y, point.data() + 33, 32);
BN_free(x);
BN_free(y);
EVP_PKEY* peer = nullptr;
{
OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
"prime256v1", 0);
OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY,
point.data(), point.size());
OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld);
EVP_PKEY_CTX* pctx =
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 ||
EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) {
if (pctx) {
EVP_PKEY_CTX_free(pctx);
}
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
fail("build peer key");
}
EVP_PKEY_CTX_free(pctx);
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
}
EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr);
size_t secretLen = 0;
if (!dctx || EVP_PKEY_derive_init(dctx) != 1 ||
EVP_PKEY_derive_set_peer(dctx, peer) != 1 ||
EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) {
if (dctx) {
EVP_PKEY_CTX_free(dctx);
}
EVP_PKEY_free(peer);
fail("ecdh derive init");
}
Bytes secret(secretLen, 0);
if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) {
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
fail("ecdh derive");
}
secret.resize(secretLen);
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
// Pad/truncate to 32 bytes, then SHA-1 (matches reference).
Bytes keyArr(32, 0);
if (secret.size() >= 32) {
std::copy(secret.end() - 32, secret.end(), keyArr.begin());
} else {
std::copy(secret.begin(), secret.end(),
keyArr.begin() + (32 - secret.size()));
}
auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size()));
return Bytes(h.begin(), h.end());
}
void Identity::save(const std::string& path) const
{
EVP_PKEY* pkey = asPkey(pkey_);
BIO* mem = BIO_new(BIO_s_mem());
if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr,
nullptr)) {
BIO_free(mem);
fail("serialize private key");
}
char* data = nullptr;
long n = BIO_get_mem_data(mem, &data);
std::string pem(data, static_cast<size_t>(n));
BIO_free(mem);
std::ofstream out(path, 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;
}
Identity Identity::load(const std::string& path)
{
std::ifstream in(path);
if (!in) {
fail("cannot open identity file");
}
std::string magic;
std::getline(in, magic);
if (magic != "ECHOION_IDENTITY_V1") {
fail("bad identity file magic");
}
std::string offsetLine;
std::getline(in, offsetLine);
Identity id;
id.keyOffset_ = std::stoull(offsetLine);
std::getline(in, id.publicKeyString_);
std::string sep;
std::getline(in, sep); // -----PRIVATE-----
std::string pem((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
BIO* mem = BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size()));
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr);
BIO_free(mem);
if (!pkey) {
fail("cannot parse private key");
}
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
return id;
}
} // namespace Echoion::Protocol
+171
View File
@@ -0,0 +1,171 @@
#include "echoion/protocol/License.hpp"
#include "echoion/protocol/Crypto.hpp"
#include <sodium.h>
#include <cstring>
#include <mutex>
#include <stdexcept>
namespace Echoion::Protocol
{
namespace
{
[[noreturn]] void fail(const char* what)
{
throw std::runtime_error(std::string("License: ") + what);
}
void ensureSodium()
{
static std::once_flag once;
static bool ok = false;
std::call_once(once, [] { ok = sodium_init() >= 0; });
if (!ok) {
fail("libsodium init failed");
}
}
// Ed25519 point compressed root key.
constexpr std::array<uint8_t, 32> LICENSE_ROOT_KEY = {
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c,
0xfd, 0x8f, 0x68, 0xb3, 0xdc, 0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec,
0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a};
size_t findNullTerminator(ByteView data, size_t start)
{
for (size_t i = start; i < data.size(); ++i) {
if (data[i] == 0) {
return i - start;
}
}
fail("non-null-terminated string in license");
}
} // namespace
std::vector<LicenseBlock> parseLicense(ByteView data)
{
if (data.size() < 1) {
fail("license too short");
}
if (data[0] != 1) {
fail("unsupported license version");
}
std::vector<LicenseBlock> blocks;
size_t pos = 1;
while (pos < data.size()) {
if (data.size() - pos < 42) {
fail("license block too short");
}
if (data[pos] != 0) {
fail("wrong key kind");
}
LicenseBlock block;
std::memcpy(block.key.data(), data.data() + pos + 1, 32);
const uint8_t blockType = data[pos + 33];
block.type = blockType;
size_t extraLen = 0;
switch (blockType) {
case 0: // Intermediate
extraLen = findNullTerminator(data, pos + 46) + 5;
break;
case 2: // Server
extraLen = findNullTerminator(data, pos + 47) + 6;
break;
case 8: { // TS5 Server
size_t p = pos + 44;
const uint8_t propCount = data[pos + 43];
for (uint8_t i = 0; i < propCount; ++i) {
const uint8_t propLen = data[p];
p += 1 + propLen;
}
extraLen = p - (pos + 42);
break;
}
case 32: // Ephemeral
extraLen = 0;
break;
default:
fail("invalid license block type");
}
const size_t blockLen = 42 + extraLen;
if (pos + blockLen > data.size()) {
fail("license block overruns buffer");
}
auto content = data.subspan(pos + 1, blockLen - 1);
auto h = Crypto::sha512(content);
std::memcpy(block.hash.data(), h.data(), 32);
blocks.push_back(block);
pos += blockLen;
}
return blocks;
}
std::array<uint8_t, 32>
deriveLicenseKey(const std::vector<LicenseBlock>& blocks)
{
ensureSodium();
std::array<uint8_t, 32> parentKey = LICENSE_ROOT_KEY;
for (const auto& block : blocks) {
// Clamp the block hash into an Ed25519 scalar.
std::array<uint8_t, 32> scalar = block.hash;
scalar[0] &= 0xf8;
scalar[31] &= 0x3f;
scalar[31] |= 0x40;
std::array<uint8_t, 32> mul{};
if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(),
block.key.data()) != 0) {
fail("ed25519 scalarmult failed");
}
std::array<uint8_t, 32> sum{};
if (crypto_core_ed25519_add(sum.data(), mul.data(),
parentKey.data()) != 0) {
fail("ed25519 point add failed");
}
parentKey = sum;
}
return parentKey;
}
TempKey generateTemporaryKey()
{
ensureSodium();
TempKey out;
randombytes_buf(out.privateKey.data(), out.privateKey.size());
out.privateKey[0] &= 248;
out.privateKey[31] &= 127;
out.privateKey[31] |= 64;
if (crypto_scalarmult_ed25519_base_noclamp(out.publicKey.data(),
out.privateKey.data()) != 0) {
fail("ed25519 base mult failed");
}
return out;
}
std::array<uint8_t, 64> getSharedSecret2(ByteView serverDerivedKey,
ByteView tempPrivateKey)
{
ensureSodium();
if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) {
fail("bad key length for shared secret");
}
std::array<uint8_t, 32> priv{};
std::memcpy(priv.data(), tempPrivateKey.data(), 32);
priv[31] &= 0x7f;
std::array<uint8_t, 32> mul{};
if (crypto_scalarmult_ed25519_noclamp(mul.data(), priv.data(),
serverDerivedKey.data()) != 0) {
fail("ed25519 scalarmult failed");
}
return Crypto::sha512(ByteView(mul.data(), mul.size()));
}
} // namespace Echoion::Protocol
+158
View File
@@ -0,0 +1,158 @@
#include "echoion/protocol/QuickLz.hpp"
#include <algorithm>
#include <stdexcept>
namespace Echoion::Protocol
{
namespace
{
constexpr int TABLE_SIZE = 4096;
constexpr uint32_t MAX_DECOMPRESSED_SIZE = 1024 * 1024;
uint32_t readU32LE(ByteView b, size_t off)
{
return static_cast<uint32_t>(b[off]) |
(static_cast<uint32_t>(b[off + 1]) << 8) |
(static_cast<uint32_t>(b[off + 2]) << 16) |
(static_cast<uint32_t>(b[off + 3]) << 24);
}
int32_t readI32LE(ByteView b, size_t off)
{
return static_cast<int32_t>(readU32LE(b, off));
}
uint32_t read24(const Bytes& b, size_t off)
{
return static_cast<uint32_t>(b[off]) |
(static_cast<uint32_t>(b[off + 1]) << 8) |
(static_cast<uint32_t>(b[off + 2]) << 16);
}
int hashVal(uint32_t value)
{
return static_cast<int>(((value >> 12) ^ value) & 0xfff);
}
} // namespace
uint32_t qlzDecompressedSize(ByteView data)
{
return (data[0] & 0x02) != 0
? static_cast<uint32_t>(readI32LE(data, 5))
: data[2];
}
uint32_t qlzCompressedSize(ByteView data)
{
return (data[0] & 0x02) != 0
? static_cast<uint32_t>(readI32LE(data, 1))
: data[1];
}
Bytes qlzDecompress(ByteView data)
{
if (data.empty()) {
throw std::runtime_error("QuickLZ: empty input");
}
const uint8_t flags = data[0];
const int level = (flags >> 2) & 0x03;
if (level != 1) {
throw std::runtime_error("QuickLZ level not supported");
}
const size_t headerLen = (flags & 0x02) != 0 ? 9 : 3;
const uint32_t decompressedSize = qlzDecompressedSize(data);
if (decompressedSize > MAX_DECOMPRESSED_SIZE) {
throw std::runtime_error("QuickLZ: decompressed size exceeds max");
}
Bytes dest(decompressedSize, 0);
if ((flags & 0x01) == 0) {
// Stored, not compressed.
if (headerLen + decompressedSize > data.size()) {
throw std::runtime_error("QuickLZ: truncated stored block");
}
std::copy_n(data.begin() + headerLen, decompressedSize,
dest.begin());
return dest;
}
std::vector<int32_t> hashtable(TABLE_SIZE, 0);
uint32_t control = 1;
size_t sourcePos = headerLen;
size_t destPos = 0;
size_t nextHashed = 0;
while (true) {
if (control == 1) {
control = readU32LE(data, sourcePos);
sourcePos += 4;
}
if ((control & 1) != 0) {
control >>= 1;
const uint8_t next = data[sourcePos++];
const int hashIdx = (next >> 4) | (data[sourcePos++] << 4);
uint32_t matchLen = next & 0x0f;
if (matchLen != 0) {
matchLen += 2;
} else {
matchLen = data[sourcePos++];
}
const int32_t offset = hashtable[hashIdx];
dest[destPos] = dest[offset];
dest[destPos + 1] = dest[offset + 1];
dest[destPos + 2] = dest[offset + 2];
for (uint32_t i = 3; i < matchLen; ++i) {
dest[destPos + i] = dest[offset + i];
}
destPos += matchLen;
const size_t end = destPos + 1 - matchLen;
if (nextHashed < end) {
uint32_t nxt = read24(dest, nextHashed);
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
for (size_t i = nextHashed + 1; i < end; ++i) {
nxt = (nxt >> 8) |
(static_cast<uint32_t>(dest[i + 2]) << 16);
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
}
}
nextHashed = destPos;
} else if (destPos >=
std::max<size_t>(decompressedSize, 10) - 10) {
while (destPos < decompressedSize) {
if (control == 1) {
sourcePos += 4;
}
control >>= 1;
dest[destPos++] = data[sourcePos++];
}
break;
} else {
dest[destPos++] = data[sourcePos++];
control >>= 1;
const size_t end = destPos >= 2 ? destPos - 2 : 0;
if (nextHashed < end) {
uint32_t nxt = read24(dest, nextHashed);
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
for (size_t i = nextHashed + 1; i < end; ++i) {
nxt = (nxt >> 8) |
(static_cast<uint32_t>(dest[i + 2]) << 16);
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
}
}
nextHashed = std::max(nextHashed, end);
}
}
return dest;
}
} // namespace Echoion::Protocol
+980
View File
@@ -0,0 +1,980 @@
#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 <openssl/bn.h>
#include <openssl/rand.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <chrono>
#include <cstring>
#include <stdexcept>
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::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
void putU16BE(std::vector<uint8_t>& b, size_t off, uint16_t v)
{
b[off] = static_cast<uint8_t>((v >> 8) & 0xff);
b[off + 1] = static_cast<uint8_t>(v & 0xff);
}
uint16_t getU16BE(std::span<const uint8_t> b, size_t off)
{
return static_cast<uint16_t>((b[off] << 8) | b[off + 1]);
}
// y = x^(2^level) mod n, all big-endian 64-byte.
std::vector<uint8_t> rsaPuzzle(std::span<const uint8_t> x,
std::span<const uint8_t> n, int32_t level)
{
BN_CTX* ctx = BN_CTX_new();
BIGNUM* bx = BN_bin2bn(x.data(), static_cast<int>(x.size()),
nullptr);
BIGNUM* bn = BN_bin2bn(n.data(), static_cast<int>(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<uint8_t> 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<size_t>(type);
return {packetCounter_[i], generationCounter_[i]};
}
void TsClient::incCounter(PacketType type)
{
if (type == PacketType::Init1) {
return;
}
auto i = static_cast<size_t>(type);
if (++packetCounter_[i] == 0) {
++generationCounter_[i];
}
}
void TsClient::connect(const TsClientOptions& opts)
{
std::lock_guard<std::recursive_mutex> 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<std::recursive_mutex> 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<const uint8_t>(buf, static_cast<size_t>(n)));
}
}
resendTick();
}
std::lock_guard<std::recursive_mutex> lock(mu_);
if (sock_ >= 0) {
::close(sock_);
sock_ = -1;
}
}
// ---- Outgoing ----------------------------------------------------------
std::vector<uint8_t> TsClient::buildInit0()
{
std::vector<uint8_t> buf(4 + 1 + 4 + 4 + 8, 0);
putU16BE(buf, 0, static_cast<uint16_t>((Crypto::INIT_VERSION >> 16)));
putU16BE(buf, 2, static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
buf[4] = 0x00; // step 0
uint32_t ts = static_cast<uint32_t>(
std::chrono::duration_cast<std::chrono::seconds>(
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<uint8_t>& 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>(
Resend{raw, 101, nowMs(), nowMs()});
sendRawLocked(raw);
}
std::vector<uint8_t> TsClient::buildRawPacket(std::span<const uint8_t> data,
PacketType type,
uint16_t packetId,
uint8_t flags)
{
std::vector<uint8_t> 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<uint8_t>((flags & 0xf0) |
(static_cast<uint8_t>(type) & 0x0f));
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(),
data.size());
return raw;
}
void TsClient::encryptPacket(std::vector<uint8_t>& raw, PacketType type,
uint16_t packetId, uint32_t gen, uint8_t flags,
std::span<const uint8_t> 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<uint8_t>(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<const uint8_t> dataIn, PacketType type,
uint8_t extraFlags)
{
auto ctr = getCounter(type);
incCounter(type);
std::vector<uint8_t> 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<uint8_t>& raw)
{
if (sock_ < 0) {
return;
}
::send(sock_, raw.data(), raw.size(), 0);
}
void TsClient::sendCommand(const std::string& cmd)
{
std::lock_guard<std::recursive_mutex> lock(mu_);
std::span<const uint8_t> data(
reinterpret_cast<const uint8_t*>(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);
}
}
void TsClient::sendVoice(std::span<const uint8_t> opus)
{
std::lock_guard<std::recursive_mutex> lock(mu_);
if (state_.load() != ClientState::Connected) {
return;
}
std::vector<uint8_t> 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<std::recursive_mutex> lock(mu_);
if (state_.load() != ClientState::Connected) {
return;
}
std::vector<uint8_t> buf(3, 0);
buf[2] = 5;
sendOutgoing(buf, PacketType::Voice);
}
void TsClient::sendWhisper(std::span<const uint8_t> opus,
const std::vector<uint64_t>& channelIds,
const std::vector<uint16_t>& clientIds)
{
std::lock_guard<std::recursive_mutex> 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<uint8_t> 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<uint8_t>(channelIds.size());
buf[p++] = static_cast<uint8_t>(clientIds.size());
for (uint64_t cid : channelIds) {
for (int s = 56; s >= 0; s -= 8) {
buf[p++] = static_cast<uint8_t>((cid >> s) & 0xff);
}
}
for (uint16_t clid : clientIds) {
buf[p++] = static_cast<uint8_t>((clid >> 8) & 0xff);
buf[p++] = static_cast<uint8_t>(clid & 0xff);
}
std::memcpy(buf.data() + p, opus.data(), opus.size());
sendOutgoing(buf, PacketType::VoiceWhisper);
}
// ---- Incoming ----------------------------------------------------------
std::vector<uint8_t> TsClient::decryptPacket(std::span<const uint8_t> 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<uint8_t>(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<uint8_t>(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<uint8_t>(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<const uint8_t> 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<PacketType>(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<const uint8_t> 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<uint8_t> buf(2, 0);
putU16BE(buf, 0, ackId);
sendOutgoing(buf, ackType);
}
void TsClient::handlePing(uint16_t packetId)
{
std::vector<uint8_t> buf(2, 0);
putU16BE(buf, 0, packetId);
sendOutgoing(buf, PacketType::Pong);
}
// ---- Handshake ---------------------------------------------------------
void TsClient::handleInit(std::span<const uint8_t> 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<uint8_t> init2(4 + 1 + 16 + 4, 0);
putU16BE(init2, 0,
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
putU16BE(init2, 2,
static_cast<uint16_t>(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<const uint8_t> x = data.subspan(1, 64);
std::span<const uint8_t> n = data.subspan(65, 64);
int32_t level = static_cast<int32_t>(
(data[129] << 24) | (data[130] << 16) | (data[131] << 8) |
data[132]);
std::span<const uint8_t> 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<const uint8_t> textBytes(
reinterpret_cast<const uint8_t*>(initAdd.data()),
initAdd.size());
std::vector<uint8_t> init4(4 + 1 + 64 + 64 + 4 + 100 + 64 +
textBytes.size(),
0);
putU16BE(init4, 0,
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
putU16BE(init4, 2,
static_cast<uint16_t>(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<const uint8_t> 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<const uint8_t>(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<const uint8_t> data, uint8_t flags)
{
std::vector<uint8_t> decompressed;
if (flags & FLAG_COMPRESSED) {
try {
decompressed = qlzDecompress(data);
data = std::span<const uint8_t>(decompressed.data(),
decompressed.size());
} catch (const std::exception& e) {
debug(std::string("decompression failed: ") + e.what());
return;
}
}
std::string cmdStr(reinterpret_cast<const char*>(data.data()),
data.size());
auto parsed = parseCommand(cmdStr);
if (cb_.onCommand) {
cb_.onCommand(parsed);
}
const std::string& name = parsed.name;
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<uint16_t>(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<uint8_t> 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<uint16_t>(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<CommandParams>{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<uint64_t>(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<uint8_t> 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<std::recursive_mutex> 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<std::recursive_mutex> lock(mu_);
if (state_.load() == ClientState::Disconnected && !running_.load()) {
return;
}
state_ = ClientState::Disconnected;
running_ = false;
if (sock_ >= 0) {
::shutdown(sock_, SHUT_RDWR);
}
}
void TsClient::cleanup()
{
if (state_.load() == ClientState::Disconnected) {
return;
}
state_ = ClientState::Disconnected;
running_ = false;
if (cb_.onDisconnected) {
cb_.onDisconnected();
}
}
} // namespace Echoion::Protocol
+116
View File
@@ -0,0 +1,116 @@
#include "echoion/protocol/Util.hpp"
#include <array>
#include <stdexcept>
namespace Echoion::Protocol::Util
{
namespace
{
constexpr char kEnc[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::array<int8_t, 256> makeDecodeTable()
{
std::array<int8_t, 256> t{};
t.fill(-1);
for (int i = 0; i < 64; ++i) {
t[static_cast<uint8_t>(kEnc[i])] = static_cast<int8_t>(i);
}
return t;
}
const std::array<int8_t, 256> kDec = makeDecodeTable();
} // namespace
std::string base64Encode(ByteView data)
{
std::string out;
out.reserve((data.size() + 2) / 3 * 4);
size_t i = 0;
for (; i + 3 <= data.size(); i += 3) {
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
(static_cast<uint32_t>(data[i + 1]) << 8) |
static_cast<uint32_t>(data[i + 2]);
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back(kEnc[(n >> 6) & 0x3f]);
out.push_back(kEnc[n & 0x3f]);
}
const size_t rem = data.size() - i;
if (rem == 1) {
uint32_t n = static_cast<uint32_t>(data[i]) << 16;
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back('=');
out.push_back('=');
} else if (rem == 2) {
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
(static_cast<uint32_t>(data[i + 1]) << 8);
out.push_back(kEnc[(n >> 18) & 0x3f]);
out.push_back(kEnc[(n >> 12) & 0x3f]);
out.push_back(kEnc[(n >> 6) & 0x3f]);
out.push_back('=');
}
return out;
}
Bytes base64Decode(const std::string& text)
{
Bytes out;
out.reserve(text.size() / 4 * 3);
uint32_t buf = 0;
int bits = 0;
for (char c : text) {
if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
continue;
}
int8_t v = kDec[static_cast<uint8_t>(c)];
if (v < 0) {
throw std::runtime_error("invalid base64 character");
}
buf = (buf << 6) | static_cast<uint32_t>(v);
bits += 6;
if (bits >= 8) {
bits -= 8;
out.push_back(static_cast<uint8_t>((buf >> bits) & 0xff));
}
}
return out;
}
std::string toHex(ByteView data)
{
static const char* h = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (uint8_t b : data) {
out.push_back(h[b >> 4]);
out.push_back(h[b & 0x0f]);
}
return out;
}
Bytes fromHex(const std::string& hex)
{
auto nib = [](char c) -> int {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
throw std::runtime_error("invalid hex character");
};
if (hex.size() % 2 != 0) {
throw std::runtime_error("odd-length hex string");
}
Bytes out;
out.reserve(hex.size() / 2);
for (size_t i = 0; i < hex.size(); i += 2) {
out.push_back(static_cast<uint8_t>((nib(hex[i]) << 4) |
nib(hex[i + 1])));
}
return out;
}
} // namespace Echoion::Protocol::Util
+12
View File
@@ -0,0 +1,12 @@
# Unit tests for EchoionProtocol. Uses a tiny header-only harness (check.hpp),
# no external test framework required.
file(GLOB ECHOIONPROTOCOL_TEST_SOURCES CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/test_*.cpp")
add_executable(echoion_protocol_tests ${ECHOIONPROTOCOL_TEST_SOURCES})
target_link_libraries(echoion_protocol_tests PRIVATE EchoionProtocol)
target_include_directories(echoion_protocol_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_protocol_tests COMMAND echoion_protocol_tests)
+82
View File
@@ -0,0 +1,82 @@
#pragma once
// Minimal dependency-free test harness. Tests register cases with TEST_CASE and
// assert with CHECK / CHECK_EQ; main() runs them and reports a non-zero exit on
// any failure so ctest treats it as a failing test.
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
namespace echotest
{
struct Case {
std::string name;
std::function<void()> fn;
};
inline std::vector<Case>& registry()
{
static std::vector<Case> cases;
return cases;
}
inline int& failures()
{
static int f = 0;
return f;
}
struct Registrar {
Registrar(const std::string& name, std::function<void()> fn)
{
registry().push_back({name, std::move(fn)});
}
};
inline int run()
{
int failed = 0;
for (auto& c : registry()) {
int before = failures();
try {
c.fn();
} catch (const std::exception& e) {
std::printf(" [THROW] %s: %s\n", c.name.c_str(), e.what());
++failures();
}
if (failures() > before) {
std::printf("[FAIL] %s\n", c.name.c_str());
++failed;
} else {
std::printf("[ok] %s\n", c.name.c_str());
}
}
std::printf("\n%zu cases, %d failed\n", registry().size(), failed);
return failed == 0 ? 0 : 1;
}
} // namespace echotest
#define TEST_CASE(name) \
static void name(); \
static echotest::Registrar reg_##name(#name, name); \
static void name()
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::printf(" CHECK failed: %s (%s:%d)\n", #cond, __FILE__, \
__LINE__); \
++echotest::failures(); \
} \
} while (0)
#define CHECK_EQ(a, b) \
do { \
if (!((a) == (b))) { \
std::printf(" CHECK_EQ failed: %s == %s (%s:%d)\n", #a, #b, \
__FILE__, __LINE__); \
++echotest::failures(); \
} \
} while (0)
+55
View File
@@ -0,0 +1,55 @@
#include "check.hpp"
#include "echoion/protocol/Command.hpp"
using namespace Echoion::Protocol;
TEST_CASE(escape_roundtrip)
{
std::string raw = "hello world|pipe/slash\ttab\nnl\\back";
auto esc = tsEscape(raw);
// Spaces and specials must be escaped (no raw space/pipe left).
CHECK(esc.find(' ') == std::string::npos);
CHECK(esc.find('|') == std::string::npos);
CHECK_EQ(tsUnescape(esc), raw);
}
TEST_CASE(escape_known)
{
CHECK_EQ(tsEscape("a b"), std::string("a\\sb"));
CHECK_EQ(tsEscape("a|b"), std::string("a\\pb"));
CHECK_EQ(tsEscape("a/b"), std::string("a\\/b"));
CHECK_EQ(tsUnescape("a\\sb"), std::string("a b"));
}
TEST_CASE(build_command)
{
CommandParams p;
p["client_nickname"] = "My Bot";
p["cid"] = "5";
auto cmd = buildCommand("clientmove", p);
// Params are ordered by key (map): cid before client_nickname.
CHECK_EQ(cmd, std::string("clientmove cid=5 client_nickname=My\\sBot"));
}
TEST_CASE(parse_notify)
{
auto pc = parseCommand(
"notifytextmessage targetmode=2 msg=hello\\sworld invokerid=7 "
"invokername=Alice");
CHECK_EQ(pc.name, std::string("notifytextmessage"));
CHECK_EQ(pc.params["targetmode"], std::string("2"));
CHECK_EQ(pc.params["msg"], std::string("hello world"));
CHECK_EQ(pc.params["invokername"], std::string("Alice"));
}
TEST_CASE(parse_pipe_groups)
{
auto pc = parseCommand("channellist cid=1 channel_name=Default|cid=2 "
"channel_name=Talk");
CHECK_EQ(pc.name, std::string("channellist"));
CHECK_EQ(pc.groups.size(), size_t(2));
CHECK_EQ(pc.groups[0]["cid"], std::string("1"));
CHECK_EQ(pc.groups[0]["channel_name"], std::string("Default"));
CHECK_EQ(pc.groups[1]["cid"], std::string("2"));
CHECK_EQ(pc.groups[1]["channel_name"], std::string("Talk"));
}
+123
View File
@@ -0,0 +1,123 @@
#include "check.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Util.hpp"
#include <string>
using namespace Echoion::Protocol;
using Crypto::ByteView;
namespace
{
Crypto::Bytes hex(const std::string& h) { return Util::fromHex(h); }
std::string hx(ByteView b) { return Util::toHex(b); }
std::string hx(const std::vector<uint8_t>& b)
{
return Util::toHex(ByteView(b.data(), b.size()));
}
template <size_t N> std::string hx(const std::array<uint8_t, N>& b)
{
return Util::toHex(ByteView(b.data(), b.size()));
}
} // namespace
// RFC 4493 AES-128-CMAC known-answer vectors.
TEST_CASE(cmac_rfc4493)
{
auto key = hex("2b7e151628aed2a6abf7158809cf4f3c");
// Example 1: empty message.
CHECK_EQ(hx(Crypto::cmac(key, {})),
std::string("bb1d6929e95937287fa37d129b756746"));
// Example 2: 16-byte message.
auto m2 = hex("6bc1bee22e409f96e93d7e117393172a");
CHECK_EQ(hx(Crypto::cmac(key, m2)),
std::string("070a16b46b4d4144f79bdd9dd04a287c"));
// Example 3: 40-byte message.
auto m3 = hex("6bc1bee22e409f96e93d7e117393172a"
"ae2d8a571e03ac9c9eb76fac45af8e51"
"30c81c46a35ce411");
CHECK_EQ(hx(Crypto::cmac(key, m3)),
std::string("dfa66747de9ae63030ca32611497c827"));
// Example 4: 64-byte message.
auto m4 = hex("6bc1bee22e409f96e93d7e117393172a"
"ae2d8a571e03ac9c9eb76fac45af8e51"
"30c81c46a35ce411e5fbc1191a0a52ef"
"f69f2445df4f9b17ad2b417be66c3710");
CHECK_EQ(hx(Crypto::cmac(key, m4)),
std::string("51f0bebf7e3b9d92fc49741779363cfe"));
}
// EAX specification test vectors (Bellare/Rogaway/Wagner). The EAX output is
// ciphertext||tag where tag is the full 16-byte value; TeamSpeak truncates the
// MAC to 8 bytes, so we compare against the first 8 tag bytes.
TEST_CASE(eax_spec_vectors)
{
// Empty message.
{
auto key = hex("233952dee4d5ed5f9b9c6d6ff80ff478");
auto nonce = hex("62ec67f9c3a4a407fcb2a8c49031a8b3");
auto hdr = hex("6bfb914fd07eae6b");
auto res = Crypto::eaxEncrypt(key, nonce, hdr, {});
CHECK(res.ciphertext.empty());
CHECK_EQ(hx(res.mac), std::string("e037830e8389f27b"));
// Round-trip.
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
CHECK(dec.has_value());
CHECK(dec && dec->empty());
}
// 2-byte message F7FB.
{
auto key = hex("91945d3f4dcbee0bf45ef52255f095a4");
auto nonce = hex("becaf043b0a23d843194ba972c66debd");
auto hdr = hex("fa3bfd4806eb53fa");
auto msg = hex("f7fb");
auto res = Crypto::eaxEncrypt(key, nonce, hdr, msg);
CHECK_EQ(hx(res.ciphertext), std::string("19dd"));
CHECK_EQ(hx(res.mac), std::string("5c4c9331049d0bda"));
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
CHECK(dec.has_value());
CHECK(dec && hx(*dec) == std::string("f7fb"));
// Tamper → reject.
auto bad = res.mac;
bad[0] ^= 0x01;
CHECK(!Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, bad));
}
}
TEST_CASE(sha_and_base64)
{
// sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d
std::string abc = "abc";
auto s1 = Crypto::sha1(
ByteView(reinterpret_cast<const uint8_t*>(abc.data()), abc.size()));
CHECK_EQ(hx(s1),
std::string("a9993e364706816aba3e25717850c26c9cd0d89d"));
// base64 round-trip + known value.
CHECK_EQ(Util::base64Encode(ByteView(
reinterpret_cast<const uint8_t*>("foobar"), 6)),
std::string("Zm9vYmFy"));
auto dec = Util::base64Decode("Zm9vYmFy");
CHECK_EQ(std::string(dec.begin(), dec.end()), std::string("foobar"));
}
// deriveKeyNonce: verify the packetId XOR into key[0..1] and the deterministic
// structure. Uses a fixed 20-byte ivStruct.
TEST_CASE(derive_key_nonce)
{
auto iv = hex("000102030405060708090a0b0c0d0e0f10111213"); // 20 bytes
auto a = Crypto::deriveKeyNonce(false, 0, 0, 2, iv);
auto b = Crypto::deriveKeyNonce(false, 0x0102, 0, 2, iv);
// key[0] ^= pid>>8, key[1] ^= pid&0xff; nonce unchanged.
CHECK_EQ(a.key[0] ^ 0x01, b.key[0]);
CHECK_EQ(a.key[1] ^ 0x02, b.key[1]);
CHECK_EQ(hx(a.nonce), hx(b.nonce));
// Direction changes the derivation.
auto c = Crypto::deriveKeyNonce(true, 0, 0, 2, iv);
CHECK(hx(a.key) != hx(c.key));
}
+52
View File
@@ -0,0 +1,52 @@
#include "check.hpp"
#include "echoion/protocol/Crypto.hpp"
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/Util.hpp"
#include <cstdio>
#include <string>
using namespace Echoion::Protocol;
TEST_CASE(identity_generate_uid_and_level)
{
auto id = Identity::generate(8);
// uid must equal base64(sha1(ascii(publicKeyString))).
auto h = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString().data()),
id.publicKeyString().size()));
CHECK_EQ(id.uid(),
Util::base64Encode(Crypto::ByteView(h.data(), h.size())));
// publicKeyString is valid base64 of a DER SEQUENCE (starts with 0x30).
auto der = Util::base64Decode(id.publicKeyString());
CHECK(!der.empty());
CHECK_EQ(der[0], uint8_t(0x30));
// Security level actually reached the requested threshold.
CHECK(id.securityLevel() >= 8);
}
TEST_CASE(identity_sign_verifiable_length)
{
auto id = Identity::generate(0);
std::string msg = "hello";
auto sig = id.sign(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(msg.data()), msg.size()));
// DER ECDSA signature over P-256 is ~70-72 bytes; never empty.
CHECK(!sig.empty());
CHECK(sig[0] == 0x30); // DER SEQUENCE
}
TEST_CASE(identity_save_load_roundtrip)
{
auto id = Identity::generate(0);
std::string path = "/tmp/echoion_identity_test.txt";
id.save(path);
auto loaded = Identity::load(path);
CHECK_EQ(loaded.publicKeyString(), id.publicKeyString());
CHECK_EQ(loaded.uid(), id.uid());
CHECK_EQ(loaded.keyOffset(), id.keyOffset());
std::remove(path.c_str());
}
+6
View File
@@ -0,0 +1,6 @@
#include "check.hpp"
int main()
{
return echotest::run();
}
+36
View File
@@ -0,0 +1,36 @@
#include "check.hpp"
#include "echoion/protocol/QuickLz.hpp"
using namespace Echoion::Protocol;
// QuickLZ level-1 "stored" (uncompressed) block: header byte with level=1
// (bits 2-3 = 01 -> 0x04), compressed bit (bit0) = 0, short size form
// (bit1 = 0) -> 3-byte header: [flags, compressedSize, decompressedSize].
TEST_CASE(qlz_stored_block)
{
Bytes payload = {'h', 'e', 'l', 'l', 'o'};
Bytes buf;
buf.push_back(0x04); // flags: level 1, not compressed, short header
buf.push_back(static_cast<uint8_t>(3 + payload.size())); // compressed size
buf.push_back(static_cast<uint8_t>(payload.size())); // decompressed size
buf.insert(buf.end(), payload.begin(), payload.end());
CHECK_EQ(qlzDecompressedSize(buf), uint32_t(payload.size()));
CHECK_EQ(qlzCompressedSize(buf), uint32_t(3 + payload.size()));
auto out = qlzDecompress(buf);
CHECK_EQ(out.size(), payload.size());
CHECK(out == payload);
}
TEST_CASE(qlz_rejects_bad_level)
{
Bytes buf = {0x00, 0x03, 0x00}; // level 0 -> unsupported
bool threw = false;
try {
qlzDecompress(buf);
} catch (const std::exception&) {
threw = true;
}
CHECK(threw);
}
+70
View File
@@ -0,0 +1,70 @@
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
#
# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load
# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's
# 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)
project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
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)
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil)
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED)
set(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin")
add_executable(EchoionStandalone
src/main.cpp
src/StandaloneClientInterface.cpp
src/AudioEncoder.cpp
# Reused, TeamSpeak-independent loader from the plugin (transition shim;
# 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
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${PLUGIN_DIR}/include"
)
target_link_libraries(EchoionStandalone PRIVATE
Echoion::Protocol
Echoion::ApiBase
Echoion::ApiPlugin
Echoion::ApiOpaque
Echoion::ApiPluginInterface
Echoion::ApiCoreInterface
Echoion::ApiLogger
Void::Data
Void::Log
Void::Stacktrace
dylib
Threads::Threads
PkgConfig::SWRESAMPLE
PkgConfig::OPUS
)
set_target_properties(EchoionStandalone PROPERTIES
OUTPUT_NAME "echoiond"
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
@@ -0,0 +1,42 @@
#pragma once
// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms
// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then
// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs
// the resampler's priming latency so every emitted frame is exactly 960/ch.
#include <cstdint>
#include <span>
#include <vector>
struct SwrContext;
struct OpusEncoder;
namespace Echoion::Standalone
{
class AudioEncoder
{
public:
// inRate defaults to Echoion's 192 kHz internal pipeline.
explicit AudioEncoder(int bitrate = 96000, int inRate = 192000);
~AudioEncoder();
AudioEncoder(const AudioEncoder&) = delete;
AudioEncoder& operator=(const AudioEncoder&) = delete;
// Feed one chunk of interleaved stereo S16 at inRate. Returns zero or
// more complete Opus frames (each a 20 ms packet).
std::vector<std::vector<uint8_t>>
encode(std::span<const short> interleaved);
private:
SwrContext* swr_ = nullptr;
OpusEncoder* enc_ = nullptr;
int inRate_ = 192000;
std::vector<short> pcm_; // resampled 48 kHz interleaved stereo
};
} // namespace Echoion::Standalone
@@ -0,0 +1,117 @@
#pragma once
// Implements Echoion's IPluginInterface against the native TeamSpeak UDP
// protocol (EchoionProtocol) instead of the TS3 Client Plugin SDK. This is the
// single seam that lets the whole Core run as a standalone application: Core
// only ever talks to IPluginInterface, so swapping this implementation in for
// the plugin drops the TeamSpeak-client dependency entirely.
#include <PluginInterface.hpp>
#include "echoion/protocol/Identity.hpp"
#include "echoion/protocol/TsClient.hpp"
#include <atomic>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace Echoion::Standalone
{
class AudioEncoder;
// Runtime knobs the protocol client needs that ServerConfig does not carry.
// Sourced from environment / defaults by main(), so no Core changes are
// required.
struct StandaloneSettings {
std::string identityPath; // where to load/persist the TS identity
int securityLevel = 8;
int opusBitrate = 96000;
};
class StandaloneClientInterface : public Api::IPluginInterface
{
public:
explicit StandaloneClientInterface(StandaloneSettings settings);
~StandaloneClientInterface() override;
// Lifecycle
Api::Result<void> initialize() override;
Api::Result<void> shutdown() override;
// Clients
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
// Channels
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
getChannel(uint64_t channelId) const override;
// Messaging
Api::Result<void>
sendTextMessage(uint64_t targetId,
const std::string& message) override;
Api::Result<void>
sendChannelMessage(uint64_t channelId,
const std::string& message) override;
Api::Result<void>
sendServerMessage(const std::string& message) override;
// Audio
Api::Result<void>
sendAudioData(const std::span<const short>& data) override;
Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
// Connection
Api::Result<void>
connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isConnected() const override;
Api::Result<void> reconnect() override;
// Events
void
registerEventCallback(const Api::EventCallback& cb) override;
void
unregisterEventCallback(const Api::EventCallback& cb) override;
private:
void wireCallbacks();
void onCommand(const Protocol::ParsedCommand& parsed);
void onTextMessage(const Protocol::CommandParams& params);
void broadcast(const Api::PluginEvent& event);
void upsertClientGroup(const Protocol::CommandParams& p,
bool emitConnected);
StandaloneSettings settings_;
std::unique_ptr<Protocol::Identity> identity_;
std::unique_ptr<Protocol::TsClient> client_;
std::unique_ptr<AudioEncoder> encoder_;
Api::ServerConfig currentConfig_{};
std::atomic<bool> initialized_{false};
mutable std::mutex mirrorMutex_;
std::map<uint64_t, Api::ClientInfo> clients_;
std::map<uint64_t, Api::ChannelInfo> channels_;
std::vector<uint64_t> whisperList_;
std::mutex cbMutex_;
std::vector<Api::EventCallback> callbacks_;
};
} // namespace Echoion::Standalone
+102
View File
@@ -0,0 +1,102 @@
#include "echoion/standalone/AudioEncoder.hpp"
extern "C" {
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
#include <opus/opus.h>
}
#include <stdexcept>
namespace Echoion::Standalone
{
namespace
{
constexpr int OUT_RATE = 48000;
constexpr int CHANNELS = 2;
constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel
constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS;
constexpr int MAX_OPUS = 4000;
} // namespace
AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate)
{
AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE,
&stereo, AV_SAMPLE_FMT_S16, inRate_, 0,
nullptr) < 0 ||
swr_init(swr_) < 0) {
throw std::runtime_error("AudioEncoder: swresample init failed");
}
int err = 0;
enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO,
&err);
if (err != OPUS_OK || !enc_) {
throw std::runtime_error("AudioEncoder: opus encoder init failed");
}
opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate));
opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC));
}
AudioEncoder::~AudioEncoder()
{
if (enc_) {
opus_encoder_destroy(enc_);
}
if (swr_) {
swr_free(&swr_);
}
}
std::vector<std::vector<uint8_t>>
AudioEncoder::encode(std::span<const short> interleaved)
{
std::vector<std::vector<uint8_t>> out;
const int inSamplesPerCh =
static_cast<int>(interleaved.size() / CHANNELS);
if (inSamplesPerCh <= 0) {
return out;
}
// Upper bound on resampled samples for this chunk.
int maxOut = static_cast<int>(
av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh,
OUT_RATE, inRate_, AV_ROUND_UP));
std::vector<short> resampled(
static_cast<size_t>(maxOut) * CHANNELS, 0);
const uint8_t* inPtr =
reinterpret_cast<const uint8_t*>(interleaved.data());
uint8_t* outPtr = reinterpret_cast<uint8_t*>(resampled.data());
int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr,
inSamplesPerCh);
if (gotPerCh < 0) {
return out;
}
pcm_.insert(pcm_.end(), resampled.begin(),
resampled.begin() +
static_cast<size_t>(gotPerCh) * CHANNELS);
// Emit as many full 20 ms frames as we have buffered.
size_t consumed = 0;
while (pcm_.size() - consumed >= static_cast<size_t>(FRAME_SHORTS)) {
uint8_t packet[MAX_OPUS];
int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES,
packet, MAX_OPUS);
if (n > 0) {
out.emplace_back(packet, packet + n);
}
consumed += FRAME_SHORTS;
}
if (consumed > 0) {
pcm_.erase(pcm_.begin(),
pcm_.begin() + static_cast<std::ptrdiff_t>(consumed));
}
return out;
}
} // namespace Echoion::Standalone
@@ -0,0 +1,495 @@
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include "echoion/standalone/AudioEncoder.hpp"
#include "echoion/protocol/Command.hpp"
#include <Void/Log/Log.hpp>
#include <chrono>
#include <filesystem>
namespace Echoion::Standalone
{
namespace
{
constexpr const char* LOG = "Standalone";
uint64_t toU64(const std::string& s)
{
try {
return std::stoull(s);
} catch (...) {
return 0;
}
}
std::string get(const Protocol::CommandParams& p, const char* k)
{
auto it = p.find(k);
return it == p.end() ? std::string{} : it->second;
}
} // namespace
StandaloneClientInterface::StandaloneClientInterface(
StandaloneSettings settings)
: settings_(std::move(settings))
{
}
StandaloneClientInterface::~StandaloneClientInterface()
{
(void)shutdown();
}
Api::Result<void> StandaloneClientInterface::initialize()
{
if (initialized_.exchange(true)) {
return {};
}
encoder_ = std::make_unique<AudioEncoder>(settings_.opusBitrate);
client_ = std::make_unique<Protocol::TsClient>();
Void::Log::info(LOG, "Standalone client interface initialized");
return {};
}
Api::Result<void> StandaloneClientInterface::shutdown()
{
if (!initialized_.exchange(false)) {
return {};
}
if (client_) {
client_->forceClose();
client_.reset();
}
encoder_.reset();
return {};
}
// ---- Connection --------------------------------------------------------
Api::Result<void>
StandaloneClientInterface::connectToServer(const Api::ServerConfig& config)
{
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized,
"interface not initialized");
}
currentConfig_ = config;
// Load or create the persistent identity.
try {
std::filesystem::path idPath(settings_.identityPath);
if (!idPath.empty() && std::filesystem::exists(idPath)) {
identity_ = std::make_unique<Protocol::Identity>(
Protocol::Identity::load(idPath.string()));
Void::Log::info(LOG, "Loaded identity (uid={})",
identity_->uid());
} else {
Void::Log::info(LOG,
"Generating identity (security level {})...",
settings_.securityLevel);
identity_ = std::make_unique<Protocol::Identity>(
Protocol::Identity::generate(settings_.securityLevel));
if (!idPath.empty()) {
std::filesystem::create_directories(idPath.parent_path());
identity_->save(idPath.string());
}
Void::Log::info(LOG, "Identity ready (uid={})",
identity_->uid());
}
} catch (const std::exception& e) {
return Api::fail(Api::ErrorCode::PluginError,
std::string("identity error: ") + e.what());
}
wireCallbacks();
Protocol::TsClientOptions opts;
opts.host = config.address;
opts.port = config.port ? config.port : 9987;
opts.identity = identity_.get();
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) {
return Api::fail(Api::ErrorCode::NetworkError,
std::string("connect failed: ") + e.what());
}
Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port,
opts.nickname);
return {};
}
void StandaloneClientInterface::wireCallbacks()
{
Protocol::TsClientCallbacks cb;
cb.onConnected = [this] {
// Ask the server to reveal all clients so the presence mirror fills.
client_->sendCommand("channelsubscribeall");
Api::PluginEvent ev;
ev.type = Api::PluginEventType::ConnectionEstablished;
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
};
cb.onDisconnected = [this] {
Void::Log::warn(LOG, "Disconnected from server");
};
cb.onError = [](const std::string& msg) {
Void::Log::error(LOG, "Protocol error: {}", msg);
};
cb.onCommand = [this](const Protocol::ParsedCommand& p) {
onCommand(p);
};
cb.onTextMessage = [this](const Protocol::CommandParams& p) {
onTextMessage(p);
};
cb.onDebug = [](const std::string& msg) {
Void::Log::debug(LOG, "{}", msg);
};
client_->setCallbacks(std::move(cb));
}
Api::Result<void> StandaloneClientInterface::disconnectFromServer()
{
if (client_) {
client_->disconnect();
}
return {};
}
bool StandaloneClientInterface::isConnected() const
{
return client_ &&
client_->state() == Protocol::ClientState::Connected;
}
Api::Result<void> StandaloneClientInterface::reconnect()
{
(void)disconnectFromServer();
return connectToServer(currentConfig_);
}
// ---- Event mirror ------------------------------------------------------
void StandaloneClientInterface::upsertClientGroup(
const Protocol::CommandParams& p, bool emitConnected)
{
uint64_t clid = toU64(get(p, "clid"));
if (clid == 0) {
return;
}
Api::ClientInfo info;
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
info = clients_[clid];
info.id = clid;
if (auto n = get(p, "client_nickname"); !n.empty()) {
info.nickname = n;
}
if (auto u = get(p, "client_unique_identifier"); !u.empty()) {
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) {
Api::PluginEvent ev;
ev.type = Api::PluginEventType::ClientConnected;
ev.clientId = clid;
ev.clientName = info.nickname;
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
}
void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p)
{
const auto& groups =
p.groups.empty()
? std::vector<Protocol::CommandParams>{p.params}
: p.groups;
if (p.name == "notifycliententerview") {
for (const auto& g : groups) {
upsertClientGroup(g, true);
}
} else if (p.name == "notifyclientleftview") {
for (const auto& g : groups) {
uint64_t clid = toU64(get(g, "clid"));
if (clid == 0) {
continue;
}
std::string name;
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
auto it = clients_.find(clid);
if (it != clients_.end()) {
name = it->second.nickname;
clients_.erase(it);
}
}
Api::PluginEvent ev;
ev.type = Api::PluginEventType::ClientDisconnected;
ev.clientId = clid;
ev.clientName = name;
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
} else if (p.name == "notifyclientmoved") {
for (const auto& g : groups) {
uint64_t clid = toU64(get(g, "clid"));
uint64_t ctid = toU64(get(g, "ctid"));
if (clid == 0) {
continue;
}
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
clients_[clid].id = clid;
clients_[clid].channelId = ctid;
}
Api::PluginEvent ev;
ev.type = Api::PluginEventType::ClientMoved;
ev.clientId = clid;
ev.targetChannelId = ctid;
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
} else if (p.name == "channellist" || p.name == "notifychannellist") {
std::lock_guard<std::mutex> lock(mirrorMutex_);
for (const auto& g : groups) {
uint64_t cid = toU64(get(g, "cid"));
if (cid == 0) {
continue;
}
Api::ChannelInfo ch = channels_[cid];
ch.id = cid;
if (auto n = get(g, "channel_name"); !n.empty()) {
ch.name = n;
}
if (auto pid = get(g, "pid"); !pid.empty()) {
ch.parentId = toU64(pid);
}
channels_[cid] = ch;
}
}
}
void StandaloneClientInterface::onTextMessage(
const Protocol::CommandParams& params)
{
uint64_t invoker = toU64(get(params, "invokerid"));
if (client_ && invoker == client_->clientId()) {
return; // ignore our own messages
}
Api::PluginEvent ev;
ev.type = Api::PluginEventType::TextMessageReceived;
ev.clientId = invoker;
ev.clientName = get(params, "invokername");
ev.message = get(params, "msg");
if (auto t = get(params, "target"); !t.empty()) {
ev.targetChannelId = toU64(t);
}
ev.timestamp = std::chrono::system_clock::now();
broadcast(ev);
}
void StandaloneClientInterface::broadcast(const Api::PluginEvent& event)
{
std::vector<Api::EventCallback> cbs;
{
std::lock_guard<std::mutex> lock(cbMutex_);
cbs = callbacks_;
}
for (const auto& cb : cbs) {
cb(event);
}
}
// ---- Clients / channels ------------------------------------------------
Api::Result<std::vector<Api::ClientInfo>>
StandaloneClientInterface::getClients()
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
std::vector<Api::ClientInfo> out;
out.reserve(clients_.size());
for (const auto& [id, c] : clients_) {
out.push_back(c);
}
return out;
}
Api::Result<std::optional<Api::ClientInfo>>
StandaloneClientInterface::getClient(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end()) {
return std::optional<Api::ClientInfo>{};
}
return std::optional<Api::ClientInfo>{it->second};
}
Api::Result<std::vector<Api::ChannelInfo>>
StandaloneClientInterface::getChannels() const
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
std::vector<Api::ChannelInfo> out;
out.reserve(channels_.size());
for (const auto& [id, c] : channels_) {
out.push_back(c);
}
return out;
}
Api::Result<std::optional<Api::ChannelInfo>>
StandaloneClientInterface::getChannel(uint64_t channelId) const
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
auto it = channels_.find(channelId);
if (it == channels_.end()) {
return std::optional<Api::ChannelInfo>{};
}
return std::optional<Api::ChannelInfo>{it->second};
}
Api::Result<void>
StandaloneClientInterface::moveClient(uint64_t clientId, uint64_t channelId)
{
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);
client_->sendCommand(Protocol::buildCommand("clientmove", p));
return {};
}
Api::Result<void>
StandaloneClientInterface::kickClient(uint64_t clientId,
const std::string& reason)
{
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;
client_->sendCommand(Protocol::buildCommand("clientkick", p));
return {};
}
// ---- Messaging ---------------------------------------------------------
Api::Result<void>
StandaloneClientInterface::sendTextMessage(uint64_t targetId,
const std::string& message)
{
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["targetmode"] = "1"; // client
p["target"] = std::to_string(targetId);
p["msg"] = message;
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
return {};
}
Api::Result<void>
StandaloneClientInterface::sendChannelMessage(uint64_t channelId,
const std::string& message)
{
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;
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
return {};
}
Api::Result<void>
StandaloneClientInterface::sendServerMessage(const std::string& message)
{
if (!client_) {
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
}
Protocol::CommandParams p;
p["targetmode"] = "3"; // server
p["msg"] = message;
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
return {};
}
// ---- Audio -------------------------------------------------------------
Api::Result<void>
StandaloneClientInterface::sendAudioData(const std::span<const short>& data)
{
if (!client_ || !encoder_ ||
client_->state() != Protocol::ClientState::Connected) {
return {};
}
std::vector<uint64_t> whisper;
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
whisper = whisperList_;
}
auto frames = encoder_->encode(data);
for (const auto& f : frames) {
if (whisper.empty()) {
client_->sendVoice(f);
} else {
std::vector<uint16_t> clients;
clients.reserve(whisper.size());
for (uint64_t c : whisper) {
clients.push_back(static_cast<uint16_t>(c));
}
client_->sendWhisper(f, {}, clients);
}
}
return {};
}
Api::Result<void> StandaloneClientInterface::setWhisperList(
const std::vector<uint64_t>& clientIds)
{
std::lock_guard<std::mutex> lock(mirrorMutex_);
whisperList_ = clientIds;
return {};
}
// ---- Events ------------------------------------------------------------
void StandaloneClientInterface::registerEventCallback(
const Api::EventCallback& cb)
{
std::lock_guard<std::mutex> lock(cbMutex_);
callbacks_.push_back(cb);
}
void StandaloneClientInterface::unregisterEventCallback(
const Api::EventCallback&)
{
// Callbacks are not individually comparable (std::function); the host
// registers a single Core callback for the process lifetime, so a full
// clear on unregister is sufficient and matches usage.
std::lock_guard<std::mutex> lock(cbMutex_);
callbacks_.clear();
}
} // namespace Echoion::Standalone
+166
View File
@@ -0,0 +1,166 @@
// Standalone Echoion host.
//
// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable
// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs
// IPluginInterface with a native TeamSpeak UDP protocol client instead of the
// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no
// TeamSpeak client, no Weston/RDP, no plugin directory.
#include "echoion/plugin/CoreLoader.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include <CoreInterface.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <atomic>
#include <condition_variable>
#include <csignal>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
namespace
{
std::atomic<bool> g_stop{false};
std::condition_variable g_cv;
std::mutex g_mu;
void onSignal(int)
{
g_stop = true;
g_cv.notify_all();
}
std::filesystem::path configDir()
{
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
return std::filesystem::path(x) / "echoion";
}
if (const char* h = std::getenv("HOME")) {
return std::filesystem::path(h) / ".config" / "echoion";
}
return std::filesystem::path(".") / "echoion";
}
std::string envOr(const char* key, const std::string& fallback)
{
const char* v = std::getenv(key);
return v ? std::string(v) : fallback;
}
int envInt(const char* key, int fallback)
{
const char* v = std::getenv(key);
if (!v) {
return fallback;
}
try {
return std::stoi(v);
} catch (...) {
return fallback;
}
}
// Locate the Core shared library ("Echoion.ts").
std::filesystem::path corePath()
{
if (const char* p = std::getenv("ECHOION_CORE_PATH")) {
return p;
}
for (const char* c :
{"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) {
if (std::filesystem::exists(c)) {
return c;
}
}
return "./Echoion.ts";
}
} // namespace
int main(int argc, char** argv)
{
std::set_terminate([] {
const auto frames = Void::Stacktrace::capture_stacktrace();
std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n';
std::abort();
});
std::filesystem::path cfgDir = configDir();
std::filesystem::path cfgPath = cfgDir / "config.json";
// Optional CLI: --config <path>
for (int i = 1; i + 1 < argc; ++i) {
if (std::string(argv[i]) == "--config") {
cfgPath = argv[i + 1];
}
}
Echoion::Standalone::StandaloneSettings settings;
settings.identityPath =
envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string());
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
auto interface = std::make_shared<Echoion::Standalone::StandaloneClientInterface>(
settings);
if (auto r = interface->initialize(); !r) {
Void::Log::error("main", "interface init failed: {}",
r.error().message);
return 1;
}
Echoion::Plugin::CoreLoader loader;
loader.setConfigPath(cfgPath);
auto corePathResolved = corePath();
Void::Log::info("main", "Loading Core from {}", corePathResolved.string());
if (auto r = loader.load(corePathResolved); !r) {
Void::Log::error("main", "failed to load Core: {}", r.error().message);
return 1;
}
auto core = loader.getCore();
if (!core) {
Void::Log::error("main", "Core not available after load");
return 1;
}
core->setPluginInterface(interface);
interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) {
std::ignore = core->onPluginEvent(ev);
});
// 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->registerEventCallback(
[c](const Echoion::Api::PluginEvent& ev) {
std::ignore = c->onPluginEvent(ev);
});
c->triggerAutoConnect();
}
});
core->triggerAutoConnect();
loader.enableAutoReload();
std::signal(SIGINT, onSignal);
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock, [] { return g_stop.load(); });
}
Void::Log::info("main", "Shutting down...");
loader.disableAutoReload();
(void)interface->disconnectFromServer();
(void)loader.unload();
(void)interface->shutdown();
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
# Echoion standalone daemon — connects to a TeamSpeak 3/6 server as its own
# client over the native UDP protocol. Replaces the old
# teamspeak-echoion.service, which had to run a full GUI TeamSpeak client under
# Weston + RDP just to host the plugin. None of that is needed anymore.
#
# Install: copy `echoiond` and `Echoion.ts` (the Core library) somewhere on
# disk, put config.json in ~/.config/echoion/ (or pass --config), then:
# systemctl --user enable --now echoion-standalone
#
# Identity is generated on first run and persisted to
# ~/.config/echoion/identity.txt (override with ECHOION_IDENTITY_PATH).
[Unit]
Description=Echoion Music Bot (standalone TeamSpeak client)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Directory holding echoiond and the Core library Echoion.ts.
WorkingDirectory=%h/echoion
Environment=ECHOION_CORE_PATH=%h/echoion/Echoion.ts
# Optional tuning:
# Environment=ECHOION_SECURITY_LEVEL=8
# Environment=ECHOION_OPUS_BITRATE=96000
# Environment=ECHOION_IDENTITY_PATH=%h/.config/echoion/identity.txt
ExecStart=%h/echoion/echoiond --config %h/.config/echoion/config.json
Restart=always
RestartSec=5
LimitNOFILE=65536
[Install]
WantedBy=default.target