diff --git a/connector/src/main.rs b/connector/src/main.rs index b2954b5..5925612 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::str; use std::time::Duration; use anyhow::Result; @@ -29,6 +30,7 @@ use tsclientlib::{ LicenseType, MaxClients, MessageHandle, MessageTarget, Permission, Reason, ServerGroupId, ServerType, StreamItem, TextMessageTargetMode, TsError, }; +use tsproto_packets::commands::{CommandItem, CommandParser}; use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType}; /// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects. @@ -344,6 +346,16 @@ enum Event { /// anywhere), for populating an "add permission" picker. #[serde(rename = "permissionCatalog")] PermissionCatalog { entries: Vec }, + /// A TS6 Stream/Call command the server sent us, forwarded verbatim. + /// + /// `tsclientlib` has no declarations for these, so they arrive as + /// `StreamItem::UnknownCommand` and are only unescaped here - the payload + /// of `notifystreamsignaling` is an opaque JSON blob (SDP offer/answer, + /// ICE candidates) that belongs to the browser's `RTCPeerConnection`, not + /// to the connector. `name` is the raw command name, e.g. + /// `notifystreamsignaling`. + #[serde(rename = "streamEvent")] + StreamEvent { name: String, args: BTreeMap }, } #[derive(Serialize)] @@ -641,6 +653,57 @@ fn snapshot(con: &data::Connection) -> Event { } } +/// Splits a raw TS command line into its unescaped key/value pairs. +/// +/// Only the first part of a `|`-separated multi-part command is read; none of +/// the stream commands use multiple parts. A flag without `=` becomes an empty +/// string, which is how TeamSpeak treats it too. +fn parse_ts_args(content: &str) -> BTreeMap { + let (_, parser) = CommandParser::new(content.as_bytes()); + let mut args = BTreeMap::new(); + for item in parser { + match item { + CommandItem::Argument(arg) => { + let (Ok(name), Ok(value)) = (str::from_utf8(arg.name()), arg.value().get_str()) + else { + continue; + }; + args.insert(name.to_string(), value.into_owned()); + } + // Stop at the first part boundary. + CommandItem::NextCommand => break, + } + } + args +} + +/// Sends `joinstreamrequest` for a `" [msg]"` argument line. +/// +/// Parameter names and order are as recovered from TS6's `TeamSpeak.dll`; `msg` +/// is written even when empty so the shape matches the native client. +fn send_join_stream_request(con: &mut tsclientlib::Connection, rest: &str, is_remove: bool) { + let mut parts = rest.splitn(3, ' '); + let (Some(id), Some(Ok(clid))) = (parts.next(), parts.next().map(|c| c.parse::())) else { + emit(&Event::Error { message: "Usage: streamjoin [msg]".into() }); + return; + }; + if id.is_empty() { + emit(&Event::Error { message: "Usage: streamjoin [msg]".into() }); + return; + } + let msg = parts.next().unwrap_or(""); + + let mut packet = + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "joinstreamrequest"); + packet.write_arg("id", &id); + packet.write_arg("clid", &clid); + packet.write_arg("msg", &msg); + packet.write_arg("is_remove", &u8::from(is_remove)); + if let Err(e) = packet.send(con) { + emit(&Event::Error { message: format!("joinstreamrequest failed: {e}") }); + } +} + fn send_server_get_variables(con: &mut tsclientlib::Connection) { let packet = OutCommand::new( Direction::C2S, @@ -1401,6 +1464,42 @@ async fn run(args: Args) -> Result<()> { } Err(e) => emit(&Event::Error { message: e.to_string() }), } + } else if let Some(rest) = l.strip_prefix("streamjoin ") { + // "streamjoin [msg]" - ask the client + // publishing a TS6 stream to let us in. Its reply is a + // notifyrespondjoinstreamrequest carrying the SDP offer. + send_join_stream_request(&mut con, rest, false); + } else if let Some(rest) = l.strip_prefix("streamleave ") { + // Same command with is_remove=1, which is how TS6 leaves + // a stream it has joined. + send_join_stream_request(&mut con, rest, true); + } else if let Some(rest) = l.strip_prefix("streamsignal ") { + // "streamsignal " - the json is + // the rest of the line, opaque to us. Escaping is done by + // write_arg. + let mut parts = rest.splitn(3, ' '); + match (parts.next(), parts.next().and_then(|c| c.parse::().ok()), parts.next()) { + (Some(id), Some(clid), Some(json)) if !id.is_empty() && !json.is_empty() => { + let mut packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "streamsignaling", + ); + packet.write_arg("id", &id); + packet.write_arg("clid", &clid); + packet.write_arg("json", &json); + // Fire and forget: ICE candidates arrive in bursts + // and a return_code round trip per candidate would + // only add latency to the handshake. + if let Err(e) = packet.send(&mut con) { + emit(&Event::Error { message: format!("streamsignaling failed: {e}") }); + } + } + _ => emit(&Event::Error { + message: "Usage: streamsignal ".into(), + }), + } } else if l == "banlist" { // No typed builder exists for banlist, so this is built as a raw // command; the reply arrives via StreamItem::MessageEvent (see below). @@ -2370,6 +2469,16 @@ async fn run(args: Args) -> Result<()> { } } } + Some(Ok(StreamItem::UnknownCommand { name, content })) => { + // TS6 Stream/Call signaling. Everything else undeclared is + // dropped on purpose - forwarding every unknown command + // would turn this into a firehose, and nothing downstream + // wants it. + if name.starts_with("notifystream") || name.starts_with("notifyrespondjoinstream") + { + emit(&Event::StreamEvent { args: parse_ts_args(&content), name }); + } + } Some(Ok(StreamItem::MessageEvent(msg))) => { // Defense in depth: TeaSpeak/GTS may surface notifyclientpoke as an // unhandled MessageEvent if bookkeeping did not mark it handled. diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 670afa5..59f566a 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -415,6 +415,27 @@ wss.on("connection", (socket: WebSocket) => { await connection?.sendAudio(msg.pcm); break; } + case "joinStream": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId)) { + await connection?.joinStream(String(msg.streamId ?? ""), clientId, msg.message ?? ""); + } + break; + } + case "leaveStream": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId)) { + await connection?.leaveStream(String(msg.streamId ?? ""), clientId); + } + break; + } + case "streamSignal": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId) && msg.payload !== undefined) { + await connection?.sendStreamSignal(String(msg.streamId ?? ""), clientId, msg.payload); + } + break; + } case "setAway": { await connection?.setAway(msg.away, msg.message ?? ""); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index 9796450..509da55 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -774,6 +774,30 @@ export class Ts3Connection { this.child?.stdin.write(`audio ${pcmBase64}\n`); } + /** Ask the client publishing a TS6 stream to let us watch. The answer comes + * back as a `streamEvent` of type `notifyrespondjoinstreamrequest`, which + * carries the SDP offer. */ + async joinStream(streamId: string, clientId: number, message = ""): Promise { + const id = streamId.replace(/[\s]+/g, ""); + const sanitized = message.replace(/[\r\n]+/g, " ").trim(); + if (id) this.child?.stdin.write(`streamjoin ${id} ${clientId} ${sanitized}\n`); + } + + async leaveStream(streamId: string, clientId: number): Promise { + const id = streamId.replace(/[\s]+/g, ""); + if (id) this.child?.stdin.write(`streamleave ${id} ${clientId}\n`); + } + + /** Relays one signaling payload (SDP answer, ICE candidate) to a stream peer. + * `payload` is passed straight through - the connector only escapes it for + * the TS wire, nobody in this path interprets it. Serializing here rather + * than accepting a string keeps literal newlines out of the line-based + * stdin protocol. */ + async sendStreamSignal(streamId: string, clientId: number, payload: unknown): Promise { + const id = streamId.replace(/[\s]+/g, ""); + if (id) this.child?.stdin.write(`streamsignal ${id} ${clientId} ${JSON.stringify(payload)}\n`); + } + async setAway(away: boolean, message: string): Promise { if (away) { const sanitized = message.replace(/[\r\n]+/g, " ").trim();