Files
VoidTeamspeak/src/TsClient.cpp
T
faumaray 6dddf513b3 New arch
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 16:30:05 +03:00

1215 lines
34 KiB
C++

#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 <algorithm>
#include <array>
#include <chrono>
#include <cstring>
#include <filesystem>
#include <fstream>
#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)
{
if (thread_.joinable()) {
forceClose();
thread_.join();
}
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);
}
}
CommandResult TsClient::requestCommand(
const std::string& cmd, std::chrono::milliseconds timeout)
{
if (std::this_thread::get_id() == thread_.get_id()) {
return {{}, -1, "requestCommand cannot block the receive thread"};
}
// TeamSpeak returns data records without a request identifier; keep one
// response-bearing command in flight so those records remain unambiguous.
std::unique_lock<std::mutex> serialLock(requestSerialMutex_);
auto pending = std::make_shared<PendingRequest>();
pending->returnCode = "echoion-" + std::to_string(++requestId_);
{
// Keep queue insertion and wire send in the same order when callers
// issue requests concurrently.
std::lock_guard<std::recursive_mutex> sendLock(mu_);
if (state_.load() != ClientState::Connected) {
return {{}, -1, "client is not connected"};
}
{
std::lock_guard<std::mutex> pendingLock(pendingMutex_);
pendingRequests_.push_back(pending);
}
sendCommand(cmd + " return_code=" + pending->returnCode);
}
std::unique_lock<std::mutex> lock(pendingMutex_);
if (!pending->cv.wait_for(lock, timeout,
[&pending] { return pending->completed; })) {
const auto entry =
std::find(pendingRequests_.begin(), pendingRequests_.end(), pending);
if (entry != pendingRequests_.end()) {
pendingRequests_.erase(entry);
}
return {{}, -1, "command timed out"};
}
return pending->result;
}
CommandResult TsClient::downloadFile(
const std::string& remotePath, const std::string& destination,
uint64_t channelId, const std::string& channelPassword,
std::chrono::milliseconds timeout)
{
CommandParams parameters;
parameters["cid"] = std::to_string(channelId);
parameters["cpw"] = channelPassword;
parameters["name"] = remotePath;
parameters["clientftfid"] = std::to_string(++transferId_);
parameters["seekpos"] = "0";
auto result = requestCommand(buildCommand("ftinitdownload", parameters),
timeout);
if (!result.ok() || result.records.empty()) {
if (result.ok()) {
result.errorId = -1;
result.errorMessage = "file transfer returned no connection data";
}
return result;
}
const auto& record = result.records.front();
auto value = [&record](const char* name) -> std::string {
const auto entry = record.find(name);
return entry == record.end() ? std::string{} : entry->second;
};
const auto transferKey = value("ftkey");
const auto portText = value("port");
const auto sizeText = value("size");
if (transferKey.empty() || portText.empty() || sizeText.empty()) {
return {{}, -1, "file transfer response is incomplete"};
}
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* addresses = nullptr;
if (getaddrinfo(opts_.host.c_str(), portText.c_str(), &hints,
&addresses) != 0 || !addresses) {
return {{}, -1, "cannot resolve file-transfer endpoint"};
}
int transferSocket = -1;
for (auto* address = addresses; address; address = address->ai_next) {
transferSocket =
::socket(address->ai_family, address->ai_socktype,
address->ai_protocol);
if (transferSocket >= 0 &&
::connect(transferSocket, address->ai_addr, address->ai_addrlen) ==
0) {
break;
}
if (transferSocket >= 0) {
::close(transferSocket);
transferSocket = -1;
}
}
freeaddrinfo(addresses);
if (transferSocket < 0) {
return {{}, -1, "cannot connect to file-transfer endpoint"};
}
const auto temporary = destination + ".part";
if (const auto parent = std::filesystem::path(destination).parent_path();
!parent.empty()) {
std::error_code directoryError;
std::filesystem::create_directories(parent, directoryError);
if (directoryError) {
::close(transferSocket);
return {{}, -1, "cannot create file-transfer destination"};
}
}
std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
timeval socketTimeout{};
socketTimeout.tv_sec = static_cast<long>(
std::max<int64_t>(1, timeout.count() / 1000));
setsockopt(transferSocket, SOL_SOCKET, SO_RCVTIMEO, &socketTimeout,
sizeof(socketTimeout));
size_t keySent = 0;
while (keySent < transferKey.size()) {
const auto count = ::send(transferSocket, transferKey.data() + keySent,
transferKey.size() - keySent, 0);
if (count <= 0) {
break;
}
keySent += static_cast<size_t>(count);
}
if (!output || keySent != transferKey.size()) {
::close(transferSocket);
std::filesystem::remove(temporary);
return {{}, -1, "cannot start file transfer"};
}
std::array<char, 81920> buffer{};
uint64_t received = 0;
while (true) {
const auto count = ::recv(transferSocket, buffer.data(), buffer.size(), 0);
if (count == 0) {
break;
}
if (count < 0) {
output.close();
::close(transferSocket);
std::filesystem::remove(temporary);
return {{}, -1, "file transfer was interrupted"};
}
output.write(buffer.data(), count);
received += static_cast<uint64_t>(count);
}
::close(transferSocket);
output.close();
uint64_t expected = 0;
try {
expected = std::stoull(sizeText);
} catch (const std::exception&) {
std::filesystem::remove(temporary);
return {{}, -1, "invalid file-transfer size"};
}
if (!output || received != expected) {
std::filesystem::remove(temporary);
return {{}, -1, "file transfer size mismatch"};
}
std::error_code renameError;
std::filesystem::rename(temporary, destination, renameError);
if (renameError) {
std::filesystem::remove(temporary);
return {{}, -1, "cannot install downloaded file"};
}
return {};
}
void TsClient::sendVoice(std::span<const uint8_t> opus)
{
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 == "error") {
std::shared_ptr<PendingRequest> pending;
{
std::lock_guard<std::mutex> lock(pendingMutex_);
const auto returnCode = parsed.params.find("return_code");
if (!pendingRequests_.empty() &&
returnCode != parsed.params.end() &&
returnCode->second == pendingRequests_.front()->returnCode) {
pending = pendingRequests_.front();
pendingRequests_.pop_front();
if (const auto id = parsed.params.find("id");
id != parsed.params.end()) {
try {
pending->result.errorId = std::stoi(id->second);
} catch (const std::exception&) {
pending->result.errorId = -1;
}
}
if (const auto message = parsed.params.find("msg");
message != parsed.params.end()) {
pending->result.errorMessage = message->second;
}
pending->completed = true;
}
}
if (pending) {
pending->cv.notify_all();
}
} else if (!name.starts_with("notify") && name != "initivexpand" &&
name != "initivexpand2" && name != "initserver") {
std::lock_guard<std::mutex> lock(pendingMutex_);
if (!pendingRequests_.empty()) {
auto& records = pendingRequests_.front()->result.records;
if (parsed.groups.empty()) {
records.push_back(parsed.params);
} else {
records.insert(records.end(), parsed.groups.begin(),
parsed.groups.end());
}
}
}
if (name == "initivexpand") {
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);
}
cancelPendingRequests("connection closed");
}
void TsClient::cleanup()
{
if (state_.load() == ClientState::Disconnected) {
return;
}
state_ = ClientState::Disconnected;
running_ = false;
cancelPendingRequests("connection closed");
if (cb_.onDisconnected) {
cb_.onDisconnected();
}
}
void TsClient::cancelPendingRequests(const std::string& reason)
{
std::deque<std::shared_ptr<PendingRequest>> pending;
{
std::lock_guard<std::mutex> lock(pendingMutex_);
pending.swap(pendingRequests_);
for (const auto& request : pending) {
request->result.errorId = -1;
request->result.errorMessage = reason;
request->completed = true;
}
}
for (const auto& request : pending) {
request->cv.notify_all();
}
}
} // namespace Echoion::Protocol