From e441156ee6c921c780ae13ad9fb89d8d01c0bc30 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 10:25:41 +0000 Subject: [PATCH] voelin-core: channel moves report why they fail; password and token on connect A move went out without asking for an answer, so a wrong password or a full channel came back as nothing. It is sent with a return code now, and a refusal comes as Event::JoinFailed: Password, Full, or a sentence for anything else. Moving to the channel we are in says nothing. The UI does not show it yet; the channel password dialog will. VoiceOptions gets channel_password and token, for joining a channel when connecting and for links with a privilege key; tsclientlib's ConnectOptions gets default_token for the latter (UPSTREAM.md patch 15). Live tests on both dev servers check the password and the key on connect, and the refused moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- crates/proto/UPSTREAM.md | 4 + crates/proto/tsclientlib/src/lib.rs | 22 ++++- crates/voelin-core/src/lib.rs | 18 ++++ crates/voelin-core/src/voice.rs | 98 ++++++++++++++++++++-- crates/voelin-core/tests/live.rs | 125 ++++++++++++++++++++++++++++ crates/voelin-ui/src/app.rs | 2 + 6 files changed, 260 insertions(+), 9 deletions(-) diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index 481464f..0554dca 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -129,3 +129,7 @@ against or offered back to upstream. Tests cover an independent signature vector, persistence validation/redaction, wire field names, clearing and reconnect snapshot replacement. The account UUID and the ordinary server identity remain separate. +15. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch"). + `ConnectOptions::default_token` sets `client_default_token` of `clientinit`, + which upstream always sent empty, so a privilege key (a bookmark's, or the + `token=` of a `ts3server://` link) can be used on connect. diff --git a/crates/proto/tsclientlib/src/lib.rs b/crates/proto/tsclientlib/src/lib.rs index 41d7fe4..4f8911e 100644 --- a/crates/proto/tsclientlib/src/lib.rs +++ b/crates/proto/tsclientlib/src/lib.rs @@ -392,6 +392,7 @@ impl Connection { channel: None, channel_password: None, password: None, + default_token: None, input_muted: false, output_muted: false, input_hardware_enabled: true, @@ -556,7 +557,7 @@ impl Connection { version_sign: Cow::Borrowed(client_version_sign.as_ref()), client_key_offset: counter, phonetic_name: "".into(), - default_token: "".into(), + default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()), hardware_id: Cow::Borrowed(options.hardware_id.as_ref()), badges: None, signed_badges: None, @@ -1730,6 +1731,7 @@ pub struct ConnectOptions { channel: Option>, channel_password: Option>, password: Option>, + default_token: Option>, input_muted: bool, output_muted: bool, input_hardware_enabled: bool, @@ -1944,6 +1946,20 @@ impl ConnectOptions { self } + /// Use a privilege key (token) when connecting. + /// Voelin patch: sent as `client_default_token` in `clientinit`. + /// + /// # Example + /// ``` + /// # use tsclientlib::Connection; + /// let opts = Connection::build("localhost").default_token("My privilege key"); + /// ``` + #[inline] + pub fn default_token>>(mut self, token: S) -> Self { + self.default_token = Some(token.into()); + self + } + /// Connect to the server in a muted state. /// /// # Example @@ -2064,6 +2080,10 @@ impl ConnectOptions { #[inline] pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) } #[inline] + pub fn get_default_token(&self) -> Option<&str> { + self.default_token.as_ref().map(AsRef::as_ref) + } + #[inline] pub fn get_input_muted(&self) -> bool { self.input_muted } #[inline] pub fn get_output_muted(&self) -> bool { self.output_muted } diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index e9424f6..f7a953b 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -153,6 +153,7 @@ pub enum Command { session: SessionId, request: GatewayRequest, }, + /// Refusals come as [`Event::JoinFailed`]. MoveToChannel { session: SessionId, channel: ChannelId, @@ -469,6 +470,17 @@ pub struct SessionState { pub server_uid: Option, } +/// Why the server did not let us into a channel ([`Event::JoinFailed`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JoinFailure { + /// The channel's password is missing or wrong. + Password, + /// The channel, or the channel with its subchannels, is full. + Full, + /// Anything else, as a sentence for the user. + Other(String), +} + /// What the engine reports. #[derive(Clone, Debug)] pub enum Event { @@ -534,6 +546,12 @@ pub enum Event { session: SessionId, message: String, }, + /// The server refused [`Command::MoveToChannel`] into `channel`. + JoinFailed { + session: SessionId, + channel: ChannelId, + reason: JoinFailure, + }, /// The streams in our channel (TeamSpeak 6), full list. StreamsChanged { session: SessionId, diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index a4687d9..3e06911 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; -use crate::{Event, SessionId}; +use crate::{Event, JoinFailure, SessionId}; #[derive(Clone, Debug)] pub struct VoiceOptions { @@ -45,6 +45,10 @@ pub struct VoiceOptions { pub server_password: Option, /// Channel path to join, e.g. `Lobby/Sub`. pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, /// Open the audio devices (capture and playback). pub audio: bool, /// Network settings for stream peer connections (TeamSpeak 6). @@ -60,6 +64,8 @@ impl VoiceOptions { client_version: None, server_password: None, channel: None, + channel_password: None, + token: None, audio: false, stream_peer: PeerConfig::default(), } @@ -253,6 +259,10 @@ enum Pending { id: u32, message: Option, }, + /// Moving ourselves; refusals are reported as [`Event::JoinFailed`]. + Move { + channel: ChannelId, + }, /// Failures are reported as [`VoiceEvent::Error`] with this label. Report(&'static str), /// Best effort: the answer does not matter. @@ -365,6 +375,12 @@ async fn run_inner( if let Some(channel) = &options.channel { builder = builder.channel(channel.clone()); } + if let Some(pw) = options.channel_password.as_ref().filter(|p| !p.is_empty()) { + builder = builder.channel_password(pw.clone()); + } + if let Some(token) = &options.token { + builder = builder.default_token(token.clone()); + } let mut identity = link.myts_identity.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. @@ -801,6 +817,13 @@ impl Voice { }; self.link.emit(Event::OfflineMessage { session, request, result }); } + Pending::Move { channel } => { + if let Err(e) = result + && let Some(reason) = join_failure(e) + { + self.link.emit(Event::JoinFailed { session, channel, reason }); + } + } Pending::Quiet | Pending::MytsIdentity(_) => {} Pending::Report(what) => { if let Err(e) = result { @@ -840,13 +863,15 @@ impl Voice { self.send(out, Pending::Report("message"))?; } VoiceCmd::Move(channel, password) => { - let state = self.con.get_state()?; - let own = &state.clients[&state.own_client]; - let mut part = own.client_move(tsclientlib::ChannelId(channel)); - if let Some(pw) = &password { - part = part.set_password(pw); - } - part.send(&mut self.con)?; + let own = self.con.get_state()?.own_client; + let cpw = encode_password(password.as_deref()); + let cmd = + c2s::OutClientMoveMessage::new(&mut std::iter::once(c2s::OutClientMovePart { + client_id: own, + channel_id: tsclientlib::ChannelId(channel), + channel_password: (!cpw.is_empty()).then_some(cpw.as_str().into()), + })); + self.send(cmd, Pending::Move { channel })?; } VoiceCmd::SetInputMuted(muted) => { self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?; @@ -1053,6 +1078,39 @@ impl Voice { } } +/// Why a move into a channel failed, for the user; `None` when there is +/// nothing to tell (we are in that channel already). +fn join_failure(error: TsError) -> Option { + let text = match error { + TsError::ChannelAlreadyIn => return None, + TsError::ChannelInvalidPassword => return Some(JoinFailure::Password), + TsError::ChannelMaxclientsReached | TsError::ChannelMaxfamilyReached => { + return Some(JoinFailure::Full); + } + TsError::ChannelInvalidId => "The channel does not exist any more.".to_owned(), + TsError::PermissionsClientInsufficient | TsError::Permissions => { + "You are not allowed to join this channel.".to_owned() + } + TsError::ClientIsFlooding => "Too many requests: try again in a moment.".to_owned(), + // The error's name in words (its Display is the name). + e => format!("The server refused to move you: {}.", error_words(e)), + }; + Some(JoinFailure::Other(text)) +} + +/// A TeamSpeak error's name in lowercase words: +/// `ChannelIsPrivateChannel` is "channel is private channel". +fn error_words(error: TsError) -> String { + let mut words = String::new(); + for c in format!("{error:?}").chars() { + if c.is_ascii_uppercase() && !words.is_empty() { + words.push(' '); + } + words.push(c.to_ascii_lowercase()); + } + words +} + /// A failed transfer, for the user. fn transfer_error(error: &tsclientlib::Error) -> String { match error { @@ -1063,6 +1121,30 @@ fn transfer_error(error: &tsclientlib::Error) -> String { } } +#[cfg(test)] +mod join_tests { + use super::*; + + #[test] + fn refused_moves_say_why() { + assert_eq!(join_failure(TsError::ChannelInvalidPassword), Some(JoinFailure::Password)); + assert_eq!(join_failure(TsError::ChannelMaxclientsReached), Some(JoinFailure::Full)); + assert_eq!(join_failure(TsError::ChannelMaxfamilyReached), Some(JoinFailure::Full)); + // Moving to the channel we are in. + assert_eq!(join_failure(TsError::ChannelAlreadyIn), None); + let other = |text: &str| Some(JoinFailure::Other(text.into())); + assert_eq!( + join_failure(TsError::PermissionsClientInsufficient), + other("You are not allowed to join this channel.") + ); + // The rest in words, not the error's name. + assert_eq!( + join_failure(TsError::ChannelIsPrivateChannel), + other("The server refused to move you: channel is private channel.") + ); + } +} + #[cfg(test)] mod image_download_tests { use super::*; diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index a47706f..498b734 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -123,6 +123,131 @@ async fn ts3_engine() { .await; } +/// A channel password and a privilege key work when connecting; a refused +/// move says why. One connection, as the servers refuse quick reconnects. +async fn channel_joins(voice_addr: &str, query: voelin_query::Connect) { + use voelin_core::JoinFailure; + use voelin_query::{Command as Query, QueryClient}; + let (admin, _) = QueryClient::connect(&query).await.unwrap(); + let tag = std::process::id() % 10_000; + let create = |name: &str| { + Query::new("channelcreate") + .arg("channel_name", format!("{name}-{tag}")) + .arg("channel_flag_semi_permanent", 1) + }; + let locked = admin.send(&create("locked").arg("channel_password", "secret")).await.unwrap()[0] + .parse::("cid") + .unwrap(); + let full = + create("full").arg("channel_maxclients", 0).arg("channel_flag_maxclients_unlimited", 0); + let full = admin.send(&full).await.unwrap()[0].parse::("cid").unwrap(); + // A key for the Normal group, which has to keep to passwords and limits. + let groups = admin.send(&Query::new("servergrouplist")).await.unwrap(); + let normal = groups + .iter() + .find(|g| g.get("name") == Some("Normal") && g.get("type") == Some("1")) + .and_then(|g| g.parse::("sgid")) + .expect("a Normal server group"); + let key = Query::new("privilegekeyadd") + .arg("tokentype", 0) + .arg("tokenid1", normal) + .arg("tokenid2", 0); + let token = admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned(); + let channels = admin.send(&Query::new("channellist").flag("-flags")).await.unwrap(); + let lobby = channels + .iter() + .find(|c| c.flag("channel_flag_default") == Some(true)) + .and_then(|c| c.parse::("cid")) + .expect("a default channel"); + + let engine = Engine::start(); + let check = { + let (engine, voice_addr, token) = (engine.clone(), voice_addr.to_owned(), token.clone()); + tokio::spawn(async move { + let mut events = engine.subscribe(); + let mut options = VoiceOptions::new(&voice_addr, format!("joins-{tag}")); + options.channel = Some(format!("locked-{tag}")); + options.channel_password = Some("secret".into()); + options.token = Some(token); + engine.send(Command::ConnectVoice { session: 1, options: Box::new(options) }); + let (mut own, mut presence) = (None, None); + wait_for(&mut events, "connected into the channel, in the key's group", |e| { + match e { + Event::State { session: 1, state } => own = state.own_client, + Event::Presence { session: 1, presence: p } => presence = Some(p.clone()), + _ => {} + } + let client = own.and_then(|id| presence.as_ref()?.clients.get(&id).cloned()); + client.is_some_and(|c| c.channel == locked && c.server_groups.contains(&normal)) + }) + .await; + let moved = async |events: &mut Receiver, channel: u64| { + wait_for( + events, + "a move", + |e| matches!(e, Event::State { session: 1, state } if state.own_channel == Some(channel)), + ) + .await; + }; + let refused = + async |events: &mut Receiver, channel: u64, reason: JoinFailure| { + let failed = wait_for(events, "a refused move", |e| { + matches!(e, Event::JoinFailed { session: 1, .. }) + }) + .await; + let Event::JoinFailed { channel: c, reason: r, .. } = failed else { + unreachable!() + }; + assert_eq!((c, r), (channel, reason)); + }; + let move_to = |channel, password: Option<&str>| Command::MoveToChannel { + session: 1, + channel, + password: password.map(Into::into), + }; + engine.send(move_to(lobby, None)); + moved(&mut events, lobby).await; + engine.send(move_to(locked, None)); + refused(&mut events, locked, JoinFailure::Password).await; + engine.send(move_to(locked, Some("wrong"))); + refused(&mut events, locked, JoinFailure::Password).await; + engine.send(move_to(locked, Some("secret"))); + moved(&mut events, locked).await; + // Moving where we are says nothing: the next refusal is the full channel's. + engine.send(move_to(locked, Some("secret"))); + engine.send(move_to(full, None)); + refused(&mut events, full, JoinFailure::Full).await; + }) + }; + let result = check.await; + engine.send(Command::CloseSession { session: 1 }); + tokio::time::sleep(Duration::from_millis(500)).await; + // Clean up everything before reporting a failure; the key is gone once used. + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + for cid in [locked, full] { + admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap(); + } + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_channel_joins() { + if !live() { + return; + } + channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_channel_joins() { + if !live() { + return; + } + channel_joins("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")).await; +} + /// A 1×1 PNG. const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 18b95db..1985241 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -1056,6 +1056,8 @@ impl App { // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. Event::Error { .. } if self.demo_ui => {} Event::Error { message, .. } => self.set_status(message), + // Not shown yet: the channel password dialog will handle it. + Event::JoinFailed { .. } => {} Event::SettingChanged { key } => self.setting_changed(&key), Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}"));