Make the engine's link vocabulary private and the options neutral

VoiceOptions is a struct of its own, no longer an alias of the TeamSpeak
link's options: identity is an IdentityBlob and client_version a spec for
ts::versions::resolve, which rides the address as the link parameter
client_version and which the TeamSpeak connector resolves (a spec it refuses
fails the connect in words). SessionLink builds the connect parameters
(link/connect.rs: the bookmark's link, the hello, the credential of the
identity's kind, now also a Voelin key's signer) and session.rs holds it
directly: the ServerLink trait between them was redundant. The trait lives
on in the TeamSpeak module (ts/ts_link.rs, with the TeamSpeak-typed
ConnectOptions) for TsLink and the in-memory link of the tests.

ServerLink, TsLink, LinkCtx, LinkCmd, LinkEvent and Remote are crate-private,
Engine::start_with_link is gone, and the three tests that needed the inner
link (tests/link_fake.rs) are unit tests of link/ now. The rg over the crate
for tsclientlib, tsproto and voelin_query, outside ts/ and the three files
that use them privately (gateway.rs, query.rs, stream.rs), is empty. The UI
and voelinctl get compile fixes: the identity blob and the spec string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 06:59:44 +03:00
1 parent be84874a09
commit 1edc52ce74
17 files changed
+549 -370

No files matched your search

