#pragma once // Full-client connection to a TeamSpeak 3/6 server over the native UDP voice // protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and // voice send path. Ported from ts6-manager tslib/client.ts. // // Threading: a single background thread runs the receive + timer loop. Public // send methods are thread-safe (guarded by an internal mutex) so the audio // thread can call sendVoice() directly. Callbacks fire on the loop thread. #include "echoion/protocol/Command.hpp" #include "echoion/protocol/Identity.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Protocol { enum class PacketType : uint8_t { Voice = 0, VoiceWhisper = 1, Command = 2, CommandLow = 3, Ping = 4, Pong = 5, Ack = 6, AckLow = 7, Init1 = 8, }; enum class ClientState { Disconnected, Init, Handshake, Connected, Disconnecting, }; struct TsClientOptions { std::string host; uint16_t port = 9987; const Identity* identity = nullptr; // not owned std::string nickname = "EchoionBot"; std::string serverPassword; std::string defaultChannel; // channel id or name std::string channelPassword; }; // All callbacks fire on the internal loop thread. struct TsClientCallbacks { std::function onConnected; std::function onDisconnected; std::function onError; std::function onCommand; std::function onTextMessage; std::function)> onVoice; std::function onDebug; }; struct CommandResult { std::vector records; int errorId = 0; std::string errorMessage; [[nodiscard]] bool ok() const noexcept { return errorId == 0; } }; class TsClient { public: TsClient(); ~TsClient(); TsClient(const TsClient&) = delete; TsClient& operator=(const TsClient&) = delete; void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); } // Begin connecting. Returns immediately; onConnected/onError fire // asynchronously. Throws only on immediate socket setup failure. void connect(const TsClientOptions& opts); // Graceful: send clientdisconnect, then close. void disconnect(); // Immediate close, no disconnect command. void forceClose(); ClientState state() const { return state_.load(); } uint16_t clientId() const { return clientId_.load(); } // Send one already-Opus-encoded 20 ms frame to the current channel. void sendVoice(std::span opus); // Whisper the frame to the given channel/client targets. void sendWhisper(std::span opus, const std::vector& channelIds, const std::vector& clientIds); // End-of-voice marker (empty frame). void sendVoiceStop(); // Send a raw pre-built TS3 command line (fragmented if large). void sendCommand(const std::string& cmd); // Send a command and wait for its data records plus terminating // `error` response. Safe to call from threads other than the receive // callback thread. CommandResult requestCommand( const std::string& cmd, std::chrono::milliseconds timeout = std::chrono::seconds{3}); CommandResult downloadFile( const std::string& remotePath, const std::string& destination, uint64_t channelId = 0, const std::string& channelPassword = {}, std::chrono::milliseconds timeout = std::chrono::seconds{10}); private: // ---- packet path ---- void loopThread(); void handleIncomingPacket(std::span raw); void sendOutgoing(std::span data, PacketType type, uint8_t extraFlags = 0); std::vector buildRawPacket(std::span data, PacketType type, uint16_t packetId, uint8_t flags); void encryptPacket(std::vector& raw, PacketType type, uint16_t packetId, uint32_t gen, uint8_t flags, std::span data); std::vector decryptPacket(std::span raw, PacketType type, uint16_t packetId, uint32_t gen, uint8_t flags, bool& ok); void sendRawLocked(const std::vector& raw); void sendInitPacket(const std::vector& data); // ---- handshake / commands ---- std::vector buildInit0(); void handleInit(std::span data); void handleCommandData(std::span data, uint8_t flags); void processCommand(std::span data, uint8_t flags); void handleInitIvExpand(const CommandParams& params); void handleInitIvExpand2(const CommandParams& params); void sendClientInit(); void handleInitServer(const CommandParams& params); void handleChannelList(const ParsedCommand& parsed); void handleChannelListFinished(); void sendAck(uint16_t ackId, PacketType ackType); void handlePing(uint16_t packetId); void resendTick(); void debug(const std::string& msg); void cleanup(); void cancelPendingRequests(const std::string& reason); // counters / crypto struct Counter { uint16_t id = 0; uint32_t gen = 0; }; Counter getCounter(PacketType type); void incCounter(PacketType type); TsClientOptions opts_; TsClientCallbacks cb_; int sock_ = -1; std::atomic state_{ClientState::Disconnected}; std::atomic clientId_{0}; std::thread thread_; std::atomic running_{false}; // Recursive: command handlers running under the loop lock call // sendCommand()/sendOutgoing() which re-lock. mutable std::recursive_mutex mu_; int64_t disconnectDeadline_ = 0; std::array packetCounter_{}; std::array generationCounter_{}; bool cryptoInitComplete_ = false; std::vector ivStruct_; std::array fakeSignature_{}; std::vector alphaTmp_; // resend tracking struct Resend { std::vector raw; uint16_t packetId = 0; int64_t firstSend = 0; int64_t lastSend = 0; }; std::map resendMap_; std::unique_ptr initResend_; int64_t lastMessageTime_ = 0; int64_t lastPing_ = 0; int64_t connectStart_ = 0; // fragment reassembly std::vector fragmentBuffer_; bool fragmenting_ = false; uint8_t fragmentFlags_ = 0; // channel map for auto-move std::map channelMap_; struct PendingRequest { CommandResult result; std::string returnCode; bool completed = false; std::condition_variable cv; }; std::mutex requestSerialMutex_; std::mutex pendingMutex_; std::deque> pendingRequests_; std::atomic requestId_{0}; std::atomic transferId_{0}; }; } // namespace Echoion::Protocol