Files
VoelinClient/crates/voelin-core/src/ts_session/mod.rs
T
faumarayandClaude Sonnet 5.5 bc9ccbc85e Measure the voice path through both adapters; test the engine on a registered connector
- A unit test frames 5,000 Opus packets each way through SessionLink, the
  TeamSpeak session and the recording link and prints the cost per packet
  (about 7 microseconds to the host, 10 from it in a debug build; the test
  bounds each direction at 500 microseconds). docs/session-seam.md section 13
  records the figures, which were the one thing slice 1 had not measured.
- tests/session_backends.rs: the engine over voelin-proto's FakeConnector
  through Engine::start_with_backends (connect, server name and backend,
  channels, a move, disconnect), and the registry's error text for an address
  no connector serves.
- The error of a TeamSpeak connector given an address that is not a TeamSpeak
  one no longer prints the query, where a channel password rides.
- The note on the two library tests that need the name localhost to resolve to
  127.0.0.1 says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 00:41:04 +03:00

769 lines
26 KiB
Rust

//! A TeamSpeak connection as a `voelin_proto::link::Session`
//! (`docs/session-seam.md`, "the TeamSpeak side").
//!
//! [`LinkSession`] is a `Session` over any [`ServerLink`](crate::link::ServerLink):
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
//! inside it is what the link tests of the engine run through. [`TsConnector`]
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
//! addresses.
//!
//! This module and the files it is made of are TeamSpeak's: they keep the
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
//! [`connect_params`] and [`TsConnector`], and everything else is v1 and the
//! client's own model. In the second half of the decoupling plan they move,
//! with `TsLink`, to the TeamSpeak gateway (`voelin-gateway-ts` of
//! VoelinGateWay).
mod driver;
pub(crate) mod entities;
pub(crate) mod ids;
mod media;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use voelin_model::{Link, ServerDetails};
use voelin_proto::link::{
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
IssuerTrust, LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, MediaSink, Placement,
Sent, Session, SessionError, Upload, placement, voice_sub,
};
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use crate::link::{
Backends, BoxDuplex, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected,
LocalConnector, LocalCtx, ServerLink, StreamPort,
};
use crate::{BackendInfo, TsLink};
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
const IDENTITY_KIND: &str = "teamspeak";
/// The link parameter that carries the client version to impersonate: the
/// JSON of `tsclientlib::Version`, in unpadded URL-safe base64.
const VERSION_PARAM: &str = "client_version";
/// How long the link may take to report its first snapshot after it said it
/// is connected; the snapshot gives the `Welcome` its own user.
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
static SESSIONS: AtomicU64 = AtomicU64::new(1);
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
// ---- what the engine hands a connector ------------------------------------
/// The connect parameters of a TeamSpeak connection, from the options the
/// session was asked to connect with (`docs/session-seam.md` section 4.2).
///
/// The address is the `ts3server://` link of the bookmark (the channel and
/// its password ride in it, and so does the client version to claim, until
/// v1 has fields for them), the server password is `Hello.password` and the
/// privilege key `Hello.invite_code`. The identity goes as
/// `Credential::Foreign`; no account is used yet.
pub(crate) fn connect_params(
options: &ConnectOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> ConnectParams {
let credential = Credential::Foreign {
kind: IDENTITY_KIND,
blob: options
.identity
.as_ref()
.and_then(|identity| serde_json::to_vec(identity).ok())
.map(Bytes::from)
.unwrap_or_default(),
};
let hello = v1::Hello {
version: 1,
client: Some(v1::ClientInfo {
name: "Voelin".into(),
version: voelin_platform::crash::app_version().to_owned(),
platform: std::env::consts::OS.into(),
kind: v1::ClientKind::User as i32,
}),
nickname: options.nickname.clone(),
password: options.server_password.clone().unwrap_or_default(),
invite_code: options.token.clone().unwrap_or_default(),
..Default::default()
};
ConnectParams {
address: address_link(options),
credential,
linked: Vec::new(),
account: backends.account(),
issuer_trust: IssuerTrust::Unknown,
hello,
host_pin: None,
trust: backends.trust(),
media,
push_capacity: 1024,
timeout: Duration::from_secs(35),
}
}
/// The `ts3server://` link of the options' address, with the channel to join
/// and the client version to claim.
fn address_link(options: &ConnectOptions) -> String {
let mut link = match Link::parse(&options.address) {
Some(Link::Server(link)) => link,
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
_ if !options.address.contains("://") => voelin_model::ServerLink::new(&options.address),
// Some other scheme: as given, for the connector of that scheme.
_ => return options.address.clone(),
};
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
link.channel_password =
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
let mut url = link.to_url();
if let Some(version) = options.client_version.as_ref().and_then(|v| serde_json::to_vec(v).ok())
{
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(VERSION_PARAM);
url.push('=');
url.push_str(&URL_SAFE_NO_PAD.encode(version));
}
url
}
/// The options a TeamSpeak link is connected with: the reverse of
/// [`connect_params`].
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
_ => {
// Without the query: a channel password rides in it.
let shown = params.address.split('?').next().unwrap_or_default();
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
}
};
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
Some(serde_json::from_slice(blob).map_err(|e| {
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
})?)
}
_ => {
return Err(SessionError::Protocol(
"a TeamSpeak server needs a TeamSpeak identity".into(),
));
}
};
let client_version = params
.address
.split_once('?')
.and_then(|(_, query)| {
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
})
.and_then(|text| URL_SAFE_NO_PAD.decode(text).ok())
.and_then(|json| serde_json::from_slice(&json).ok());
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
Ok(ConnectOptions {
address: link.address(),
nickname: nonempty(&params.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
identity,
client_version,
server_password: nonempty(&params.hello.password).or(link.password.clone()),
channel: link.channel.clone(),
channel_password: link.channel_password.clone(),
token: nonempty(&params.hello.invite_code).or(link.token.clone()),
audio: ctx.audio,
stream_peer: ctx.stream_peer.clone(),
})
}
// ---- backend and features ---------------------------------------------------
/// The server software as v1 names it (table 4.7): `teamspeak` with the
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
let (product, flavor) = match backend.product.as_str() {
"TeamSpeak 3" => ("teamspeak", "ts3"),
"TeamSpeak 6" => ("teamspeak", "ts6"),
// A TeamSpeak server the engine does not recognise: the version it
// sent, no flavor.
"" => ("teamspeak", ""),
other => (other, ""),
};
v1::BackendInfo {
product: product.into(),
version: backend.version.clone(),
flavor: flavor.into(),
}
}
/// The features a TeamSpeak connection offers, from what its link can do
/// (`docs/session-seam.md` section 4.7).
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
let mut features =
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
if capabilities.file_transfer {
features.extend(["files", "files.upload"]);
}
if capabilities.offline_messages {
features.push("mailbox");
}
if capabilities.streams {
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
}
features
}
// ---- the session ------------------------------------------------------------
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
pub(crate) struct LinkSession {
welcome: v1::Welcome,
features: Features,
cmds: mpsc::UnboundedSender<Cmd>,
closed: watch::Receiver<Option<CloseReason>>,
own_slot: u32,
}
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
}
impl Session for LinkSession {
fn welcome(&self) -> &v1::Welcome {
&self.welcome
}
fn features(&self) -> Features {
self.features.clone()
}
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
let closed = self.closed.clone();
match placement(&op) {
Placement::Invalid => {
return Box::pin(async {
Err(SessionError::Protocol("a Hello is part of connecting".into()))
});
}
Placement::OwnStream
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
{
return Box::pin(async {
Err(SessionError::Protocol("files go through read_file and write_file".into()))
});
}
_ => {}
}
// Queued now, in the order of the calls, not when the future is polled.
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
if placement(&op) == Placement::Invalid {
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
}
self.cmds
.send(Cmd::Notify(op))
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
}
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
let flow = packet.flow;
if self.closed.borrow().is_some() {
return Err(MediaError::Closed);
}
if packet.rtp.len() > MAX_RTP {
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
}
// Only our voice to the channel: TeamSpeak whispers and priority voice,
// like video, are not offered here.
if class != MediaClass::Voice
|| flow.slot() != self.own_slot
|| flow.sub() != voice_sub::CHANNEL
{
return Err(MediaError::NotOwned(flow));
}
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
Ok(Sent::Queued)
}
fn stats(&self) -> LinkStats {
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
}
fn close(&self, code: v1::CloseCode, reason: &str) {
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
}
fn closed(&self) -> BoxFuture<CloseReason> {
let mut closed = self.closed.clone();
Box::pin(async move {
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
reason.unwrap_or_else(|| closed_reason(&closed))
})
}
}
/// The write half of an upload: ending it tells the other half of the
/// upload that the file is all there.
struct UploadBody {
inner: tokio::io::WriteHalf<BoxDuplex>,
ended: Option<oneshot::Sender<()>>,
}
impl AsyncWrite for UploadBody {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
if matches!(done, Poll::Ready(Ok(())))
&& let Some(ended) = self.ended.take()
{
let _ = ended.send(());
}
done
}
}
/// An upload over the transfer connection `stream`: the body writes to it,
/// and `done` resolves once the body is shut down and the server has closed
/// the connection (or 30 s passed), with the file as `stored`.
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
let (mut read, write) = tokio::io::split(stream);
let (ended, shut) = oneshot::channel();
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
if shut.await.is_err() {
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
}
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
Ok(v1::Entities {
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
..Default::default()
})
});
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
}
// ---- the connector ----------------------------------------------------------
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
#[derive(Clone)]
pub(crate) struct LinkConnector {
link: Arc<dyn ServerLink>,
schemes: &'static [&'static str],
/// Serves every scheme (the engine's tests give a link of their own).
any: bool,
}
impl LinkConnector {
/// A connector for `schemes`.
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
Self { link, schemes, any: false }
}
/// A connector for addresses of every scheme.
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
}
impl Connector for LinkConnector {
fn schemes(&self) -> &'static [&'static str] {
self.schemes
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
Box::pin(async move { Ok(connect.await?.connected) })
}
}
impl LocalConnector for LinkConnector {
fn accepts(&self, scheme: &str) -> bool {
self.any || self.schemes.contains(&scheme)
}
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
Box::pin(connect_link(self.link.clone(), params, ctx))
}
}
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
/// with `tsclientlib`: [`LinkSession`]s over [`TsLink`].
#[derive(Clone)]
pub(crate) struct TsConnector(LinkConnector);
impl TsConnector {
pub(crate) fn new() -> Self {
Self(LinkConnector::new(Arc::new(TsLink), &["ts3server", "teamspeak"]))
}
}
impl Connector for TsConnector {
fn schemes(&self) -> &'static [&'static str] {
self.0.schemes()
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
self.0.connect(params)
}
}
impl LocalConnector for TsConnector {
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
self.0.connect_local(params, ctx)
}
}
/// What the link told when it connected.
struct Joined {
name: String,
backend: BackendInfo,
capabilities: voelin_model::Capabilities,
own_client: u16,
server_uid: String,
own_uid: Option<String>,
}
fn ended_error(reason: Option<String>) -> SessionError {
SessionError::Closed(match reason {
Some(reason) => CloseReason::Network(reason),
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
})
}
/// Wait for the link to say it is connected (or that it failed).
async fn wait_connected(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
) -> Result<Joined, SessionError> {
loop {
match events.recv().await {
Some(LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
}) => {
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
}
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
Some(_) => {}
None => return Err(ended_error(Some("the connection ended".into()))),
}
}
}
/// Open a [`LinkSession`] over `link` to the address in `params`.
async fn connect_link(
link: Arc<dyn ServerLink>,
params: ConnectParams,
ctx: LocalCtx,
) -> Result<LocalConnected, SessionError> {
let options = inner_options(&params, &ctx)?;
let nickname = options.nickname.clone();
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
let (events_tx, mut events) = mpsc::unbounded_channel();
// The link answers requests on a bus of its own: this session reads the
// answers, and passes on the rest to the engine's.
let (bus_tx, bus) = broadcast::channel(4096);
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
link.spawn(options, inner_ctx, inner_rx, events_tx);
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
Ok(joined) => joined?,
Err(_) => {
let _ = inner_tx.send(LinkCmd::Disconnect);
return Err(SessionError::Timeout);
}
};
// The link reports its first snapshot right after it says it is connected;
// the session needs it to know the own user.
let mut early: Vec<LinkEvent> = Vec::new();
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
while let Some(event) = events.recv().await {
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
early.push(event);
if stop {
break;
}
}
})
.await;
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
return Err(ended_error(reason.clone()));
}
let own_database_id = early.iter().find_map(|event| match event {
LinkEvent::Presence(presence) => {
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
}
_ => None,
});
let ts6 = joined.backend.product == "TeamSpeak 6";
let own_user =
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
let features = features_of(&joined.capabilities);
let welcome = v1::Welcome {
user_id: own_user,
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
host: Some(v1::HostInfo {
host_key: Bytes::new(),
name: joined.name.clone(),
product: joined.backend.product.clone(),
version: joined.backend.version.clone(),
backend: Some(backend_to_v1(&joined.backend)),
icon: None,
}),
features: features.iter().map(|f| (*f).to_owned()).collect(),
limits: Some(v1::Limits {
max_message_chars: 1024,
max_page: 100,
max_subscriptions: 4,
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
max_live_subscriptions: 8,
..Default::default()
}),
time_ms: now_ms(),
..Default::default()
};
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
let (closed_tx, closed_rx) = watch::channel(None);
let (port, streams) = if joined.capabilities.streams {
let (events_tx, events_rx) = mpsc::unbounded_channel();
let cmds = cmds_tx.clone();
let send = move |cmd| {
let _ = cmds.send(Cmd::Stream(cmd));
};
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
} else {
(None, None)
};
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
let driver = Driver::new(Parts {
cfg: Config {
ts6,
own_client: joined.own_client,
nickname,
own_uid: joined.own_uid.clone(),
files: joined.capabilities.file_transfer,
mail: joined.capabilities.offline_messages,
},
inner: inner_tx,
events,
early,
bus,
engine_bus: ctx.link.events.clone(),
pushes: pushes_tx,
media: params.media.clone(),
port,
closed: closed_tx,
server: entities::server(&details, &joined.name, 0),
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
});
let session = LinkSession {
welcome,
features: Features::new(features),
cmds: cmds_tx,
closed: closed_rx,
own_slot: entities::slot(joined.own_client),
};
tokio::spawn(driver.run(cmds_rx));
Ok(LocalConnected {
connected: Connected {
session: Arc::new(session),
pushes: pushes_rx,
// A TeamSpeak server has no host key to pin.
host_uid: [0; 32],
},
streams,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn params(options: &ConnectOptions) -> ConnectParams {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty())
}
fn back(options: &ConnectOptions) -> ConnectOptions {
inner_options(&params(options), &LocalCtx::standalone()).unwrap()
}
#[test]
fn the_options_of_a_bookmark_come_back_as_they_went() {
let mut options = ConnectOptions::new("ts.example.com:9988", "nick");
let same = back(&options);
assert_eq!(
(same.address.as_str(), same.nickname.as_str()),
("ts.example.com:9988", "nick")
);
assert!(same.identity.is_none() && same.client_version.is_none());
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
// Everything a connection can be told: the server password and the
// privilege key go in the hello, the channel and its password in the
// link, the identity as a credential.
options.server_password = Some("s3cret pass&word".into());
options.channel = Some("Games/Raid Night".into());
options.channel_password = Some("p w+%".into());
options.token = Some("tokenvalue".into());
options.identity = Some(tsclientlib::Identity::create());
options.client_version = Some(crate::versions::native_version().unwrap());
options.audio = false;
let sent = params(&options);
assert_eq!(sent.hello.password, "s3cret pass&word");
assert_eq!(sent.hello.invite_code, "tokenvalue");
assert_eq!(sent.hello.nickname, "nick");
assert!(
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
"{}",
sent.address
);
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
let got = back(&options);
assert_eq!(got.address, "ts.example.com:9988");
assert_eq!(got.server_password, options.server_password);
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
assert_eq!(got.channel_password, options.channel_password);
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
assert_eq!(got.client_version, options.client_version);
// The identity is the same key and counters.
let (a, b) = (options.identity.as_ref().unwrap(), got.identity.as_ref().unwrap());
assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap());
}
#[test]
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
let mut options = ConnectOptions::new("[::1]:9987", "nick");
options.channel = Some("/12".into());
let got = back(&options);
assert_eq!(got.address, "[::1]:9987");
assert_eq!(got.channel.as_deref(), Some("/12"));
// A bookmark that is a link keeps its own parameters.
let options =
ConnectOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
let got = back(&options);
assert_eq!(
(got.address.as_str(), got.channel.as_deref()),
("ts.example.com:1", Some("Lobby"))
);
// Another scheme is left as it is for the connector of that scheme.
let options = ConnectOptions::new("voelin://host/i/code", "nick");
assert_eq!(params(&options).address, "voelin://host/i/code");
}
#[test]
fn what_is_no_teamspeak_identity_is_refused() {
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
assert!(matches!(error, SessionError::Protocol(_)));
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
let mut sent = params(&ConnectOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
// A host that wants trust is refused: TeamSpeak has no host key.
let backends = Backends::empty();
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
address: "x".into(),
uid: [0; 32],
previous: None,
});
assert!(!futures::executor::block_on(confirm));
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&ConnectOptions::new("ts.example.com", "nick"));
assert!(sent.account.is_none());
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
let client = sent.hello.client.unwrap();
assert_eq!(client.name, "Voelin");
assert_eq!(sent.hello.version, 1);
}
}