+7 -25
View File
@@ -3,9 +3,10 @@
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
//! Each server the user works with is a session with up to three sources:
//!
//! - **voice**: a normal client connection (visible, can talk), made by a
//! [`link::ServerLink`] (the engine's `SessionLink` over a `voelin_proto::link::Session`,
//! [`TsLink`] inside it for TeamSpeak servers; see [`link`])
//! - **voice**: a normal client connection (visible, can talk): a
//! `voelin_proto::link::Session` that the connector of the server's address
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
//! [`link`])
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
//!
@@ -88,17 +89,13 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use link::Backends;
pub use link::ConnectOptions;
pub use link::ConnectOptions as VoiceOptions;
pub use link::ServerLink;
pub use link::{Backends, VoiceOptions};
pub use offline::{OfflineMessage, OfflineMessageInfo};
pub use query::{QueryLogin, QueryTransport};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
pub use ts::TsLink;
pub use voelin_identity::IdentityBlob;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
@@ -794,27 +791,12 @@ impl Engine {
Self::start_with_backends(settings, history, Backends::default())
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with `link` (every session's voice
/// source is one of its connections, see [`link`]). The engine reaches
/// `link` as a `voelin_proto::link::Session` of its own, for every
/// address, like it does a connector's.
pub fn start_with_link(
settings: Settings,
history: History,
link: Arc<dyn ServerLink>,
) -> Self {
let mut backends = Backends::empty();
backends.register_local(Arc::new(ts::ts_session::LinkConnector::any(link)));
Self::start_with_backends(settings, history, backends)
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with the connectors in `backends`:
/// the one for the scheme of a session's address makes its
/// `voelin_proto::link::Session`.
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
let link: Arc<dyn ServerLink> = Arc::new(link::SessionLink::new(backends));
let link = Arc::new(link::SessionLink::new(backends));
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
@@ -910,7 +892,7 @@ async fn run(
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
engine: Shared,
link: Arc<dyn ServerLink>,
link: Arc<link::SessionLink>,
) {
let Shared { settings: shared, history, cache, contacts } = engine.clone();
// Before any command: a contact set meanwhile would be lost.
+233
View File
@@ -0,0 +1,233 @@
//! What a session hands the connector of an address: the `ConnectParams` of
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
//!
//! The options are the engine's own, and a connector reads them back: the
//! address is the link of the bookmark (a `ts3server://` link for a
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
//! the server password and the privilege key are in the hello, the identity
//! is the credential. What v1 has no field for yet (the channel to join and
//! its password, the client version a TeamSpeak server is shown) rides in
//! the address, as parameters of the link.
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
use voelin_model::Link;
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
use voelin_proto::v1;
use super::{Backends, VoiceOptions, without_query};
/// The link parameter that carries the client version to impersonate: the
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
/// The connector for TeamSpeak resolves it; other connectors never read it.
pub(crate) const VERSION_PARAM: &str = "client_version";
/// The connect parameters of a connection, from the options the session was
/// asked to connect with.
///
/// The address is the 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 the credential of its kind; no
/// account is used yet.
///
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
/// an identity that is of no kind a connector can use.
pub(crate) fn connect_params(
options: &VoiceOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
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()
};
Ok(ConnectParams {
address: address_link(options)?,
credential: credential(options.identity.as_ref())?,
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 credential of an identity (`docs/session-seam.md` section 7). A
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
/// an empty one, for which the TeamSpeak connector makes an identity up (the
/// protocol's convention for "generate one", follow-up P11); a Voelin key
/// signs.
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
let Some(blob) = identity else {
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
};
if blob.is_teamspeak() {
let json = Bytes::copy_from_slice(blob.json.as_bytes());
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
} else if blob.is_voelin() {
let key = blob.voelin_key().map_err(|e| {
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
})?;
Ok(Credential::Voelin(Arc::new(key)))
} else {
Err(SessionError::Protocol(format!(
"an identity of kind {:?} cannot be used to connect",
blob.kind
)))
}
}
/// The `ts3server://` link of the options' address, with the channel to join
/// and the client version to claim.
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
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("://") => bookmark(&options.address)?,
// Some other scheme: as given, for the connector of that scheme.
_ => return Ok(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(spec) = &options.client_version {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(VERSION_PARAM);
url.push('=');
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
}
Ok(url)
}
/// The link to a bookmark's `host[:port]`.
///
/// A link cannot say everything an address can: it drops a port that is no
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
/// `%` (so that a `?` in the host would hide the channel behind the next
/// one). The TeamSpeak library refuses such an address when it resolves it;
/// so does this, in words, instead of connecting to something else.
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
let address = address.trim();
// Without the query: a link keeps secrets in it.
let shown = without_query(address);
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
if address.is_empty()
|| address
.chars()
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
{
return Err(not_an_address());
}
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
// colon (more colons are an IPv6 address without a port).
let port = if let Some(rest) = address.strip_prefix('[') {
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
} else {
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
};
if let Some(port) = port
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
{
return Err(SessionError::Protocol(format!(
"the port in {shown} is not a number from 1 to 65535"
)));
}
Ok(voelin_model::ServerLink::new(address))
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_identity::IdentityKey;
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty())
}
/// The identity of the options is the credential of its kind: a TeamSpeak
/// identity as the JSON the key store keeps, none as the empty blob a
/// connector makes an identity up for, a Voelin key as its signer.
#[test]
fn an_identity_is_the_credential_of_its_kind() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
let none = params(&options).unwrap();
assert!(matches!(
&none.credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
let sent = params(&options).unwrap();
assert!(matches!(
&sent.credential,
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
));
let key = IdentityKey::generate().unwrap();
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
panic!("a Voelin credential")
};
assert_eq!(signer.public_key(), key.public_key());
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
// A Voelin blob whose key cannot be read, and a kind that connects to
// nothing: refused in words, without the JSON.
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert!(
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
);
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
}
/// The client version spec rides the link as it was typed, whatever it
/// holds, and only for an address that is a TeamSpeak bookmark or link.
#[test]
fn the_client_version_spec_rides_the_link_unchanged() {
let spec = |address: &str, spec: &str| {
let mut options = VoiceOptions::new(address, "nick");
options.client_version = Some(spec.into());
params(&options).unwrap().address
};
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
let (_, query) = address.split_once('?').unwrap();
let text = query
.split('&')
.find_map(|pair| pair.strip_prefix("client_version="))
.expect("the parameter");
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
// Another scheme is left as it is: its connector has no use for a TeamSpeak
// client's version.
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
// No spec, no parameter.
let options = VoiceOptions::new("ts.example.com", "nick");
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
}
}
@@ -11,19 +11,25 @@
//! - a link that keeps talking after the engine replaced its connection,
//! which a closed `FakeSession` cannot do on purpose.
//!
//! (They were integration tests while the inner link was public; it is the
//! TeamSpeak module's now, and so are these.)
//!
//! Presence, chat, the dedup of a message that comes twice, history, transfers
//! and the rest of what the engine does with a session are tested on the
//! protocol repository's fake host in `session_fake.rs`. Nothing here needs a
//! TeamSpeak server or a TeamSpeak type.
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
//! needs a TeamSpeak server or a TeamSpeak type.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
use voelin_core::settings::Settings;
use voelin_core::stream::{StreamCmd, StreamSetup};
use voelin_core::{
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
use crate::settings::Settings;
use crate::stream::{StreamCmd, StreamSetup};
use crate::ts::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
use crate::{
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
};
use voelin_model::{
@@ -94,8 +100,10 @@ struct Harness {
impl Harness {
fn start() -> Self {
let (link, conns) = FakeLink::new();
let mut backends = Backends::empty();
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
let engine =
Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link));
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
Self { engine, events, conns }
}
+1 -1
View File
@@ -127,7 +127,7 @@ impl HostRig {
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
+53 -134
View File
@@ -1,108 +1,25 @@
//! The seam between a session and the server it talks to as a client.
//! The engine's seam to the server its voice source talks to.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. Everything the
//! session needs from it goes through [`ServerLink`]: the session hands the
//! link the connection's options and a [`LinkCtx`], and talks to it with two
//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the
//! backend shows: the session merges, deduplicates, stores and routes what a
//! link reports, whichever server software is behind it.
//! carries chat, files, pokes, offline messages and streams. The engine holds
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
//! protocol repository, and knows nothing else of the server software behind
//! it: which backend makes the `Session` is the scheme of the address, and
//! [`Backends`] is the registry of connectors by scheme
//! ([`Backends::default`] has the TeamSpeak one,
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
//! another). [`VoiceOptions`] says what to connect to and as whom.
//!
//! # Contract for a link
//!
//! - [`ServerLink::spawn`] returns at once; the connection runs on its own
//! task and reports through `events`. Connecting is not an event: the
//! session shows `Connecting` from the moment it spawned the link, until
//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed).
//! - The first thing a connected link reports is [`LinkEvent::Connected`]
//! (name, backend, what it can do, our client id, the server's unique id),
//! then [`LinkEvent::Presence`] whenever anything in the server's tree or
//! client list changed (a full snapshot each time) and
//! [`LinkEvent::OwnChannel`] when we moved.
//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for,
//! reports that the connection ended, whichever way it did; a link sends it
//! once, and nothing from the connection itself follows it. A link that
//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves.
//! It is not promised to be the last event of the link: the stream task of
//! a connection with streams is a task of its own, which winds down after
//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and
//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its
//! streams, may follow `Disconnected` (`TsLink` ends the stream task as the
//! connection's loop ends, which usually, not always, puts them before it).
//! The session does not depend on the order: it ends our own stream and
//! the audio of watched streams itself when it hears `Disconnected`, and
//! ignores what a link says after that, like the events of a replaced one.
//! - Streams (screen sharing) are the link's business from the capabilities
//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the
//! stream task, takes [`LinkCmd::Stream`] and reports through the event
//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the
//! session first (file lists, transfers, offline messages, stream state).
//! What the session must place itself comes as events: our own stream's
//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio
//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread,
//! and [`LinkEvent::StreamAudioEnded`] when a stream's audio is over).
//! When the session replaces a connection it gives the old link
//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear
//! of their end before the link stops reading commands).
//! - What the session must see first (chat, pokes, who is talking, audio)
//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file
//! list, a request's `Done`) go straight to the event bus with
//! [`LinkCtx::emit`].
//! - Events of a link the session replaced are ignored (each link has a
//! generation), so a link need not stop emitting at once.
//!
//! # Implementations
//!
//! The engine's own implementation is `SessionLink`: it connects through
//! [`Backends`], the registry of connectors by address scheme, and talks to
//! the `voelin_proto::link::Session` it gets (`session_link.rs`, with
//! `project.rs` and `media.rs`). Nothing of a backend shows above it:
//! `session.rs` keeps speaking [`LinkCmd`] and [`LinkEvent`], and SessionLink
//! turns them into `Session` calls and the session's pushes and media into
//! events (`docs/session-seam.md` describes the mapping row by row).
//!
//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the
//! TeamSpeak 3 and 6 connection of `tsclientlib`. It is a `ServerLink` of this
//! older vocabulary, and the engine reaches it as a `Session`: the
//! `ts_session` module wraps any `ServerLink` in a `Session` (`LinkSession`,
//! made by `TsConnector` for `ts3server://` and `teamspeak://` addresses).
//! [`Engine::start_with_link`](crate::Engine::start_with_link) takes another
//! link the same way (the tests drive the session with an in-memory one,
//! `tests/link_fake.rs`), and
//! [`Engine::start_with_backends`](crate::Engine::start_with_backends) takes
//! connectors of `Session`s. The decoupling plan moves the TeamSpeak side out
//! of this crate into the TeamSpeak gateway (VoelinGateWay,
//! `voelin-gateway-ts`), and the Voelin protocol's QUIC transport becomes the
//! other implementation, both behind the backend-neutral
//! `voelin_proto::link::Session` of VoelinProtocol.
//!
//! # What is still TeamSpeak's
//!
//! The vocabulary of [`ServerLink`], and of the engine above it, is not
//! backend-neutral yet. What still has TeamSpeak types or TeamSpeak's shape,
//! and changes when the TeamSpeak side leaves:
//!
//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and
//! [`ConnectOptions::client_version`] (`tsclientlib`). The account proof is
//! no part of the link's context: [`TsConnector`](crate::ts::TsConnector)
//! keeps it.
//! - Client ids are TeamSpeak's `u16`: `own_client` of
//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of
//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a
//! [`ChatMessage`], and the viewer and streamer ids of the stream API.
//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client
//! ids, `u64` channel and group ids, server and channel groups, talk
//! power, icons, badges and the myTeamSpeak avatar.
//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream
//! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame`
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
//! API (re-exported from [`crate::stream`]). TeamSpeak 6 streams are peer
//! to peer, so their commands and events pass the `Session` through a local
//! port for now.
//! Inside the crate `session.rs` merges and routes, and an adapter below it
//! turns what it asks into `Session` calls and what the `Session` pushes into
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
//! `docs/session-seam.md` describes the mapping row by row.
mod backends;
mod connect;
#[cfg(test)]
mod fake_link_tests;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
@@ -115,6 +32,7 @@ pub use backends::Backends;
pub(crate) use backends::{
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
};
pub(crate) use connect::{VERSION_PARAM, connect_params};
pub(crate) use session_link::SessionLink;
use std::path::PathBuf;
@@ -122,8 +40,9 @@ use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::sync::{broadcast, oneshot};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_identity::IdentityBlob;
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
@@ -132,33 +51,31 @@ use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// Starts the voice connection of a session.
/// What a voice connection needs to know: the server, who to be, where to
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a connection needs to know: the server, who to be, where to join.
/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.)
/// Nothing in it belongs to one kind of server: what a connector needs of it
/// that is its own (a TeamSpeak identity, the client version to claim) is in
/// the `identity` blob and the `client_version` spec, which the connector of
/// the address reads.
#[derive(Clone, Debug)]
pub struct ConnectOptions {
pub struct VoiceOptions {
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
pub nickname: String,
/// The identity to connect with (TeamSpeak's, for now).
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
/// connection generates an identity, which a server then knows as a new
/// client).
pub identity: Option<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
@@ -172,7 +89,9 @@ pub struct ConnectOptions {
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
impl VoiceOptions {
/// Options for `address` and `nickname`; everything else is left to the
/// connector.
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
@@ -193,7 +112,7 @@ impl ConnectOptions {
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub struct LinkCtx {
pub(crate) struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
@@ -203,13 +122,13 @@ pub struct LinkCtx {
impl LinkCtx {
/// The session this connection belongs to.
pub fn session(&self) -> SessionId {
pub(crate) fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub fn emit(&self, event: Event) {
pub(crate) fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
@@ -220,25 +139,25 @@ impl LinkCtx {
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub struct Remote {
pub(crate) struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub trait Duplex: AsyncRead + AsyncWrite + Send {}
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub type BoxDuplex = Pin<Box<dyn Duplex>>;
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub enum LinkCmd {
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
@@ -340,7 +259,7 @@ pub enum LinkCmd {
}
/// What a connection tells the session.
pub enum LinkEvent {
pub(crate) enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
@@ -385,7 +304,7 @@ pub enum LinkEvent {
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`ConnectOptions::audio`]); `time` is its RTP time on the 48 kHz
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
+77 -13
View File
@@ -1,12 +1,74 @@
//! [`SessionLink`]: the engine's [`ServerLink`], over a
//! [`SessionLink`]: what `session.rs` talks to as the voice source, over a
//! `voelin_proto::link::Session` (`docs/session-seam.md` sections 3 and 4).
//!
//! `session.rs` hands a link its [`ConnectOptions`] and a [`LinkCtx`] and
//! `session.rs` hands a link its [`VoiceOptions`] and a [`LinkCtx`] and
//! talks to it with [`LinkCmd`]s and [`LinkEvent`]s. SessionLink opens the
//! session through [`Backends`], runs the connect sequence (the server, the
//! HOME, SERVER and LIVE scopes, the seat in voice), keeps a replica of what
//! the host pushes and projects it into the older model, and turns every
//! command into the `Session` call that stands for it.
//!
//! # The vocabulary of the session
//!
//! - [`SessionLink::spawn`] returns at once; the connection runs on its own
//! task and reports through `events`. Connecting is not an event: the
//! session shows `Connecting` from the moment it spawned the link, until
//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed).
//! - The first thing a connected link reports is [`LinkEvent::Connected`]
//! (name, backend, what it can do, our client id, the server's unique id),
//! then [`LinkEvent::Presence`] whenever anything in the server's tree or
//! client list changed (a full snapshot each time) and
//! [`LinkEvent::OwnChannel`] when we moved.
//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for,
//! reports that the connection ended, whichever way it did; a link sends it
//! once, and nothing from the connection itself follows it. A link that
//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves.
//! It is not promised to be the last event of the link: the stream task of
//! a connection with streams is a task of its own, which winds down after
//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and
//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its
//! streams, may follow `Disconnected`. The session does not depend on the
//! order: it ends our own stream and the audio of watched streams itself
//! when it hears `Disconnected`, and ignores what a link says after that,
//! like the events of a replaced one.
//! - Streams (screen sharing) are the link's business from the capabilities
//! on: when `Capabilities::streams` is set in `Connected`, the connection
//! has a stream task, takes [`LinkCmd::Stream`] and reports through the
//! event bus ([`LinkCtx::emit`]) like the other answers that need not pass
//! the session first (file lists, transfers, offline messages, stream
//! state). What the session must place itself comes as events: our own
//! stream's life ([`LinkEvent::OwnStream`], for the gateway directory) and
//! the audio of watched streams ([`LinkEvent::StreamAudio`], for the audio
//! thread, and [`LinkEvent::StreamAudioEnded`] when a stream's audio is
//! over). When the session replaces a connection it gives the old link
//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear of
//! their end before the link stops reading commands).
//! - What the session must see first (chat, pokes, who is talking, audio)
//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file
//! list, a request's `Done`) go straight to the event bus with
//! [`LinkCtx::emit`].
//! - Events of a link the session replaced are ignored (each link has a
//! generation), so a link need not stop emitting at once.
//!
//! # What is still TeamSpeak's
//!
//! The vocabulary, and the engine above it, is not backend-neutral yet:
//!
//! - Client ids are TeamSpeak's `u16`: `own_client` of
//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of
//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a
//! [`ChatMessage`](voelin_model::ChatMessage), and the viewer and streamer
//! ids of the stream API.
//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client
//! ids, `u64` channel and group ids, server and channel groups, talk
//! power, icons, badges and the myTeamSpeak avatar.
//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream
//! protocol: `PeerConfig` in [`VoiceOptions::stream_peer`], `MediaFrame`
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
//! API (re-exported from [`crate::stream`]). TeamSpeak 6 streams are peer
//! to peer, so their commands and events pass the `Session` through a local
//! port ([`StreamPort`]) for now.
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
@@ -32,8 +94,8 @@ use voelin_proto::v1::{
use super::media::{Incoming, TalkTracker, Uplink};
use super::project::{self, View};
use super::{
Backends, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalCtx, Remote,
ServerLink, StreamEvent, StreamPort,
Backends, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalCtx, Remote, StreamEvent,
StreamPort, VoiceOptions, connect_params,
};
use crate::files::{self, FileEntry, Report, Sink, TransferId, TransferState};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
@@ -60,12 +122,14 @@ impl SessionLink {
pub(crate) fn new(backends: Backends) -> Self {
Self { backends: Arc::new(backends) }
}
}
impl ServerLink for SessionLink {
fn spawn(
/// Connect to the server `options` names and run the connection on its own
/// task: take commands from `cmds`, report through `events`, and end the
/// connection with [`LinkEvent::Disconnected`]. Does not block. One
/// SessionLink serves every session of an engine.
pub(crate) fn spawn(
&self,
options: ConnectOptions,
options: VoiceOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
@@ -175,7 +239,7 @@ pub(crate) fn capabilities(
async fn run(
backends: Arc<Backends>,
options: ConnectOptions,
options: VoiceOptions,
ctx: LinkCtx,
mut cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
@@ -200,14 +264,14 @@ async fn until_disconnect(
/// Connect and run the connection; the reason it ended with.
async fn drive(
backends: &Backends,
options: &ConnectOptions,
options: &VoiceOptions,
ctx: &LinkCtx,
cmds: &mut mpsc::UnboundedReceiver<LinkCmd>,
events: &mpsc::UnboundedSender<LinkEvent>,
) -> Option<String> {
let (media_tx, media_rx) = mpsc::unbounded_channel();
let sink: Arc<dyn MediaSink> = Arc::new(MediaQueue(media_tx));
let params = match crate::ts::ts_session::connect_params(options, sink, backends) {
let params = match connect_params(options, sink, backends) {
Ok(params) => params,
Err(e) => return connect_failure(&e),
};
@@ -422,7 +486,7 @@ impl Conn {
/// Find the server, subscribe, wait for the syncs, take the seat in voice,
/// and tell the session it is connected (`docs/session-seam.md` 4.2).
async fn establish(&mut self, options: &ConnectOptions) -> Result<(), Option<String>> {
async fn establish(&mut self, options: &VoiceOptions) -> Result<(), Option<String>> {
let fail = |e: SessionError| Some(text(&e, true)).filter(|t| !t.is_empty());
// The server: the only one listed, or the lowest.
let listed = self
@@ -528,7 +592,7 @@ impl Conn {
/// The channel to join: the bookmark's (`/<id>` or a path of names), else
/// the server's default.
fn join_channel(&self, options: &ConnectOptions) -> u64 {
fn join_channel(&self, options: &VoiceOptions) -> u64 {
let wanted = options.channel.as_deref().filter(|c| !c.is_empty());
if let Some(path) = wanted {
if let Some(id) = voelin_model::channel_path_id(path) {
+9 -8
View File
@@ -28,6 +28,7 @@ use crate::offline::OfflineMessage;
use crate::offline::OfflineMessageInfo;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamKind};
use crate::ts::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
use crate::{BackendInfo, Event, JoinFailure};
const ME: u16 = 7;
@@ -157,7 +158,7 @@ impl Rig {
let bus = ctx.events.subscribe();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx);
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(connected).unwrap();
inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap();
@@ -960,7 +961,7 @@ async fn a_connect_that_fails_is_a_disconnect_with_the_reason() {
let ctx = LocalCtx::standalone().link;
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx);
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(LinkEvent::Disconnected(Some("connection refused".into()))).unwrap();
let event = within("the end", events.recv()).await;
@@ -972,7 +973,7 @@ async fn a_connect_that_fails_is_a_disconnect_with_the_reason() {
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let link = SessionLink::new(Backends::empty());
link.spawn(ConnectOptions::new("voelin://host", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("voelin://host", "tester"), ctx, cmd_rx, event_tx);
let event = within("the end", events.recv()).await;
assert!(
matches!(event, LinkEvent::Disconnected(Some(ref why)) if why == "no connector for voelin://host"),
@@ -1386,7 +1387,7 @@ async fn the_engine_consumes_any_session_a_connector_makes() {
let ctx = LocalCtx::standalone().link;
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
async fn event<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
@@ -1804,7 +1805,7 @@ async fn a_session_that_ends_during_the_connect_syncs_says_why() {
let ctx = LocalCtx::standalone().link;
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
// The three subscriptions are answered; two syncs end, the LIVE one never does.
let handle = loop {
@@ -1851,7 +1852,7 @@ async fn the_text_of_an_address_nobody_serves_keeps_the_channel_password_out() {
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let link = SessionLink::new(Backends::empty());
let mut options = ConnectOptions::new("ts.example.com:9987", "tester");
let mut options = VoiceOptions::new("ts.example.com:9987", "tester");
options.channel = Some("Raid".into());
options.channel_password = Some("hunter2".into());
link.spawn(options, ctx, cmd_rx, event_tx);
@@ -2188,7 +2189,7 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
let mut bus = ctx.events.subscribe();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
// The host offers files, the server does not.
let capabilities = event_of(&mut events, |e| match e {
@@ -2270,7 +2271,7 @@ async fn a_bookmark_with_a_port_that_is_no_port_does_not_connect() {
let ctx = LocalCtx::standalone().link;
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(ConnectOptions::new("ts.example.com:99999", "tester"), ctx, cmd_rx, event_tx);
link.spawn(VoiceOptions::new("ts.example.com:99999", "tester"), ctx, cmd_rx, event_tx);
let reason = event_of(&mut events, |e| match e {
LinkEvent::Disconnected(reason) => Some(reason),
_ => None,
+5 -5
View File
@@ -29,7 +29,7 @@ use crate::gateway::{
Push, ReactionPush,
};
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, ServerLink};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::{
@@ -84,7 +84,7 @@ impl SessionHandle {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
link: Arc<SessionLink>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
@@ -283,7 +283,7 @@ struct OwnStream {
struct Session {
/// Starts the voice connections.
link: Arc<dyn ServerLink>,
link: Arc<SessionLink>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -375,7 +375,7 @@ impl Session {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
link: Arc<SessionLink>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
@@ -2259,7 +2259,7 @@ mod banner_tests {
frames,
AudioSettings::default(),
shared,
Arc::new(crate::TsLink::new()),
Arc::new(SessionLink::new(crate::Backends::empty())),
);
(session, receiver)
}
+1 -1
View File
@@ -171,7 +171,7 @@ impl PartialEq for StreamSink {
}
}
/// What the session asks of the streams of a connection ([`crate::link::LinkCmd::Stream`]).
/// What the session asks of the streams of a connection (`LinkCmd::Stream`).
#[derive(Debug)]
pub enum StreamCmd {
Start {
+1 -1
View File
@@ -26,5 +26,5 @@ pub(crate) mod ts_session;
pub mod versions;
mod voice;
pub use ts_link::TsLink;
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
pub use ts_session::TsConnector;
+74 -5
View File
@@ -1,6 +1,11 @@
//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`].
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
//!
//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and
//! The engine does not know this vocabulary: it talks to a
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
//! or 6 client with `tsclientlib` and
//! runs the connection ([`super::voice`]) with everything that rides on it:
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
//! stream task. Which product the server is (and what it can do) is decided
@@ -15,9 +20,73 @@
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use voelin_stream::PeerConfig;
use super::voice;
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
/// Starts the connection of a link: the contract of `crate::link` for the
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
/// with them, and the module documentation of `link/session_link.rs` states
/// it.
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub(crate) trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a TeamSpeak connection needs to know: the server, who to be, where
/// to join. The reverse of what the engine's `ConnectParams` carry
/// (`ts_session::inner_options`).
#[derive(Clone, Debug)]
pub(crate) struct ConnectOptions {
pub address: String,
pub nickname: String,
/// The identity to connect with; none generates one.
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections.
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
/// Options for `address` and `nickname`, the rest as a test leaves it.
#[cfg(test)]
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// The main myTeamSpeak account of an application, as its connections show
/// it to the servers: the proof of the myTS ID, and what servers are shown
@@ -97,9 +166,9 @@ impl Watches {
}
}
/// Connects to TeamSpeak 3 and 6 servers. The engine's default link.
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
#[derive(Clone, Default)]
pub struct TsLink {
pub(crate) struct TsLink {
account: Arc<Account>,
}
@@ -46,6 +46,7 @@ use voelin_proto::v1::request::Op;
use voelin_proto::v1::{self, entity::Kind};
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
@@ -136,7 +137,7 @@ async fn raise_flood_limits(dev: &Dev) {
/// connector, with its push channel and media sink.
async fn session(
dev: &Dev,
options: &ConnectOptions,
options: &VoiceOptions,
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
raise_flood_limits(dev).await;
let (sink, media) = media_channel();
@@ -169,10 +170,10 @@ fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
impl Client {
async fn connect(dev: &Dev, nick: &str) -> Self {
Self::connect_with(dev, ConnectOptions::new(dev.voice, nick)).await
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
}
async fn connect_with(dev: &Dev, options: ConnectOptions) -> Self {
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
let (session, pushes, media) = session(dev, &options).await;
let mut client = Self {
session,
@@ -414,7 +415,7 @@ const EXPECTED: [(&str, Expect); 17] = [
/// of an unrelated fake host, which the cases that are run never touch.
async fn fixture(dev: Dev) -> Fixture {
let (session, pushes, media) =
session(&dev, &ConnectOptions::new(dev.voice, dev.nick("conf"))).await;
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
let unrelated = FakeConnector::new();
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
unrelated.connect(params).await.expect("a fake session");
@@ -547,7 +548,7 @@ async fn refused_moves(dev: Dev) {
let check = {
let token = token.clone();
tokio::spawn(async move {
let mut options = ConnectOptions::new(dev.voice, dev.nick("moves"));
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
options.token = Some(token);
let client = Client::connect_with(&dev, options).await;
let code = |result: Result<v1::VoiceState, SessionError>| match result {
@@ -742,7 +743,7 @@ async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
}
async fn channel_file_with_a_key(dev: Dev, token: String) {
let mut options = ConnectOptions::new(dev.voice, dev.nick("files"));
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
options.token = Some(token);
let a = Client::connect_with(&dev, options).await;
let channel = a.seat.channel_id;
+55 -153
View File
@@ -1,7 +1,7 @@
//! 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):
//! [`LinkSession`] is a `Session` over any [`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
@@ -11,10 +11,10 @@
//!
//! 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).
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
//! 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;
@@ -37,24 +37,21 @@ 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,
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, 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 super::{ConnectOptions, ServerLink, TsLink, versions};
use crate::BackendInfo;
use crate::link::{
Backends, BoxDuplex, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, LocalConnected,
LocalConnector, LocalCtx, ServerLink, StreamPort,
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
VERSION_PARAM,
};
use crate::ts::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";
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
/// 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);
@@ -70,122 +67,9 @@ fn now_ms() -> i64 {
// ---- 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.
///
/// An address a link cannot carry is refused here ([`bookmark`]).
pub(crate) fn connect_params(
options: &ConnectOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
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()
};
Ok(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) -> Result<String, SessionError> {
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("://") => bookmark(&options.address)?,
// Some other scheme: as given, for the connector of that scheme.
_ => return Ok(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));
}
Ok(url)
}
/// The link to a bookmark's `host[:port]`.
///
/// A link cannot say everything an address can: it drops a port that is no
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
/// `%` (so that a `?` in the host would hide the channel behind the next
/// one). The TeamSpeak library refuses such an address when it resolves it;
/// so does this, in words, instead of connecting to something else.
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
let address = address.trim();
// Without the query: a link keeps secrets in it.
let shown = crate::link::without_query(address);
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
if address.is_empty()
|| address
.chars()
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
{
return Err(not_an_address());
}
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
// colon (more colons are an IPv6 address without a port).
let port = if let Some(rest) = address.strip_prefix('[') {
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
} else {
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
};
if let Some(port) = port
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
{
return Err(SessionError::Protocol(format!(
"the port in {shown} is not a number from 1 to 65535"
)));
}
Ok(voelin_model::ServerLink::new(address))
}
/// The options a TeamSpeak link is connected with: the reverse of
/// [`connect_params`].
/// `link::connect_params`. A client version spec that [`versions::resolve`]
/// refuses fails the connect, in words.
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
@@ -208,14 +92,26 @@ fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOption
));
}
};
let client_version = params
let spec = 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());
.map(|text| {
URL_SAFE_NO_PAD
.decode(text)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
})
.transpose()?;
let client_version = match spec {
None => None,
Some(spec) => versions::resolve(&spec).map_err(|e| {
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
})?,
};
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
Ok(ConnectOptions {
address: link.address(),
@@ -485,6 +381,7 @@ impl LinkConnector {
}
/// A connector for addresses of every scheme.
#[cfg(test)]
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
@@ -516,13 +413,14 @@ impl LocalConnector for LinkConnector {
}
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
/// with `tsclientlib`: [`LinkSession`]s over [`TsLink`].
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
///
/// Clones share one account: the main myTeamSpeak account that every
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
/// [`TsConnector::set_myts_data`]), also those made before it was set.
/// Register a connector in the engine's registry with
/// [`Backends::register_teamspeak`] and keep a clone to set the account.
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
/// keep a clone to set the account.
#[derive(Clone)]
pub struct TsConnector {
connector: LinkConnector,
@@ -754,19 +652,21 @@ async fn connect_link(
#[cfg(test)]
mod tests {
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
use voelin_proto::link::IssuerTrust;
fn params(options: &ConnectOptions) -> ConnectParams {
fn params(options: &VoiceOptions) -> ConnectParams {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty()).unwrap()
}
fn back(options: &ConnectOptions) -> ConnectOptions {
fn back(options: &VoiceOptions) -> 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 mut options = VoiceOptions::new("ts.example.com:9988", "nick");
let same = back(&options);
assert_eq!(
(same.address.as_str(), same.nickname.as_str()),
@@ -782,8 +682,10 @@ mod tests {
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::ts::versions::native_version().unwrap());
let identity = tsclientlib::Identity::create();
options.identity = Some(crate::ts::identity::to_blob(&identity));
// A spec the user can give; the connector resolves it.
options.client_version = Some("generic".into());
options.audio = false;
let sent = params(&options);
assert_eq!(sent.hello.password, "s3cret pass&word");
@@ -801,44 +703,44 @@ mod tests {
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);
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
assert!(got.client_version.is_some());
// 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());
let b = got.identity.as_ref().unwrap();
assert_eq!(serde_json::to_value(&identity).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");
let mut options = VoiceOptions::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 options = VoiceOptions::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");
let options = VoiceOptions::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"));
let mut sent = params(&VoiceOptions::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"));
let mut sent = params(&VoiceOptions::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"));
let mut sent = params(&VoiceOptions::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());
@@ -854,7 +756,7 @@ mod tests {
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&ConnectOptions::new("ts.example.com", "nick"));
let sent = params(&VoiceOptions::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());
@@ -867,7 +769,7 @@ mod tests {
/// Why `connect_params` refused an address, if it did.
fn refused(address: &str) -> Option<String> {
let (media, _rx) = voelin_proto::test_util::media_channel();
match connect_params(&ConnectOptions::new(address, "nick"), media, &Backends::empty()) {
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
Ok(_) => None,
Err(SessionError::Protocol(text)) => Some(text),
Err(other) => panic!("{address}: {other}"),
@@ -925,7 +827,7 @@ mod tests {
("::1", "::1"),
("2001:db8::1", "2001:db8::1"),
] {
let mut options = ConnectOptions::new(address, "nick");
let mut options = VoiceOptions::new(address, "nick");
options.channel = Some("Games/Raid".into());
let got = back(&options);
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
@@ -936,7 +838,7 @@ mod tests {
/// (13): an empty option is none, and an empty nickname stays empty.
#[test]
fn empty_options_come_back_as_none() {
let mut options = ConnectOptions::new("ts.example.com", "");
let mut options = VoiceOptions::new("ts.example.com", "");
options.server_password = Some(String::new());
options.channel = Some(String::new());
options.channel_password = Some(String::new());
+2 -2
View File
@@ -37,10 +37,10 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavo
use voelin_stream::{ClientState, Request, StreamNotification};
use super::book::presence_from_book;
use super::ts_link::Watches;
use super::ts_link::{ConnectOptions, Watches};
use crate::cache::{self, IMAGE_NEGOTIATION, image_download_time};
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
use crate::link::{BoxDuplex, BoxRead, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote};
use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkCtx, LinkEvent, Remote};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
use crate::settings::FILES_PROGRESS_MS;
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
+7 -7
View File
@@ -122,15 +122,15 @@ impl App {
}
let mut options = VoiceOptions::new(&b.address, &b.nickname);
if let Some(spec) = &b.client_version {
match voelin_core::ts::versions::resolve(spec) {
Ok(version) => options.client_version = version,
Err(error) => {
self.set_status(format!("Invalid client compatibility version: {error}"));
return false;
}
// The engine resolves the spec when it connects; asking now tells the
// user at once.
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
self.set_status(format!("Invalid client compatibility version: {error}"));
return false;
}
options.client_version = Some(spec.clone());
}
options.identity = Some(self.identity_for(Some(b.id)));
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = channel;
options.channel_password = channel_password;
+1 -1
View File
@@ -254,7 +254,7 @@ pub async fn run(args: EngineArgs) -> Result<()> {
let mut options = VoiceOptions::new(&args.address, &args.nick);
if let Some(path) = &args.identity {
options.identity = Some(crate::identity::load(path)?);
options.identity = Some(voelin_core::ts::identity::to_blob(&crate::identity::load(path)?));
}
engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
+1 -1
View File
@@ -104,7 +104,7 @@ pub async fn run(args: GatewayArgs) -> Result<()> {
});
if let Some(addr) = &args.voice {
let mut options = VoiceOptions::new(addr, &args.nick);
options.identity = Some(identity);
options.identity = Some(voelin_core::ts::identity::to_blob(&identity));
if args.loopback {
options.stream_peer = PeerConfig::loopback();
}