Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-11 21:41:30 +03:00
1 parent 6dddf513b3
commit a7ffe73a6c
14 files changed
+700 -114

No files matched your search

+63 -36
View File
@@ -1,49 +1,76 @@
# 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 4.0)
project(VoidTeamspeak VERSION 0.1.0 LANGUAGES CXX)
cmake_minimum_required(VERSION 3.24)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
# Allow standalone configuration (own build) as well as add_subdirectory() from
# the Echoion root.
if(NOT DEFINED PROJECT_NAME)
project(EchoionProtocol LANGUAGES CXX)
option(VOID_TEAMSPEAK_BUILD_TESTS "Build VoidTeamspeak tests" OFF)
if(NOT TARGET Void::Functional)
include(FetchContent)
set(VOID_ENABLE_TESTING OFF CACHE BOOL "" FORCE)
set(_void_source "$ENV{HOME}/Project/Personal/VoidLibrary")
if(DEFINED CPM_Void_SOURCE)
set(_void_source "${CPM_Void_SOURCE}")
endif()
if(EXISTS "${_void_source}/CMakeLists.txt")
add_subdirectory("${_void_source}" "${CMAKE_CURRENT_BINARY_DIR}/Void")
else()
FetchContent_Declare(Void
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
GIT_TAG main)
FetchContent_MakeAvailable(Void)
endif()
endif()
option(ECHOIONPROTOCOL_BUILD_TESTS "Build EchoionProtocol unit tests" OFF)
find_package(OpenSSL REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
pkg_check_modules(OPUS IMPORTED_TARGET opus)
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 VOID_TEAMSPEAK_SOURCES CONFIGURE_DEPENDS "src/*.cpp")
add_library(VoidTeamspeak ${VOID_TEAMSPEAK_SOURCES})
add_library(Void::TeamSpeak ALIAS VoidTeamspeak)
# One-release source compatibility for Echoion consumers.
add_library(Echoion::Protocol ALIAS VoidTeamspeak)
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)
target_compile_features(VoidTeamspeak PUBLIC cxx_std_26)
target_include_directories(VoidTeamspeak PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
target_link_libraries(VoidTeamspeak
PUBLIC Void::Functional Void::Log Void::System Void::Net
PRIVATE OpenSSL::Crypto PkgConfig::SODIUM)
if(TARGET PkgConfig::OPUS)
target_link_libraries(EchoionProtocol PUBLIC PkgConfig::OPUS)
target_compile_definitions(EchoionProtocol PUBLIC ECHOION_HAVE_OPUS=1)
target_link_libraries(VoidTeamspeak PRIVATE PkgConfig::OPUS)
target_compile_definitions(VoidTeamspeak PUBLIC VOID_TEAMSPEAK_HAVE_OPUS=1)
endif()
if(ECHOIONPROTOCOL_BUILD_TESTS OR BUILD_TESTS)
if(NOT MSVC)
target_compile_options(VoidTeamspeak PRIVATE
-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow)
endif()
install(TARGETS VoidTeamspeak EXPORT VoidTeamspeakTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(EXPORT VoidTeamspeakTargets FILE VoidTeamspeakTargets.cmake
NAMESPACE Void:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VoidTeamspeak)
configure_package_config_file(cmake/VoidTeamspeakConfig.cmake.in
"${CMAKE_CURRENT_BINARY_DIR}/VoidTeamspeakConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VoidTeamspeak)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/VoidTeamspeakConfigVersion.cmake"
VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion)
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/VoidTeamspeakConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/VoidTeamspeakConfigVersion.cmake"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VoidTeamspeak)
if(VOID_TEAMSPEAK_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
+60 -35
View File
@@ -1,47 +1,72 @@
# EchoionProtocol
# VoidTeamspeak
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.
VoidTeamspeak is a modern C++26 implementation of the TeamSpeak 3/6 native
client protocol. It connects as a real voice client without embedding the
official GUI client or depending on its proprietary ClientLib.
TeamSpeak 6 has **no WebRTC voice** — its voice is still the legacy TS3 UDP
protocol on port 9987, which this library speaks.
The public API follows the concepts of the original TeamSpeak Client SDK while
using RAII, strong IDs, chrono durations, spans, typed events, and
`Void::Result`. The compatibility implementation currently lives below the
modern facade and will be removed after the Echoion migration release.
## Modules
## Public API
| 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. |
```cpp
#include <Void/TeamSpeak/TeamSpeak.hpp>
## Dependencies
auto identity = std::make_shared<Void::TeamSpeak::Identity>(
Void::TeamSpeak::Identity::load("identity.txt"));
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.
Void::TeamSpeak::Client client;
client.setEvents({
.connected = [] { /* ready */ },
.error = [](const Void::TeamSpeak::Error& error) { /* report */ },
});
## Build & test standalone
```bash
cmake -S . -B build -DECHOIONPROTOCOL_BUILD_TESTS=ON
cmake --build build
./build/tests/echoion_protocol_tests
auto connected = client.connect({
.host = "voice.example.net",
.identity = std::move(identity),
.nickname = "music bot",
});
```
## Verified
Each `Client` owns one connection, packet sequence, and transmitted audio
timeline. To send different audio to different audiences simultaneously,
create one `Client` per timeline and give each client independent
`WhisperTargets`.
- 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.
## Build
## Not yet integration-tested against a live server
```sh
cmake -S . -B build \
-DCPM_Void_SOURCE="$HOME/Project/Personal/VoidLibrary" \
-DVOID_TEAMSPEAK_BUILD_TESTS=ON
cmake --build build
ctest --test-dir build --output-on-failure
```
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.
Dependencies are VoidLibrary, OpenSSL, libsodium, and optionally libopus.
## SDK mapping
The detailed and deliberately conservative status is tracked in
[`SDK_PARITY.md`](SDK_PARITY.md).
| Original Client SDK concept | VoidTeamspeak |
|---|---|
| connection handler ID | owning `Client` object |
| `ts3client_startConnection` | `Client::connect(ConnectOptions)` |
| `ts3client_stopConnection` | `Client::disconnect()` |
| `ts3client_getClientID` | `Client::id()` returning `ClientId` |
| request + return code callback | `Client::request()` returning a typed result |
| whisper-list arrays | `WhisperTargets` with strong channel/client IDs |
| global callback table | per-client `Events` |
| raw voice buffers | `sendVoice` / `sendWhisper` spans |
Operations that exist only inside the official GUI client will return a typed
`NotSupported` error as the broader SDK facade is filled out.
## License
MIT. The initial protocol implementation was ported from MIT-licensed
`ts6-manager` and cross-checked against public protocol documentation.
+27
View File
@@ -0,0 +1,27 @@
# TeamSpeak Client SDK parity
VoidTeamspeak models the original Client SDK as an owning modern C++ API. It
does not reproduce the proprietary C ABI.
| Capability | Status | Modern interface |
|---|---|---|
| Library/client lifecycle | Implemented | `ClientLibrary`, RAII `Client` |
| Identity generation/import/security level | Implemented | `Identity` |
| Connect/disconnect/state/client ID | Implemented | `Client` |
| Raw requests and typed responses | Implemented | `Client::request` |
| Client and channel lists | Implemented | `clients`, `channels` |
| Text messaging | Implemented | `sendText` |
| Client move and kick | Implemented | `move`, `kick` |
| Server groups | Implemented | `serverGroups`, add/remove client |
| Voice and whisper transmission | Implemented | `sendVoice`, `sendWhisper` |
| Independent voice timelines | Implemented | one `Client` per timeline |
| Voice receive callback | Implemented | `Events::voice` |
| File download | Implemented | `download` |
| Typed server/channel/client notifications | Partial | typed command event plus raw request fallback |
| Permissions and channel groups | Partial | raw request fallback |
| File upload/delete | Planned | raw request fallback |
| Audio preprocessing/device GUI | Not applicable | client-local SDK behavior |
| GUI contacts, hotkeys, overlays | Not applicable | client-local SDK behavior |
An entry is marked implemented only when it is present in the public modern
facade and backed by protocol tests or the existing live handshake path.
+7
View File
@@ -0,0 +1,7 @@
@PACKAGE_INIT@
include(CMakeFindDependencyMacro)
find_dependency(Void CONFIG REQUIRED)
find_dependency(OpenSSL REQUIRED)
find_dependency(PkgConfig REQUIRED)
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
include("${CMAKE_CURRENT_LIST_DIR}/VoidTeamspeakTargets.cmake")
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <Void/TeamSpeak/Types.hpp>
#include <chrono>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::TeamSpeak
{
struct ConnectOptions {
std::string host;
std::uint16_t port{9987};
std::shared_ptr<Identity> identity;
std::string nickname{"VoidTeamspeak"};
std::string serverPassword;
std::string defaultChannel;
std::string channelPassword;
};
struct CommandResponse {
using Record = std::map<std::string, std::string>;
std::vector<Record> records;
};
struct Events {
std::function<void()> connected;
std::function<void()> disconnected;
std::function<void(const Error&)> error;
std::function<void(std::string_view)> debug;
std::function<void(std::string_view,
const std::map<std::string, std::string>&)> command;
std::function<void(std::span<const std::uint8_t>)> voice;
};
class Client final
{
public:
Client();
~Client();
Client(Client&&) noexcept;
Client& operator=(Client&&) noexcept;
Client(const Client&) = delete;
Client& operator=(const Client&) = delete;
void setEvents(Events events);
[[nodiscard]] Void::Result::Result<void, Error>
connect(const ConnectOptions& options);
void disconnect() noexcept;
void close() noexcept;
[[nodiscard]] ConnectionState state() const noexcept;
[[nodiscard]] ClientId id() const noexcept;
[[nodiscard]] Void::Result::Result<CommandResponse, Error>
request(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::seconds{3});
[[nodiscard]] Void::Result::Result<std::vector<RemoteClient>, Error>
clients(std::chrono::milliseconds timeout = std::chrono::seconds{3});
[[nodiscard]] Void::Result::Result<std::vector<Channel>, Error>
channels(std::chrono::milliseconds timeout = std::chrono::seconds{3});
[[nodiscard]] Void::Result::Result<std::vector<ServerGroup>, Error>
serverGroups(
std::chrono::milliseconds timeout = std::chrono::seconds{3});
[[nodiscard]] Void::Result::Result<void, Error>
addToServerGroup(ServerGroupId group, ClientDatabaseId client);
[[nodiscard]] Void::Result::Result<void, Error>
removeFromServerGroup(ServerGroupId group, ClientDatabaseId client);
[[nodiscard]] Void::Result::Result<void, Error>
sendText(TextTarget target, std::string_view message);
[[nodiscard]] Void::Result::Result<void, Error>
move(ClientId client, ChannelId channel);
[[nodiscard]] Void::Result::Result<void, Error>
kick(ClientId client, std::string_view reason);
[[nodiscard]] Void::Result::Result<std::filesystem::path, Error>
download(std::string_view remotePath,
const std::filesystem::path& destination,
ChannelId channel = {},
std::string_view channelPassword = {},
std::chrono::milliseconds timeout = std::chrono::seconds{10});
[[nodiscard]] Void::Result::Result<void, Error>
sendVoice(std::span<const std::uint8_t> opusFrame);
[[nodiscard]] Void::Result::Result<void, Error>
sendWhisper(std::span<const std::uint8_t> opusFrame,
const WhisperTargets& targets);
void stopVoice() noexcept;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <echoion/protocol/Identity.hpp>
namespace Void::TeamSpeak
{
// Modern public name; the implementation remains source-compatible during
// the extraction release.
using Identity = Echoion::Protocol::Identity;
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <Void/TeamSpeak/Client.hpp>
#include <memory>
#include <string_view>
namespace Void::TeamSpeak
{
/// Process-level entry point corresponding to the original Client SDK
/// library lifecycle. It is intentionally cheap and RAII-managed: clients
/// own their actual network and callback resources.
class ClientLibrary final
{
public:
static constexpr std::string_view version() noexcept { return "0.1.0"; }
[[nodiscard]] std::unique_ptr<Client> createClient() const
{
return std::make_unique<Client>();
}
};
}
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <Void/TeamSpeak/Client.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <Void/TeamSpeak/Library.hpp>
#include <Void/TeamSpeak/Types.hpp>
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include <cstdint>
#include <string>
#include <optional>
#include <vector>
namespace Void::TeamSpeak
{
template <typename Tag, typename Value>
struct Id {
Value value{};
explicit constexpr operator bool() const noexcept { return value != 0; }
auto operator<=>(const Id&) const = default;
};
using ClientId = Id<struct ClientIdTag, std::uint16_t>;
using ClientDatabaseId = Id<struct ClientDatabaseIdTag, std::uint64_t>;
using ChannelId = Id<struct ChannelIdTag, std::uint64_t>;
using ServerConnectionId = Id<struct ServerConnectionIdTag, std::uint64_t>;
using ServerGroupId = Id<struct ServerGroupIdTag, std::uint64_t>;
using ChannelGroupId = Id<struct ChannelGroupIdTag, std::uint64_t>;
using PermissionId = Id<struct PermissionIdTag, std::uint32_t>;
enum class ConnectionState {
Disconnected,
Initializing,
Handshaking,
Connected,
Disconnecting,
};
struct WhisperTargets {
std::vector<ChannelId> channels;
std::vector<ClientId> clients;
[[nodiscard]] bool empty() const noexcept
{
return channels.empty() && clients.empty();
}
};
struct RemoteClient {
ClientId id;
ChannelId channel;
std::string nickname;
std::string uniqueId;
};
struct Channel {
ChannelId id;
std::optional<ChannelId> parent;
std::string name;
bool passwordProtected{false};
};
struct ServerGroup {
ServerGroupId id;
std::string name;
int type{};
};
enum class TextTargetKind { Client = 1, Channel = 2, Server = 3 };
struct TextTarget {
TextTargetKind kind{TextTargetKind::Client};
std::uint64_t id{};
};
struct Error {
enum class Code {
InvalidArgument,
NotConnected,
Timeout,
Protocol,
Io,
NotSupported,
} code{Code::Protocol};
std::string message;
};
}
+2 -1
View File
@@ -10,6 +10,7 @@
#include "echoion/protocol/Command.hpp"
#include "echoion/protocol/Identity.hpp"
#include <Void/Net/Socket.hpp>
#include <atomic>
#include <chrono>
@@ -173,7 +174,7 @@ namespace Echoion::Protocol
TsClientOptions opts_;
TsClientCallbacks cb_;
int sock_ = -1;
Void::Net::UdpSocket socket_;
std::atomic<ClientState> state_{ClientState::Disconnected};
std::atomic<uint16_t> clientId_{0};
+273
View File
@@ -0,0 +1,273 @@
#include <Void/TeamSpeak/Client.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <echoion/protocol/TsClient.hpp>
#include <echoion/protocol/Command.hpp>
#include <exception>
#include <charconv>
#include <system_error>
#include <utility>
namespace Void::TeamSpeak
{
class Client::Impl {
public:
Echoion::Protocol::TsClient client;
Events events;
};
namespace
{
Error protocolError(std::string message)
{
return Error{Error::Code::Protocol, std::move(message)};
}
ConnectionState convert(Echoion::Protocol::ClientState state)
{
using Old = Echoion::Protocol::ClientState;
switch (state) {
case Old::Disconnected: return ConnectionState::Disconnected;
case Old::Init: return ConnectionState::Initializing;
case Old::Handshake: return ConnectionState::Handshaking;
case Old::Connected: return ConnectionState::Connected;
case Old::Disconnecting: return ConnectionState::Disconnecting;
}
return ConnectionState::Disconnected;
}
std::uint64_t number(const Echoion::Protocol::CommandParams& record,
std::string_view key)
{
const auto iterator = record.find(std::string{key});
if (iterator == record.end()) return 0;
std::uint64_t value = 0;
auto [end, error] = std::from_chars(iterator->second.data(),
iterator->second.data() + iterator->second.size(), value);
return error == std::errc{} && end == iterator->second.data() +
iterator->second.size() ? value : 0;
}
std::string text(const Echoion::Protocol::CommandParams& record,
std::string_view key)
{
const auto iterator = record.find(std::string{key});
return iterator == record.end() ? std::string{} : iterator->second;
}
}
Client::Client() : impl_(std::make_unique<Impl>()) {}
Client::~Client() = default;
Client::Client(Client&&) noexcept = default;
Client& Client::operator=(Client&&) noexcept = default;
void Client::setEvents(Events events)
{
impl_->events = std::move(events);
auto* impl = impl_.get();
Echoion::Protocol::TsClientCallbacks callbacks;
callbacks.onConnected = [impl] { if (impl->events.connected) impl->events.connected(); };
callbacks.onDisconnected = [impl] { if (impl->events.disconnected) impl->events.disconnected(); };
callbacks.onError = [impl](const std::string& message) {
if (impl->events.error) impl->events.error(protocolError(message));
};
callbacks.onDebug = [impl](const std::string& message) {
if (impl->events.debug) impl->events.debug(message);
};
callbacks.onCommand = [impl](const Echoion::Protocol::ParsedCommand& command) {
if (impl->events.command) impl->events.command(command.name, command.params);
};
callbacks.onVoice = [impl](std::span<const std::uint8_t> voice) {
if (impl->events.voice) impl->events.voice(voice);
};
impl_->client.setCallbacks(std::move(callbacks));
}
Void::Result::Result<void, Error> Client::connect(const ConnectOptions& options)
{
if (options.host.empty() || !options.identity) {
return Void::Result::fail(Error{Error::Code::InvalidArgument,
"host and identity are required"});
}
Echoion::Protocol::TsClientOptions old;
old.host = options.host;
old.port = options.port;
old.identity = options.identity.get();
old.nickname = options.nickname;
old.serverPassword = options.serverPassword;
old.defaultChannel = options.defaultChannel;
old.channelPassword = options.channelPassword;
try {
impl_->client.connect(old);
return {};
} catch (const std::exception& exception) {
return Void::Result::fail(Error{Error::Code::Io, exception.what()});
}
}
void Client::disconnect() noexcept { impl_->client.disconnect(); }
void Client::close() noexcept { impl_->client.forceClose(); }
ConnectionState Client::state() const noexcept { return convert(impl_->client.state()); }
ClientId Client::id() const noexcept { return ClientId{impl_->client.clientId()}; }
Void::Result::Result<CommandResponse, Error>
Client::request(std::string_view command, std::chrono::milliseconds timeout)
{
auto result = impl_->client.requestCommand(std::string{command}, timeout);
if (!result.ok()) {
return Void::Result::fail(protocolError(result.errorMessage));
}
return CommandResponse{std::move(result.records)};
}
Void::Result::Result<std::vector<RemoteClient>, Error>
Client::clients(std::chrono::milliseconds timeout)
{
auto response = request("clientlist -uid", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<RemoteClient> result;
result.reserve(response->records.size());
for (const auto& record : response->records) {
result.push_back(RemoteClient{
.id = ClientId{static_cast<std::uint16_t>(number(record, "clid"))},
.channel = ChannelId{number(record, "cid")},
.nickname = text(record, "client_nickname"),
.uniqueId = text(record, "client_unique_identifier")});
}
return result;
}
Void::Result::Result<std::vector<Channel>, Error>
Client::channels(std::chrono::milliseconds timeout)
{
auto response = request("channellist -flags", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<Channel> result;
result.reserve(response->records.size());
for (const auto& record : response->records) {
const auto parent = number(record, "pid");
result.push_back(Channel{
.id = ChannelId{number(record, "cid")},
.parent = parent == 0 ? std::nullopt
: std::optional{ChannelId{parent}},
.name = text(record, "channel_name"),
.passwordProtected = number(record, "channel_flag_password") != 0});
}
return result;
}
Void::Result::Result<std::vector<ServerGroup>, Error>
Client::serverGroups(std::chrono::milliseconds timeout)
{
auto response = request("servergrouplist", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<ServerGroup> result;
result.reserve(response->records.size());
for (const auto& record : response->records) {
result.push_back(ServerGroup{
.id = ServerGroupId{number(record, "sgid")},
.name = text(record, "name"),
.type = static_cast<int>(number(record, "type"))});
}
return result;
}
Void::Result::Result<void, Error>
Client::addToServerGroup(ServerGroupId group, ClientDatabaseId client)
{
Echoion::Protocol::CommandParams params{
{"sgid", std::to_string(group.value)},
{"cldbid", std::to_string(client.value)}};
auto response = request(Echoion::Protocol::buildCommand(
"servergroupaddclient", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::removeFromServerGroup(ServerGroupId group, ClientDatabaseId client)
{
Echoion::Protocol::CommandParams params{
{"sgid", std::to_string(group.value)},
{"cldbid", std::to_string(client.value)}};
auto response = request(Echoion::Protocol::buildCommand(
"servergroupdelclient", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::sendText(TextTarget target, std::string_view message)
{
Echoion::Protocol::CommandParams params;
params["targetmode"] = std::to_string(static_cast<int>(target.kind));
if (target.kind != TextTargetKind::Server)
params["target"] = std::to_string(target.id);
params["msg"] = std::string{message};
auto response = request(Echoion::Protocol::buildCommand(
"sendtextmessage", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::move(ClientId client, ChannelId channel)
{
Echoion::Protocol::CommandParams params{
{"clid", std::to_string(client.value)},
{"cid", std::to_string(channel.value)}};
auto response = request(Echoion::Protocol::buildCommand("clientmove", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::kick(ClientId client, std::string_view reason)
{
Echoion::Protocol::CommandParams params{
{"clid", std::to_string(client.value)}, {"reasonid", "5"},
{"reasonmsg", std::string{reason}}};
auto response = request(Echoion::Protocol::buildCommand("clientkick", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<std::filesystem::path, Error>
Client::download(std::string_view remotePath,
const std::filesystem::path& destination, ChannelId channel,
std::string_view password, std::chrono::milliseconds timeout)
{
auto result = impl_->client.downloadFile(std::string{remotePath}, destination.string(),
channel.value, std::string{password}, timeout);
if (!result.ok()) return Void::Result::fail(protocolError(result.errorMessage));
return destination;
}
Void::Result::Result<void, Error>
Client::sendVoice(std::span<const std::uint8_t> frame)
{
if (state() != ConnectionState::Connected)
return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"});
impl_->client.sendVoice(frame);
return {};
}
Void::Result::Result<void, Error>
Client::sendWhisper(std::span<const std::uint8_t> frame,
const WhisperTargets& targets)
{
if (state() != ConnectionState::Connected)
return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"});
std::vector<std::uint64_t> channels;
std::vector<std::uint16_t> clients;
channels.reserve(targets.channels.size());
clients.reserve(targets.clients.size());
for (auto value : targets.channels) channels.push_back(value.value);
for (auto value : targets.clients) clients.push_back(value.value);
impl_->client.sendWhisper(frame, channels, clients);
return {};
}
void Client::stopVoice() noexcept { impl_->client.sendVoiceStop(); }
}
+13 -41
View File
@@ -9,7 +9,6 @@
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
@@ -136,30 +135,11 @@ namespace Echoion::Protocol
}
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);
auto connected = Void::Net::UdpSocket::connect(opts.host, opts.port);
if (!connected) {
throw std::runtime_error("TsClient: " + connected.error().message());
}
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);
socket_ = std::move(*connected);
// Reset all per-connection state.
state_ = ClientState::Init;
@@ -192,29 +172,23 @@ namespace Echoion::Protocol
void TsClient::loopThread()
{
while (running_.load()) {
pollfd pfd{};
pfd.fd = sock_;
pfd.events = POLLIN;
int rc = ::poll(&pfd, 1, 100);
auto readable = socket_.wait_readable(std::chrono::milliseconds{100});
if (!running_.load()) {
break;
}
std::lock_guard<std::recursive_mutex> lock(mu_);
if (rc > 0 && (pfd.revents & POLLIN)) {
if (readable && *readable) {
uint8_t buf[2048];
ssize_t n = ::recv(sock_, buf, sizeof(buf), 0);
if (n > 0) {
auto received = socket_.receive(buf);
if (received && *received > 0) {
handleIncomingPacket(
std::span<const uint8_t>(buf, static_cast<size_t>(n)));
std::span<const uint8_t>(buf, *received));
}
}
resendTick();
}
std::lock_guard<std::recursive_mutex> lock(mu_);
if (sock_ >= 0) {
::close(sock_);
sock_ = -1;
}
socket_.close();
}
// ---- Outgoing ----------------------------------------------------------
@@ -333,10 +307,10 @@ namespace Echoion::Protocol
void TsClient::sendRawLocked(const std::vector<uint8_t>& raw)
{
if (sock_ < 0) {
if (!socket_.valid()) {
return;
}
::send(sock_, raw.data(), raw.size(), 0);
std::ignore = socket_.send(raw);
}
void TsClient::sendCommand(const std::string& cmd)
@@ -1175,9 +1149,7 @@ namespace Echoion::Protocol
}
state_ = ClientState::Disconnected;
running_ = false;
if (sock_ >= 0) {
::shutdown(sock_, SHUT_RDWR);
}
socket_.shutdown();
cancelPendingRequests("connection closed");
}
+1 -1
View File
@@ -5,7 +5,7 @@ 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_link_libraries(echoion_protocol_tests PRIVATE Void::TeamSpeak)
target_include_directories(echoion_protocol_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}")
+37
View File
@@ -0,0 +1,37 @@
#include "check.hpp"
#include <Void/TeamSpeak/TeamSpeak.hpp>
using namespace Void::TeamSpeak;
TEST_CASE(modern_library_creates_independent_clients)
{
ClientLibrary library;
auto first = library.createClient();
auto second = library.createClient();
CHECK(first != nullptr);
CHECK(second != nullptr);
CHECK(first.get() != second.get());
CHECK_EQ(first->state(), ConnectionState::Disconnected);
CHECK_EQ(second->state(), ConnectionState::Disconnected);
}
TEST_CASE(strong_ids_do_not_erase_target_types)
{
WhisperTargets targets{
.channels = {ChannelId{42}},
.clients = {ClientId{7}, ClientId{8}},
};
CHECK(!targets.empty());
CHECK_EQ(targets.channels.front().value, std::uint64_t{42});
CHECK_EQ(targets.clients.size(), std::size_t{2});
CHECK(ClientId{7} != ClientId{8});
}
TEST_CASE(connect_options_are_validated_before_network_io)
{
Client client;
auto result = client.connect({});
CHECK(!result.has_value());
CHECK_EQ(result.error().code, Error::Code::InvalidArgument);
}