ts::voice::Voice::command answered LinkCmd::Download, Upload and CancelTransfer with anyhow::bail!, which ends the whole TeamSpeak connection: chat, voice, presence and the stream task with it. SessionLink copies the bytes of a transfer itself and never sends them, but a command that does arrive is that transfer's failure, not the connection's. Download and Upload answer their report with TransferState::Failed and the connection goes on; CancelTransfer has no report and nothing to cancel, so it is logged at debug. A unit test gives an unconnected Voice the three commands: each returns Ok, the two reports see Failed, nothing is pending. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1677 lines
58 KiB
Rust
1677 lines
58 KiB
Rust
//! The TeamSpeak connection: a normal client connection
|
|
//! ([`TsLink`](super::ts_link::TsLink) runs [`run`]).
|
|
//!
|
|
//! Besides presence, chat, voice and stream signalling it carries what only
|
|
//! a client connection can do: pokes, file transfer (channel files,
|
|
//! avatars, icons) and offline messages. Their answers go straight to the
|
|
//! engine's event bus ([`LinkCtx`]); what the session must see first
|
|
//! (chat, pokes: blocking) comes as [`LinkEvent`]s.
|
|
//!
|
|
//! On TeamSpeak 6 servers the connection also runs the stream task
|
|
//! ([`crate::stream`]): it hands the task the server's stream notifications
|
|
//! and the clients' channels, and sends the requests the task makes. The
|
|
//! session only sees the commands it gave ([`LinkCmd::Stream`]) and, for the
|
|
//! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]).
|
|
|
|
use std::collections::{BTreeMap, HashMap};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use base64::Engine as _;
|
|
use futures::prelude::*;
|
|
use tokio::sync::{mpsc, oneshot, watch};
|
|
use tokio::time::{Instant, timeout};
|
|
use tracing::{debug, info, warn};
|
|
use tsclientlib::events::Event as BookEvent;
|
|
use tsclientlib::messages::c2s;
|
|
use tsclientlib::prelude::*;
|
|
use tsclientlib::{
|
|
Connection, DisconnectOptions, FiletransferHandle, InMessage, MessageHandle, MessageTarget,
|
|
StreamItem, TsError,
|
|
};
|
|
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutCommand, OutPacket};
|
|
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
|
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavor};
|
|
use voelin_stream::{ClientState, Request, StreamNotification};
|
|
|
|
use super::book::presence_from_book;
|
|
use super::ts_link::{ConnectOptions, Watches};
|
|
use crate::files::{self, FileEntry, RequestId, TransferState};
|
|
use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkCtx, LinkEvent, Remote};
|
|
use crate::offline::{OfflineMessage, OfflineMessageInfo};
|
|
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
|
|
use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX};
|
|
|
|
impl Remote {
|
|
fn cpw(&self) -> String {
|
|
encode_password(self.password.as_deref())
|
|
}
|
|
}
|
|
|
|
fn encode_password(password: Option<&str>) -> String {
|
|
password
|
|
.filter(|p| !p.is_empty())
|
|
.map(|p| tsproto_types::crypto::encode_password(p.as_bytes()))
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// What the engine is told of the server this connection reached: the
|
|
/// product and version to show, and what the product can do. The flavor
|
|
/// (TeamSpeak 3 or 6) is decided here, from the version the server sent, and
|
|
/// goes no further.
|
|
fn backend_of(flavor: &ServerFlavor) -> (BackendInfo, Capabilities) {
|
|
let (product, version) = match flavor {
|
|
ServerFlavor::Ts3(version) => ("TeamSpeak 3", version.to_string()),
|
|
ServerFlavor::Ts6(version) => ("TeamSpeak 6", version.to_string()),
|
|
// Not recognised: the version string as it came, for the status
|
|
// line and the log.
|
|
ServerFlavor::Unknown(raw) => ("", raw.clone()),
|
|
};
|
|
(BackendInfo { product: product.into(), version }, flavor.capabilities())
|
|
}
|
|
|
|
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 `client_user_tag` is to be set to, if anything: on servers that
|
|
/// know it (`user_tags`), the tag `wanted` where `shown` is another (or
|
|
/// none), or `again` after a new account proof; empty (cleared) where one
|
|
/// is shown that is no longer wanted.
|
|
fn user_tag_update(
|
|
wanted: Option<&tsclientlib::UserTag>,
|
|
shown: Option<&tsclientlib::UserTag>,
|
|
user_tags: bool,
|
|
again: bool,
|
|
now_ms: i64,
|
|
) -> Option<String> {
|
|
match (wanted, shown) {
|
|
_ if !user_tags => None,
|
|
(Some(tag), shown) if again || shown != Some(tag) => Some(tag.value(now_ms)),
|
|
(None, Some(_)) => Some(String::new()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Which of the badges sent (`sent`, their ids) the server does not
|
|
/// publish (`client_signed_badges`: the ids that verified, joined by `,`).
|
|
fn badges_dropped<'a>(sent: &'a [String], published: &str) -> Vec<&'a str> {
|
|
let published: Vec<&str> = published.split(',').collect();
|
|
sent.iter().map(String::as_str).filter(|id| !published.contains(id)).collect()
|
|
}
|
|
|
|
enum Input {
|
|
MytsIdentityChanged,
|
|
MytsDataChanged,
|
|
AccountSourceClosed,
|
|
Item(Option<Result<StreamItem, tsclientlib::Error>>),
|
|
Cmd(Option<LinkCmd>),
|
|
/// A request of the stream task, for the server.
|
|
Request(Request),
|
|
Tick,
|
|
}
|
|
|
|
/// A command waiting for the server's answer.
|
|
enum Pending {
|
|
MytsIdentity(Instant),
|
|
/// `updatemytsdata`: whether it showed the avatar and the badges (else
|
|
/// it cleared them), and the ids of the badges shown; what the server
|
|
/// published is only logged.
|
|
MytsData {
|
|
avatar: Option<bool>,
|
|
badges: Option<bool>,
|
|
badge_ids: Vec<String>,
|
|
},
|
|
/// `clientupdate client_user_tag`: the value (empty: cleared); only logged.
|
|
UserTag(String),
|
|
Stream(Request),
|
|
FileList {
|
|
request: RequestId,
|
|
channel: ChannelId,
|
|
path: String,
|
|
entries: Vec<FileEntry>,
|
|
},
|
|
Done(RequestId),
|
|
OfflineList {
|
|
request: RequestId,
|
|
messages: Vec<OfflineMessageInfo>,
|
|
},
|
|
OfflineGet {
|
|
request: RequestId,
|
|
id: u32,
|
|
message: Option<OfflineMessage>,
|
|
},
|
|
/// Moving ourselves; refusals are reported as [`Event::JoinFailed`].
|
|
Move {
|
|
channel: ChannelId,
|
|
},
|
|
/// Failures are reported as [`LinkEvent::Error`] with this label.
|
|
Report(&'static str),
|
|
/// Best effort: the answer does not matter.
|
|
Quiet,
|
|
}
|
|
|
|
/// A transfer connection the server has not opened yet: the caller wants the
|
|
/// connection itself, and does the copying (the engine's `SessionLink`
|
|
/// does, with its progress, its limits and its cancel).
|
|
enum Job {
|
|
/// [`LinkCmd::OpenRead`].
|
|
OpenRead(oneshot::Sender<Result<(u64, BoxRead), String>>),
|
|
/// [`LinkCmd::OpenWrite`].
|
|
OpenWrite(oneshot::Sender<Result<(u64, BoxDuplex), String>>),
|
|
}
|
|
|
|
impl Job {
|
|
/// The job could not be done: tell whoever waits.
|
|
fn fail(self, text: String) {
|
|
match self {
|
|
Job::OpenRead(reply) => {
|
|
let _ = reply.send(Err(text));
|
|
}
|
|
Job::OpenWrite(reply) => {
|
|
let _ = reply.send(Err(text));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Run a voice connection until it ends or is told to disconnect.
|
|
pub(crate) async fn run(
|
|
options: ConnectOptions,
|
|
ctx: LinkCtx,
|
|
account: Watches,
|
|
mut commands: mpsc::UnboundedReceiver<LinkCmd>,
|
|
events: mpsc::UnboundedSender<LinkEvent>,
|
|
) {
|
|
let reason = match run_inner(&options, ctx, account, &mut commands, &events).await {
|
|
Ok(()) => None,
|
|
Err(e) => Some(e.to_string()),
|
|
};
|
|
let _ = events.send(LinkEvent::Disconnected(reason));
|
|
}
|
|
|
|
/// The stream task of a connection. When the connection ends, in whatever
|
|
/// way, its streams end with it.
|
|
struct ConnectionStreams(StreamHandle);
|
|
|
|
impl ConnectionStreams {
|
|
fn send(&self, input: impl Into<StreamInput>) {
|
|
self.0.send(input);
|
|
}
|
|
}
|
|
|
|
impl Drop for ConnectionStreams {
|
|
fn drop(&mut self) {
|
|
// After a `StreamCmd::Shutdown` of the session this reaches a task
|
|
// that has ended, which is fine; the task keeps a sender of its own,
|
|
// so it never ends by itself.
|
|
self.0.send(StreamCmd::Shutdown("voice disconnected".into()));
|
|
}
|
|
}
|
|
|
|
/// The state of a connected voice source.
|
|
struct Voice {
|
|
con: Connection,
|
|
link: LinkCtx,
|
|
/// The account this connection presents (and keeps open).
|
|
account: Watches,
|
|
events: mpsc::UnboundedSender<LinkEvent>,
|
|
server_uid: String,
|
|
/// Who is talking: last voice packet per client.
|
|
talking: HashMap<u16, Instant>,
|
|
pending: HashMap<MessageHandle, Pending>,
|
|
jobs: HashMap<FiletransferHandle, Job>,
|
|
/// `updatemytsdata` is to be sent once connected again: a reconnect
|
|
/// (tsclientlib's own) leaves the server without it.
|
|
myts_data_due: bool,
|
|
/// What this connection has shown the server of the account (avatar,
|
|
/// badges, User Tag): what changes, and what a sign-out clears.
|
|
myts_shown: tsclientlib::MytsData,
|
|
/// The streams of the connection (TeamSpeak 6 servers).
|
|
streams: Option<ConnectionStreams>,
|
|
/// The clients as last told to the streams: channel and `client_is_streaming`.
|
|
streaming_clients: BTreeMap<u16, ClientState>,
|
|
}
|
|
|
|
async fn run_inner(
|
|
options: &ConnectOptions,
|
|
link: LinkCtx,
|
|
account: Watches,
|
|
commands: &mut mpsc::UnboundedReceiver<LinkCmd>,
|
|
events: &mpsc::UnboundedSender<LinkEvent>,
|
|
) -> anyhow::Result<()> {
|
|
let version = match &options.client_version {
|
|
Some(version) => version.clone(),
|
|
None => super::versions::native_version()?,
|
|
};
|
|
let mut builder = Connection::build(options.address.clone())
|
|
.name(options.nickname.clone())
|
|
.version(version)
|
|
.metadata(super::versions::client_metadata());
|
|
if let Some(identity) = &options.identity {
|
|
builder = builder.identity(identity.clone());
|
|
}
|
|
if let Some(pw) = &options.server_password {
|
|
builder = builder.password(pw.clone());
|
|
}
|
|
if let Some(channel) = &options.channel {
|
|
builder = builder.channel(channel.clone());
|
|
}
|
|
if let Some(pw) = options.channel_password.as_ref().filter(|p| !p.is_empty()) {
|
|
builder = builder.channel_password(pw.clone());
|
|
}
|
|
if let Some(token) = &options.token {
|
|
builder = builder.default_token(token.clone());
|
|
}
|
|
let mut identity = account.identity.clone();
|
|
let mut data = account.data.clone();
|
|
// A changed account invalidates an in-flight handshake. Drop that connection
|
|
// and take a fresh snapshot before publishing any connected state.
|
|
let mut con = timeout(Duration::from_secs(30), async {
|
|
loop {
|
|
let snapshot = identity.borrow_and_update().as_deref().cloned();
|
|
let mut con = builder.clone().myts_identity(snapshot).connect()?;
|
|
let connected = tokio::select! {
|
|
biased;
|
|
changed = identity.changed() => {
|
|
changed.map_err(|_| anyhow::anyhow!("account source closed"))?;
|
|
continue;
|
|
}
|
|
connected = async {
|
|
con.events()
|
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
|
.next().await
|
|
} => connected,
|
|
};
|
|
match connected {
|
|
Some(Ok(_)) => {}
|
|
Some(Err(e)) => return Err(anyhow::Error::from(e)),
|
|
None => anyhow::bail!("connection closed"),
|
|
}
|
|
if identity.has_changed().unwrap_or(true) {
|
|
// Connected already: leave properly, or the server keeps a
|
|
// client with the old account until it times out, next to
|
|
// the new one.
|
|
let _ = shutdown_connection(con).await;
|
|
continue;
|
|
}
|
|
return Ok(con);
|
|
}
|
|
})
|
|
.await
|
|
.map_err(|_| anyhow::anyhow!("timed out while connecting"))??;
|
|
// The requests the stream task makes; `requests_tx` stays here, so the
|
|
// channel is open (and empty) also where there is no stream task.
|
|
let (requests_tx, mut requests) = mpsc::unbounded_channel();
|
|
let (server_uid, streams) = {
|
|
let state = con.get_state()?;
|
|
let flavor = ServerFlavor::from_version_string(&state.server.version);
|
|
let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts());
|
|
let server_uid = ids.for_server(matches!(flavor, ServerFlavor::Ts6(_))).to_owned();
|
|
info!(server = %state.server.name, ?flavor, %server_uid, "voice connected");
|
|
let own_uid = state
|
|
.clients
|
|
.get(&state.own_client)
|
|
.and_then(|c| c.uid.as_ref())
|
|
.map(|u| u.as_ref().to_string());
|
|
let (backend, capabilities) = backend_of(&flavor);
|
|
// Before the session hears of the connection, so that the commands it
|
|
// then gives find the task.
|
|
let streams = capabilities.streams.then(|| {
|
|
ConnectionStreams(StreamHandle::spawn(
|
|
link.session,
|
|
state.own_client.0,
|
|
options.stream_peer.clone(),
|
|
requests_tx.clone(),
|
|
link.events.clone(),
|
|
link.frames.clone(),
|
|
options.audio,
|
|
link.settings.clone(),
|
|
events.clone(),
|
|
))
|
|
});
|
|
let _ = events.send(LinkEvent::Connected {
|
|
name: state.server.name.clone(),
|
|
backend,
|
|
capabilities,
|
|
own_client: state.own_client.0,
|
|
server_uid: server_uid.clone(),
|
|
own_uid,
|
|
});
|
|
(server_uid, streams)
|
|
};
|
|
// Subscribe to all channels to see everyone.
|
|
let cmd = con.get_state()?.server.set_subscribed(true);
|
|
cmd.send(&mut con)?;
|
|
let mut voice = Voice {
|
|
con,
|
|
link,
|
|
account,
|
|
events: events.clone(),
|
|
server_uid,
|
|
talking: HashMap::new(),
|
|
pending: HashMap::new(),
|
|
jobs: HashMap::new(),
|
|
myts_data_due: false,
|
|
myts_shown: tsclientlib::MytsData::default(),
|
|
streams,
|
|
streaming_clients: BTreeMap::new(),
|
|
};
|
|
voice.publish_state()?;
|
|
// The account's avatar, badges and User Tag, for everyone on the
|
|
// server (as the official client, once connected).
|
|
data.borrow_and_update();
|
|
voice.send_myts_data(true);
|
|
|
|
let mut tick = tokio::time::interval(Duration::from_millis(250));
|
|
let result = loop {
|
|
// Check on every turn so busy command/audio queues cannot delay expiry.
|
|
if voice.pending.values().any(|pending| {
|
|
matches!(pending, Pending::MytsIdentity(started)
|
|
if started.elapsed() >= Duration::from_secs(10))
|
|
}) {
|
|
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
|
|
}
|
|
let input = next_input(
|
|
&mut voice.con.events(),
|
|
commands,
|
|
&mut requests,
|
|
&mut tick,
|
|
&mut identity,
|
|
&mut data,
|
|
)
|
|
.await;
|
|
match input {
|
|
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
|
|
Input::MytsIdentityChanged => {
|
|
let snapshot = identity.borrow_and_update().as_deref().cloned();
|
|
match voice.con.update_myts_identity(snapshot) {
|
|
Ok(handle) => {
|
|
voice.pending.insert(handle, Pending::MytsIdentity(Instant::now()));
|
|
}
|
|
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
|
|
}
|
|
// After the proof, what is shown of the account (a sign-in):
|
|
// its change, if any, is in this one. All of it again: the
|
|
// server checks it for the myTS ID it holds when it comes.
|
|
data.borrow_and_update();
|
|
voice.send_myts_data(true);
|
|
}
|
|
Input::MytsDataChanged => {
|
|
data.borrow_and_update();
|
|
voice.send_myts_data(false);
|
|
}
|
|
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
|
|
Input::Item(Some(Err(e))) => break Err(e.into()),
|
|
Input::Item(Some(Ok(item))) => {
|
|
if let Err(e) = voice.item(item) {
|
|
break Err(e);
|
|
}
|
|
}
|
|
Input::Cmd(None) | Input::Cmd(Some(LinkCmd::Disconnect)) => break Ok(()),
|
|
Input::Cmd(Some(cmd)) => {
|
|
if let Err(e) = voice.command(cmd) {
|
|
let _ = voice.events.send(LinkEvent::Error(e.to_string()));
|
|
}
|
|
}
|
|
Input::Request(request) => {
|
|
if let Err(e) = voice.stream_request(request) {
|
|
let _ = voice.events.send(LinkEvent::Error(e.to_string()));
|
|
}
|
|
}
|
|
Input::Tick => voice.tick(),
|
|
}
|
|
};
|
|
// The streams end now, not after the shutdown below (up to three seconds):
|
|
// the commands are not read any more, so a `StreamCmd::Shutdown` the
|
|
// session sends from here on would never reach the stream task. Its end
|
|
// needs nothing of the connection: it reports to the session's channels.
|
|
drop(voice.streams.take());
|
|
// Transfers the server never opened fail; running ones go on.
|
|
for (_, job) in voice.jobs.drain() {
|
|
job.fail("disconnected".into());
|
|
}
|
|
let disconnect = shutdown_connection(voice.con).await;
|
|
result?;
|
|
disconnect?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn next_input(
|
|
stream: &mut (impl Stream<Item = Result<StreamItem, tsclientlib::Error>> + Unpin),
|
|
commands: &mut mpsc::UnboundedReceiver<LinkCmd>,
|
|
requests: &mut mpsc::UnboundedReceiver<Request>,
|
|
tick: &mut tokio::time::Interval,
|
|
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
|
data: &mut watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
|
) -> Input {
|
|
tokio::select! {
|
|
biased;
|
|
changed = identity.changed() => if changed.is_ok() {
|
|
Input::MytsIdentityChanged
|
|
} else {
|
|
Input::AccountSourceClosed
|
|
},
|
|
changed = data.changed() => if changed.is_ok() {
|
|
Input::MytsDataChanged
|
|
} else {
|
|
Input::AccountSourceClosed
|
|
},
|
|
input = async {
|
|
// Keep account changes first without starving network or timers when
|
|
// the audio command queue remains ready.
|
|
tokio::select! {
|
|
cmd = commands.recv() => Input::Cmd(cmd),
|
|
Some(request) = requests.recv() => Input::Request(request),
|
|
_ = tick.tick() => Input::Tick,
|
|
item = stream.next() => Input::Item(item),
|
|
}
|
|
} => input,
|
|
}
|
|
}
|
|
|
|
async fn shutdown_connection(mut con: Connection) -> Result<(), tsclientlib::Error> {
|
|
// disconnect() also returns Ok while Connecting. Never poll that stale
|
|
// handshake: dropping it is the cancellation boundary for logout.
|
|
if con.get_state().is_err() {
|
|
return Ok(());
|
|
}
|
|
con.disconnect(DisconnectOptions::new())?;
|
|
let _ = timeout(Duration::from_secs(3), async {
|
|
while con.get_state().is_ok() {
|
|
if con.events().next().await.is_none() {
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.await;
|
|
Ok(())
|
|
}
|
|
|
|
impl Voice {
|
|
fn publish_state(&mut self) -> anyhow::Result<()> {
|
|
let state = self.con.get_state()?;
|
|
let talking = |id| self.talking.contains_key(&id);
|
|
let presence = presence_from_book(state, Some(&self.server_uid), talking);
|
|
// The streams follow the clients' channels and streaming flags.
|
|
if let Some(streams) = &self.streams {
|
|
let clients: BTreeMap<_, _> = presence
|
|
.clients
|
|
.values()
|
|
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
|
|
.collect();
|
|
if clients != self.streaming_clients {
|
|
self.streaming_clients = clients.clone();
|
|
streams.send(StreamInput::Clients(clients));
|
|
}
|
|
}
|
|
let _ = self.events.send(LinkEvent::Presence(Box::new(presence)));
|
|
if let Some(own) = state.clients.get(&state.own_client) {
|
|
let _ = self.events.send(LinkEvent::OwnChannel(own.channel.0));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn tick(&mut self) {
|
|
let events = &self.events;
|
|
self.talking.retain(|client, last| {
|
|
let active = last.elapsed() < Duration::from_millis(400);
|
|
if !active {
|
|
let _ = events.send(LinkEvent::Talking { client: *client, talking: false });
|
|
}
|
|
active
|
|
});
|
|
}
|
|
|
|
fn item(&mut self, item: StreamItem) -> anyhow::Result<()> {
|
|
match item {
|
|
StreamItem::BookEvents(book_events) => {
|
|
for e in &book_events {
|
|
if let BookEvent::Message { target, invoker, message } = e {
|
|
self.message(target, invoker, message);
|
|
}
|
|
}
|
|
// Connected again after a reconnect.
|
|
if self.myts_data_due {
|
|
self.send_myts_data(true);
|
|
}
|
|
self.publish_state()?;
|
|
}
|
|
StreamItem::Audio(packet) => {
|
|
let from = match packet.data().data() {
|
|
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
|
_ => return Ok(()),
|
|
};
|
|
if self.talking.insert(from, Instant::now()).is_none() {
|
|
let _ = self.events.send(LinkEvent::Talking { client: from, talking: true });
|
|
}
|
|
if let Some(packet) = voice_packet(&packet) {
|
|
let _ = self.events.send(LinkEvent::Audio(packet));
|
|
}
|
|
}
|
|
StreamItem::MessageEvent(msg) => self.message_event(&msg),
|
|
StreamItem::MessageResult(handle, result) => {
|
|
if let Some(pending) = self.pending.remove(&handle) {
|
|
if matches!(pending, Pending::MytsIdentity(_)) {
|
|
result.map_err(|e| {
|
|
anyhow::anyhow!("myTeamSpeak account update: {}", e.error)
|
|
})?;
|
|
} else {
|
|
self.answered(pending, result.map_err(|e| e.error));
|
|
}
|
|
}
|
|
}
|
|
// The server opened a transfer connection: the caller that asked for it
|
|
// gets the connection itself.
|
|
StreamItem::FileDownload(handle, download) => {
|
|
if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_)))
|
|
&& let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle)
|
|
{
|
|
let _ = reply.send(Ok((download.size, Box::pin(download.stream))));
|
|
}
|
|
}
|
|
StreamItem::FileUpload(handle, upload) => {
|
|
if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_)))
|
|
&& let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle)
|
|
{
|
|
let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream))));
|
|
}
|
|
}
|
|
StreamItem::FiletransferFailed(handle, error) => {
|
|
if let Some(job) = self.jobs.remove(&handle) {
|
|
job.fail(transfer_error(&error));
|
|
}
|
|
}
|
|
StreamItem::DisconnectedTemporarily(reason) => {
|
|
warn!(?reason, "voice connection interrupted, reconnecting");
|
|
// A new client on the server: it shows nothing of the account.
|
|
self.myts_data_due = true;
|
|
self.myts_shown = tsclientlib::MytsData::default();
|
|
}
|
|
_ => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// A chat message or poke from the book.
|
|
fn message(&self, target: &MessageTarget, invoker: &tsclientlib::Invoker, text: &str) {
|
|
let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string());
|
|
let target = match target {
|
|
MessageTarget::Poke(_) => {
|
|
let _ = self.events.send(LinkEvent::Poke {
|
|
from: invoker.id.0,
|
|
from_uid: uid,
|
|
from_name: invoker.name.to_string(),
|
|
message: text.to_owned(),
|
|
});
|
|
return;
|
|
}
|
|
MessageTarget::Server => ChatTarget::Server,
|
|
MessageTarget::Channel => ChatTarget::Channel(self.own_channel().unwrap_or(0)),
|
|
// Our own private message comes back to us: it belongs to the
|
|
// chat with its receiver.
|
|
MessageTarget::Client(to) if Some(invoker.id) == self.own_client() => {
|
|
ChatTarget::Private(self.client_uid(to).unwrap_or_default())
|
|
}
|
|
MessageTarget::Client(_) => ChatTarget::Private(uid.clone().unwrap_or_default()),
|
|
};
|
|
let _ = self.events.send(LinkEvent::Chat(ChatMessage {
|
|
target,
|
|
author_name: invoker.name.to_string(),
|
|
author_uid: uid,
|
|
author_id: Some(invoker.id.0),
|
|
text: text.to_owned(),
|
|
ts_ms: now_ms(),
|
|
via_relay: false,
|
|
blocked: false,
|
|
}));
|
|
}
|
|
|
|
/// Messages the book does not handle: stream signalling, file lists,
|
|
/// offline messages.
|
|
fn message_event(&mut self, msg: &InMessage) {
|
|
match msg {
|
|
InMessage::FileList(list) => {
|
|
for part in list.iter() {
|
|
let path = files::normalize_dir(&part.path);
|
|
let entry = FileEntry {
|
|
name: part.name.clone(),
|
|
size: part.size,
|
|
modified_s: part.date_time.unix_timestamp(),
|
|
is_dir: !part.is_file,
|
|
};
|
|
let channel = part.channel_id.0;
|
|
if let Some(Pending::FileList { entries, .. }) = self.first_pending(|p| {
|
|
matches!(p, Pending::FileList { channel: c, path: p, .. }
|
|
if *c == channel && *p == path)
|
|
}) {
|
|
entries.push(entry);
|
|
}
|
|
}
|
|
}
|
|
InMessage::OfflineMessageList(list) => {
|
|
for part in list.iter() {
|
|
let info = OfflineMessageInfo {
|
|
id: part.message_id,
|
|
from_uid: part.client_uid.as_ref().to_string(),
|
|
subject: part.subject.clone(),
|
|
ts_s: part.timestamp.unix_timestamp(),
|
|
read: part.is_read,
|
|
};
|
|
if let Some(Pending::OfflineList { messages, .. }) =
|
|
self.first_pending(|p| matches!(p, Pending::OfflineList { .. }))
|
|
{
|
|
messages.push(info);
|
|
}
|
|
}
|
|
}
|
|
InMessage::OfflineMessage(list) => {
|
|
for part in list.iter() {
|
|
let m = OfflineMessage {
|
|
id: part.message_id,
|
|
from_uid: part.client_uid.as_ref().to_string(),
|
|
subject: part.subject.clone(),
|
|
text: part.message.clone(),
|
|
ts_s: part.timestamp.unix_timestamp(),
|
|
};
|
|
let id = part.message_id;
|
|
if let Some(Pending::OfflineGet { message, .. }) = self.first_pending(
|
|
|p| matches!(p, Pending::OfflineGet { id: i, .. } if *i == id),
|
|
) {
|
|
*message = Some(m);
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
if let Some(streams) = &self.streams {
|
|
for n in StreamNotification::from_message(msg) {
|
|
streams.send(StreamInput::Notification(n));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The oldest pending command matching `f` (answers come in order).
|
|
fn first_pending(&mut self, f: impl Fn(&Pending) -> bool) -> Option<&mut Pending> {
|
|
let key = self.pending.iter().filter(|(_, p)| f(p)).map(|(h, _)| *h).min_by_key(|h| h.0)?;
|
|
self.pending.get_mut(&key)
|
|
}
|
|
|
|
/// The server answered a command.
|
|
fn answered(&mut self, pending: Pending, result: Result<(), TsError>) {
|
|
let session = self.link.session;
|
|
// An empty list is an empty result, not an error.
|
|
let listed = match result {
|
|
Ok(()) | Err(TsError::DatabaseEmptyResult) => Ok(()),
|
|
Err(e) => Err(e),
|
|
};
|
|
match pending {
|
|
Pending::Stream(request) => {
|
|
if let (Err(e), Some(streams)) = (result, &self.streams) {
|
|
streams.send(StreamInput::RequestFailed(request, e.to_string()));
|
|
}
|
|
}
|
|
Pending::FileList { request, channel, path, entries } => {
|
|
let result = listed.map(|()| entries).map_err(|e| e.to_string());
|
|
self.link.emit(Event::FileList { session, request, channel, path, result });
|
|
}
|
|
Pending::Done(request) => self.link.done(request, result.map_err(|e| e.to_string())),
|
|
Pending::OfflineList { request, messages } => {
|
|
let result = listed.map(|()| messages).map_err(|e| e.to_string());
|
|
self.link.emit(Event::OfflineMessages { session, request, result });
|
|
}
|
|
Pending::OfflineGet { request, id, message } => {
|
|
let result = match (result, message) {
|
|
(Ok(()), Some(m)) => Ok(m),
|
|
(Ok(()), None) => Err(format!("offline message {id} not found")),
|
|
(Err(e), _) => Err(e.to_string()),
|
|
};
|
|
self.link.emit(Event::OfflineMessage { session, request, result });
|
|
}
|
|
Pending::Move { channel } => {
|
|
if let Err(e) = result
|
|
&& let Some(reason) = join_failure(e)
|
|
{
|
|
self.link.emit(Event::JoinFailed { session, channel, reason });
|
|
}
|
|
}
|
|
Pending::Quiet | Pending::MytsIdentity(_) => {}
|
|
Pending::MytsData { avatar, badges, badge_ids } => match result {
|
|
Ok(()) => self.myts_published(avatar, badges, &badge_ids),
|
|
Err(TsError::ParameterInvalid) => warn!(
|
|
"the server refused the account's myTeamSpeak certificate (error 1538): it \
|
|
is expired, revoked or not a myTeamSpeak signing certificate, or the \
|
|
server could not load myTeamSpeak's revocation list"
|
|
),
|
|
Err(e) => warn!(error = %e, "the server refused the account's avatar or badges"),
|
|
},
|
|
Pending::UserTag(value) => match result {
|
|
Ok(()) => {
|
|
let own = self.con.get_state().ok().and_then(|state| {
|
|
state.clients.get(&state.own_client).and_then(|c| c.user_tag.clone())
|
|
});
|
|
if value.is_empty() {
|
|
info!("the server no longer shows a User Tag for the account");
|
|
} else if own.as_deref() == Some(value.as_str()) {
|
|
info!("the server shows the account's User Tag");
|
|
} else {
|
|
warn!("the server took the account's User Tag but shows another value");
|
|
}
|
|
}
|
|
Err(e) => warn!(error = %e, "the server refused the account's User Tag"),
|
|
},
|
|
Pending::Report(what) => {
|
|
if let Err(e) = result {
|
|
let _ = self.events.send(LinkEvent::Error(format!("{what}: {e}")));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What is to be shown of the account on this connection: what the UI
|
|
/// gave, when it is for the myTS ID this connection presents; nothing
|
|
/// without one (signed out).
|
|
fn myts_wanted(&self) -> tsclientlib::MytsData {
|
|
let identity = self.account.identity.borrow();
|
|
let data = self.account.data.borrow();
|
|
match (identity.as_deref(), data.as_deref()) {
|
|
(Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(),
|
|
_ => tsclientlib::MytsData::default(),
|
|
}
|
|
}
|
|
|
|
/// Whether the server knows the User Tag (TeamSpeak 6: it names
|
|
/// `client_user_tag` for our client, protocol 8 on).
|
|
fn has_user_tags(&self) -> bool {
|
|
self.con.get_state().is_ok_and(|state| {
|
|
state.server.protocol_version >= 8
|
|
|| state.clients.get(&state.own_client).is_some_and(|c| c.user_tag.is_some())
|
|
})
|
|
}
|
|
|
|
/// Show the server the account's avatar, badges and User Tag where it
|
|
/// shows something else (`updatemytsdata`, `clientupdate`), or clear
|
|
/// them; `again`: all of it, after a new account proof. While
|
|
/// reconnecting, once connected again.
|
|
fn send_myts_data(&mut self, again: bool) {
|
|
self.myts_data_due = false;
|
|
if self.con.get_state().is_err() {
|
|
self.myts_data_due = true;
|
|
return;
|
|
}
|
|
let mut wanted = self.myts_wanted();
|
|
let user_tags = self.has_user_tags();
|
|
if !user_tags {
|
|
wanted.user_tag = None;
|
|
}
|
|
for update in wanted.updates(&self.myts_shown, again) {
|
|
let shows = |part: &Option<Vec<u8>>| part.as_ref().map(|data| !data.is_empty());
|
|
let (avatar, badges) = (shows(&update.avatar), shows(&update.badges));
|
|
let badge_ids =
|
|
if badges == Some(true) { wanted.badge_ids.clone() } else { Vec::new() };
|
|
info!(
|
|
avatar = ?avatar.map(|shown| if shown { "shown" } else { "cleared" }),
|
|
badges = ?badges.map(|shown| if shown { "shown" } else { "cleared" }),
|
|
?badge_ids,
|
|
"telling the server what to show of the account (updatemytsdata)"
|
|
);
|
|
match self.con.send_myts_update(&update) {
|
|
Ok(handle) => {
|
|
let pending = Pending::MytsData { avatar, badges, badge_ids };
|
|
self.pending.insert(handle, pending);
|
|
}
|
|
Err(tsclientlib::Error::NotConnected) => {
|
|
self.myts_data_due = true;
|
|
return;
|
|
}
|
|
Err(e) => warn!(error = %e, "the account's avatar or badges were not sent"),
|
|
}
|
|
}
|
|
let shown = self.myts_shown.user_tag.as_ref();
|
|
if let Some(value) =
|
|
user_tag_update(wanted.user_tag.as_ref(), shown, user_tags, again, now_ms())
|
|
{
|
|
match &wanted.user_tag {
|
|
Some(tag) if !value.is_empty() => {
|
|
info!(tag = %tag.tag, "setting the account's User Tag")
|
|
}
|
|
_ => info!("clearing the account's User Tag"),
|
|
}
|
|
match self.con.send_user_tag(&value) {
|
|
Ok(handle) => {
|
|
self.pending.insert(handle, Pending::UserTag(value));
|
|
}
|
|
Err(tsclientlib::Error::NotConnected) => {
|
|
self.myts_data_due = true;
|
|
return;
|
|
}
|
|
Err(e) => warn!(error = %e, "the account's User Tag was not sent"),
|
|
}
|
|
}
|
|
self.myts_shown = wanted;
|
|
}
|
|
|
|
/// What the server published of an `updatemytsdata` it took: it says so
|
|
/// for our client before its answer, and shows nothing of what does not
|
|
/// verify, without an error.
|
|
fn myts_published(&self, avatar: Option<bool>, badges: Option<bool>, badge_ids: &[String]) {
|
|
let Ok(state) = self.con.get_state() else { return };
|
|
let Some(own) = state.clients.get(&state.own_client) else { return };
|
|
let has_id = own.my_team_speak_id.as_deref().is_some_and(|id| !id.is_empty());
|
|
let why = if has_id {
|
|
"its signature does not verify with the certificate for the account's myTS ID"
|
|
} else {
|
|
"the server holds no myTS ID for this client (the account proof was not accepted)"
|
|
};
|
|
match avatar {
|
|
Some(true) if own.my_team_speak_avatar.as_deref().is_some_and(|a| !a.is_empty()) => {
|
|
info!("the server shows the account's avatar")
|
|
}
|
|
Some(true) => warn!(why, "the server took the account's avatar but shows none"),
|
|
Some(false) => info!("the server no longer shows an avatar for the account"),
|
|
None => {}
|
|
}
|
|
let published = own.signed_badges.as_deref().unwrap_or_default();
|
|
let dropped = badges_dropped(badge_ids, published);
|
|
match badges {
|
|
Some(true) if published.is_empty() => {
|
|
warn!(why, "the server took the account's badges but shows none")
|
|
}
|
|
Some(true) if dropped.is_empty() => {
|
|
info!(published, "the server shows the account's badges")
|
|
}
|
|
Some(true) => warn!(
|
|
published,
|
|
?dropped,
|
|
"the server shows only some of the account's badges: the others' signatures do \
|
|
not verify for the account's myTS ID"
|
|
),
|
|
Some(false) => info!("the server no longer shows badges for the account"),
|
|
None => {}
|
|
}
|
|
}
|
|
|
|
fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> {
|
|
let handle = cmd.send_with_result(&mut self.con)?;
|
|
self.pending.insert(handle, pending);
|
|
Ok(())
|
|
}
|
|
|
|
/// Send a request of the stream task to the server.
|
|
fn stream_request(&mut self, request: Request) -> anyhow::Result<()> {
|
|
let cmd = request.to_command();
|
|
self.send(cmd, Pending::Stream(request))
|
|
}
|
|
|
|
fn command(&mut self, cmd: LinkCmd) -> anyhow::Result<()> {
|
|
match cmd {
|
|
LinkCmd::SendChat(target, text) => {
|
|
let state = self.con.get_state()?;
|
|
let out = match target {
|
|
ChatTarget::Server => state.server.send_textmessage(&text),
|
|
ChatTarget::Channel(_) => state.send_message(MessageTarget::Channel, &text),
|
|
ChatTarget::Private(uid) => {
|
|
let client = state
|
|
.clients
|
|
.values()
|
|
.find(|c| c.uid.as_ref().is_some_and(|u| u.as_ref().to_string() == uid))
|
|
.ok_or_else(|| {
|
|
anyhow::anyhow!(
|
|
"private message: the client is not on the server \
|
|
(send an offline message instead)"
|
|
)
|
|
})?;
|
|
state.send_message(MessageTarget::Client(client.id), &text)
|
|
}
|
|
};
|
|
self.send(out, Pending::Report("message"))?;
|
|
}
|
|
LinkCmd::Move(channel, password) => {
|
|
let own = self.con.get_state()?.own_client;
|
|
let cpw = encode_password(password.as_deref());
|
|
let cmd =
|
|
c2s::OutClientMoveMessage::new(&mut std::iter::once(c2s::OutClientMovePart {
|
|
client_id: own,
|
|
channel_id: tsclientlib::ChannelId(channel),
|
|
channel_password: (!cpw.is_empty()).then_some(cpw.as_str().into()),
|
|
}));
|
|
self.send(cmd, Pending::Move { channel })?;
|
|
}
|
|
LinkCmd::SetInputMuted(muted) => {
|
|
self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?;
|
|
}
|
|
LinkCmd::SetOutputMuted(muted) => {
|
|
let update = self.con.get_state()?.client_update().set_output_muted(muted);
|
|
update.send(&mut self.con)?;
|
|
}
|
|
LinkCmd::Audio(voice) => self.con.send_audio(out_audio(&voice))?,
|
|
LinkCmd::Stream(cmd) => {
|
|
if let Some(streams) = &self.streams {
|
|
streams.send(cmd);
|
|
}
|
|
}
|
|
LinkCmd::Poke { client, message } => {
|
|
let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once(
|
|
c2s::OutClientPokeRequestPart {
|
|
client_id: tsclientlib::ClientId(client),
|
|
message: poke_message(&message).into(),
|
|
},
|
|
));
|
|
self.send(cmd, Pending::Report("poke"))?;
|
|
}
|
|
LinkCmd::ListFiles { request, dir } => {
|
|
let path = files::normalize_dir(&dir.path);
|
|
let cpw = dir.cpw();
|
|
let cmd = c2s::OutFileListRequestMessage::new(&mut std::iter::once(
|
|
c2s::OutFileListRequestPart {
|
|
channel_id: tsclientlib::ChannelId(dir.channel),
|
|
channel_password: cpw.as_str().into(),
|
|
path: path.as_str().into(),
|
|
},
|
|
));
|
|
let pending =
|
|
Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() };
|
|
self.send(cmd, pending)?;
|
|
}
|
|
LinkCmd::OpenRead { file, offset, reply } => {
|
|
let seek = (offset > 0).then_some(offset);
|
|
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
|
let channel = tsclientlib::ChannelId(file.channel);
|
|
match self.con.download_file(channel, &file.path, password, seek) {
|
|
Ok(handle) => {
|
|
self.jobs.insert(handle, Job::OpenRead(reply));
|
|
}
|
|
Err(e) => {
|
|
let _ = reply.send(Err(e.to_string()));
|
|
}
|
|
}
|
|
}
|
|
LinkCmd::OpenWrite { file, size, overwrite, resume, reply } => {
|
|
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
|
let channel = tsclientlib::ChannelId(file.channel);
|
|
match self.con.upload_file(channel, &file.path, password, size, overwrite, resume) {
|
|
Ok(handle) => {
|
|
self.jobs.insert(handle, Job::OpenWrite(reply));
|
|
}
|
|
Err(e) => {
|
|
let _ = reply.send(Err(e.to_string()));
|
|
}
|
|
}
|
|
}
|
|
// SessionLink copies the bytes itself, over the connections OpenRead and
|
|
// OpenWrite open (`docs/session-seam.md` section 8): this link is never
|
|
// given a transfer to run. One that is given anyway fails (its report
|
|
// is the answer), and the connection, which other things ride on, goes
|
|
// on; there is nothing to cancel.
|
|
LinkCmd::Download { report, .. } | LinkCmd::Upload { report, .. } => {
|
|
report(TransferState::Failed("this link does not run transfers itself".into()));
|
|
}
|
|
LinkCmd::CancelTransfer(id) => debug!(transfer = id, "no transfer runs on this link"),
|
|
LinkCmd::DeleteFiles { request, channel, password, paths } => {
|
|
let cpw = encode_password(password.as_deref());
|
|
let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart {
|
|
channel_id: tsclientlib::ChannelId(channel),
|
|
channel_password: cpw.as_str().into(),
|
|
name: p.as_str().into(),
|
|
});
|
|
let cmd = c2s::OutDeleteFileMessage::new(&mut parts);
|
|
self.send(cmd, request.map_or(Pending::Quiet, Pending::Done))?;
|
|
}
|
|
LinkCmd::RenameFile { request, from, to } => {
|
|
let (cpw, tcpw) = (from.cpw(), to.cpw());
|
|
let other = to.channel != from.channel;
|
|
let cmd =
|
|
c2s::OutRenameFileMessage::new(&mut std::iter::once(c2s::OutRenameFilePart {
|
|
channel_id: tsclientlib::ChannelId(from.channel),
|
|
channel_password: cpw.as_str().into(),
|
|
target_channel_id: other.then_some(tsclientlib::ChannelId(to.channel)),
|
|
target_channel_password: other.then_some(tcpw.as_str().into()),
|
|
old_name: from.path.as_str().into(),
|
|
new_name: to.path.as_str().into(),
|
|
}));
|
|
self.send(cmd, Pending::Done(request))?;
|
|
}
|
|
LinkCmd::CreateDirectory { request, dir } => {
|
|
let cpw = dir.cpw();
|
|
let cmd = c2s::OutCreateDirectoryMessage::new(&mut std::iter::once(
|
|
c2s::OutCreateDirectoryPart {
|
|
channel_id: tsclientlib::ChannelId(dir.channel),
|
|
channel_password: cpw.as_str().into(),
|
|
directory_name: dir.path.as_str().into(),
|
|
},
|
|
));
|
|
self.send(cmd, Pending::Done(request))?;
|
|
}
|
|
LinkCmd::SetAvatarHash { request, hash } => {
|
|
let update = self.con.get_state()?.client_update().set_avatar_hash(&hash);
|
|
let cmd = c2s::OutClientUpdateMessage::new(&mut std::iter::once(update));
|
|
let pending = request.map_or(Pending::Report("avatar"), Pending::Done);
|
|
self.send(cmd, pending)?;
|
|
}
|
|
LinkCmd::OfflineList { request } => {
|
|
let cmd = c2s::OutOfflineMessageListRequestMessage::new();
|
|
self.send(cmd, Pending::OfflineList { request, messages: Vec::new() })?;
|
|
}
|
|
LinkCmd::OfflineGet { request, id } => {
|
|
let cmd = c2s::OutOfflineMessageGetMessage::new(&mut std::iter::once(
|
|
c2s::OutOfflineMessageGetPart { message_id: id },
|
|
));
|
|
self.send(cmd, Pending::OfflineGet { request, id, message: None })?;
|
|
}
|
|
LinkCmd::OfflineAdd { request, to_uid, subject, text } => {
|
|
// The command carries the unique id's bytes (base64 on the wire).
|
|
let bytes = base64::engine::general_purpose::STANDARD
|
|
.decode(to_uid.trim())
|
|
.map_err(|_| anyhow::anyhow!("offline message: invalid unique id {to_uid:?}"));
|
|
let uid = match bytes {
|
|
Ok(bytes) => tsclientlib::UidBuf(bytes),
|
|
Err(e) => {
|
|
self.link.done(request, Err(e.to_string()));
|
|
return Ok(());
|
|
}
|
|
};
|
|
let cmd = c2s::OutOfflineMessageAddMessage::new(&mut std::iter::once(
|
|
c2s::OutOfflineMessageAddPart {
|
|
client_uid: std::borrow::Cow::Borrowed(uid.as_ref()),
|
|
subject: subject.as_str().into(),
|
|
message: text.as_str().into(),
|
|
},
|
|
));
|
|
self.send(cmd, Pending::Done(request))?;
|
|
}
|
|
LinkCmd::OfflineDelete { request, id } => {
|
|
let cmd = c2s::OutOfflineMessageDelMessage::new(&mut std::iter::once(
|
|
c2s::OutOfflineMessageDelPart { message_id: id },
|
|
));
|
|
self.send(cmd, Pending::Done(request))?;
|
|
}
|
|
LinkCmd::OfflineFlag { request, id, read } => {
|
|
let cmd = c2s::OutOfflineMessageUpdateFlagMessage::new(&mut std::iter::once(
|
|
c2s::OutOfflineMessageUpdateFlagPart { message_id: id, is_read: read },
|
|
));
|
|
self.send(cmd, Pending::Done(request))?;
|
|
}
|
|
LinkCmd::Disconnect => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn own_client(&self) -> Option<tsclientlib::ClientId> {
|
|
self.con.get_state().ok().map(|state| state.own_client)
|
|
}
|
|
|
|
fn client_uid(&self, client: &tsclientlib::ClientId) -> Option<String> {
|
|
let state = self.con.get_state().ok()?;
|
|
state.clients.get(client)?.uid.as_ref().map(|u| u.as_ref().to_string())
|
|
}
|
|
|
|
fn own_channel(&self) -> Option<ChannelId> {
|
|
let state = self.con.get_state().ok()?;
|
|
state.clients.get(&state.own_client).map(|c| c.channel.0)
|
|
}
|
|
}
|
|
|
|
/// Why a move into a channel failed, for the user; `None` when there is
|
|
/// nothing to tell (we are in that channel already).
|
|
fn join_failure(error: TsError) -> Option<JoinFailure> {
|
|
let text = match error {
|
|
TsError::ChannelAlreadyIn => return None,
|
|
TsError::ChannelInvalidPassword => return Some(JoinFailure::Password),
|
|
TsError::ChannelMaxclientsReached | TsError::ChannelMaxfamilyReached => {
|
|
return Some(JoinFailure::Full);
|
|
}
|
|
TsError::ChannelInvalidId => "The channel does not exist any more.".to_owned(),
|
|
TsError::PermissionsClientInsufficient | TsError::Permissions => {
|
|
"You are not allowed to join this channel.".to_owned()
|
|
}
|
|
TsError::ClientIsFlooding => "Too many requests: try again in a moment.".to_owned(),
|
|
// The error's name in words (its Display is the name).
|
|
e => format!("The server refused to move you: {}.", error_words(e)),
|
|
};
|
|
Some(JoinFailure::Other(text))
|
|
}
|
|
|
|
/// A poke's message as servers take it: its first [`POKE_MESSAGE_MAX`]
|
|
/// characters (not bytes, so a letter is never cut in half).
|
|
fn poke_message(message: &str) -> &str {
|
|
match message.char_indices().nth(POKE_MESSAGE_MAX) {
|
|
Some((end, _)) => &message[..end],
|
|
None => message,
|
|
}
|
|
}
|
|
|
|
/// A TeamSpeak error's name in lowercase words:
|
|
/// `ChannelIsPrivateChannel` is "channel is private channel".
|
|
fn error_words(error: TsError) -> String {
|
|
let mut words = String::new();
|
|
for c in format!("{error:?}").chars() {
|
|
if c.is_ascii_uppercase() && !words.is_empty() {
|
|
words.push(' ');
|
|
}
|
|
words.push(c.to_ascii_lowercase());
|
|
}
|
|
words
|
|
}
|
|
|
|
/// A failed transfer, for the user.
|
|
fn transfer_error(error: &tsclientlib::Error) -> String {
|
|
match error {
|
|
tsclientlib::Error::CommandError(e) if e.error == TsError::FileNotFound => {
|
|
"file not found".into()
|
|
}
|
|
e => e.to_string(),
|
|
}
|
|
}
|
|
|
|
/// Our voice frame as a TeamSpeak audio packet; the connection assigns its
|
|
/// packet id. This and [`voice_packet`] are the only places that convert
|
|
/// between the audio pipeline's packets and TeamSpeak's.
|
|
fn out_audio(voice: &EncodedVoice) -> OutPacket {
|
|
let codec = match voice.codec {
|
|
VoiceCodec::Voice => CodecType::OpusVoice,
|
|
VoiceCodec::Music => CodecType::OpusMusic,
|
|
};
|
|
OutAudio::new(&AudioData::C2S { id: 0, codec, data: &voice.payload })
|
|
}
|
|
|
|
/// A received TeamSpeak audio packet for the audio thread. `None` for
|
|
/// anything but Opus voice: the jitter buffer cannot play the other codecs
|
|
/// (Speex, CELT), and only server-to-client packets are received.
|
|
fn voice_packet(packet: &InAudioBuf) -> Option<VoicePacket> {
|
|
let (seq, from, codec, data, whisper) = match packet.data().data() {
|
|
AudioData::S2C { id, from, codec, data } => (*id, *from, *codec, *data, false),
|
|
AudioData::S2CWhisper { id, from, codec, data } => (*id, *from, *codec, *data, true),
|
|
_ => return None,
|
|
};
|
|
let codec = match codec {
|
|
CodecType::OpusVoice => VoiceCodec::Voice,
|
|
CodecType::OpusMusic => VoiceCodec::Music,
|
|
other => {
|
|
debug!(codec = ?other, "dropped voice packet: only Opus is supported");
|
|
return None;
|
|
}
|
|
};
|
|
Some(VoicePacket { talker: TalkerId(from), seq, codec, whisper, payload: data.to_vec() })
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod audio_packet_tests {
|
|
use tsproto_packets::packets::Direction;
|
|
|
|
use super::*;
|
|
|
|
fn received(data: AudioData) -> InAudioBuf {
|
|
InAudioBuf::try_new(Direction::S2C, OutAudio::new(&data).into_vec()).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn received_voice_reaches_the_audio_thread_as_a_voice_packet() {
|
|
let packet = received(AudioData::S2C {
|
|
id: 513,
|
|
from: 7,
|
|
codec: CodecType::OpusVoice,
|
|
data: &[1, 2, 3],
|
|
});
|
|
assert_eq!(
|
|
voice_packet(&packet),
|
|
Some(VoicePacket {
|
|
talker: TalkerId(7),
|
|
seq: 513,
|
|
codec: VoiceCodec::Voice,
|
|
whisper: false,
|
|
payload: vec![1, 2, 3],
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn whispers_and_music_are_marked() {
|
|
let packet = received(AudioData::S2CWhisper {
|
|
id: 65_535,
|
|
from: 300,
|
|
codec: CodecType::OpusMusic,
|
|
data: &[9],
|
|
});
|
|
let voice = voice_packet(&packet).unwrap();
|
|
assert_eq!((voice.talker, voice.seq), (TalkerId(300), 65_535));
|
|
assert_eq!(voice.codec, VoiceCodec::Music);
|
|
assert!(voice.whisper);
|
|
}
|
|
|
|
#[test]
|
|
fn the_end_of_a_talk_arrives_empty() {
|
|
let packet =
|
|
received(AudioData::S2C { id: 4, from: 7, codec: CodecType::OpusVoice, data: &[] });
|
|
let voice = voice_packet(&packet).unwrap();
|
|
assert!(voice.payload.is_empty() && voice.is_end());
|
|
}
|
|
|
|
#[test]
|
|
fn codecs_other_than_opus_are_dropped() {
|
|
for codec in [CodecType::SpeexWideband, CodecType::CeltMono] {
|
|
let packet = received(AudioData::S2C { id: 1, from: 7, codec, data: &[1, 2, 3] });
|
|
assert_eq!(voice_packet(&packet), None);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sent_voice_is_a_client_audio_packet() {
|
|
for (codec, wire) in
|
|
[(VoiceCodec::Voice, CodecType::OpusVoice), (VoiceCodec::Music, CodecType::OpusMusic)]
|
|
{
|
|
let voice = EncodedVoice { codec, payload: vec![5, 6, 7] };
|
|
let packet = InAudioBuf::try_new(Direction::C2S, out_audio(&voice).into_vec()).unwrap();
|
|
match packet.data().data() {
|
|
AudioData::C2S { id, codec, data } => {
|
|
// The connection numbers the packets.
|
|
assert_eq!((*id, *codec, *data), (0, wire, &[5u8, 6, 7][..]));
|
|
}
|
|
other => panic!("not a client audio packet: {other:?}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_end_of_our_transmission_is_an_empty_packet() {
|
|
let end = EncodedVoice { codec: VoiceCodec::Voice, payload: Vec::new() };
|
|
// Two bytes of packet id and one of codec, no audio.
|
|
assert_eq!(out_audio(&end).content().len(), 3);
|
|
let voice = EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] };
|
|
assert_eq!(out_audio(&voice).content().len(), 4);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod backend_tests {
|
|
use super::*;
|
|
|
|
/// What a connection tells the engine about the server it reached: the
|
|
/// product and version the UI shows, and the capabilities the old flavor
|
|
/// carried through the event.
|
|
fn told(version: &str) -> (BackendInfo, Capabilities) {
|
|
backend_of(&ServerFlavor::from_version_string(version))
|
|
}
|
|
|
|
#[test]
|
|
fn a_teamspeak_3_server_is_named_with_its_capabilities() {
|
|
let (backend, capabilities) = told("3.13.8 [Build: 1779874471]");
|
|
assert_eq!(
|
|
backend,
|
|
BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() }
|
|
);
|
|
assert_eq!(backend.label(), "TeamSpeak 3 3.13.8");
|
|
assert!(!capabilities.streams && capabilities.raw_query && capabilities.file_transfer);
|
|
}
|
|
|
|
#[test]
|
|
fn a_teamspeak_6_server_is_named_with_its_capabilities() {
|
|
let (backend, capabilities) = told("6.0.0-beta13.1 [Build: 1790080330]");
|
|
assert_eq!(
|
|
backend,
|
|
BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0-beta13.1".into() }
|
|
);
|
|
assert_eq!(backend.label(), "TeamSpeak 6 6.0.0-beta13.1");
|
|
assert!(capabilities.streams && !capabilities.raw_query && capabilities.http_query);
|
|
// The capabilities are the flavor's own.
|
|
assert_eq!(
|
|
capabilities,
|
|
ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1790080330]").capabilities()
|
|
);
|
|
}
|
|
|
|
/// A version nobody recognises names no product: the status line shows
|
|
/// the string as the server sent it, and nothing is switched on.
|
|
#[test]
|
|
fn an_unrecognised_server_keeps_its_version_string_and_no_capabilities() {
|
|
let (backend, capabilities) = told("custom 9");
|
|
assert_eq!(backend, BackendInfo { product: String::new(), version: "custom 9".into() });
|
|
assert_eq!(backend.label(), "custom 9");
|
|
assert_eq!(capabilities, Capabilities::default());
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod join_tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn refused_moves_say_why() {
|
|
assert_eq!(join_failure(TsError::ChannelInvalidPassword), Some(JoinFailure::Password));
|
|
assert_eq!(join_failure(TsError::ChannelMaxclientsReached), Some(JoinFailure::Full));
|
|
assert_eq!(join_failure(TsError::ChannelMaxfamilyReached), Some(JoinFailure::Full));
|
|
// Moving to the channel we are in.
|
|
assert_eq!(join_failure(TsError::ChannelAlreadyIn), None);
|
|
let other = |text: &str| Some(JoinFailure::Other(text.into()));
|
|
assert_eq!(
|
|
join_failure(TsError::PermissionsClientInsufficient),
|
|
other("You are not allowed to join this channel.")
|
|
);
|
|
// The rest in words, not the error's name.
|
|
assert_eq!(
|
|
join_failure(TsError::ChannelIsPrivateChannel),
|
|
other("The server refused to move you: channel is private channel.")
|
|
);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod poke_tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn long_pokes_are_cut_by_characters() {
|
|
assert_eq!(poke_message("hi"), "hi");
|
|
assert_eq!(poke_message(""), "");
|
|
let exact = "x".repeat(POKE_MESSAGE_MAX);
|
|
assert_eq!(poke_message(&exact), exact);
|
|
// Two bytes each: cut after 100 letters, not 100 bytes.
|
|
let long = "ä".repeat(150);
|
|
assert_eq!(poke_message(&long), "ä".repeat(POKE_MESSAGE_MAX));
|
|
assert_eq!(poke_message(&"🙂".repeat(101)).chars().count(), POKE_MESSAGE_MAX);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod account_tests {
|
|
use super::*;
|
|
use tokio::sync::broadcast;
|
|
|
|
#[tokio::test(start_paused = true)]
|
|
async fn account_priority_preserves_ready_network_and_timer_progress() {
|
|
let (account, mut identity) = watch::channel(None);
|
|
let (account_data, mut data) = watch::channel(None);
|
|
let (commands, mut receiver) = mpsc::unbounded_channel();
|
|
let (_requests, mut requests) = mpsc::unbounded_channel();
|
|
for _ in 0..512 {
|
|
commands.send(LinkCmd::SetInputMuted(false)).unwrap();
|
|
}
|
|
let mut stream = futures::stream::poll_fn(|_| {
|
|
std::task::Poll::Ready(Some(Err(tsclientlib::Error::NotConnected)))
|
|
});
|
|
let mut tick = tokio::time::interval(Duration::from_millis(1));
|
|
account.send_replace(None);
|
|
assert!(matches!(
|
|
next_input(
|
|
&mut stream,
|
|
&mut receiver,
|
|
&mut requests,
|
|
&mut tick,
|
|
&mut identity,
|
|
&mut data
|
|
)
|
|
.await,
|
|
Input::MytsIdentityChanged
|
|
));
|
|
identity.borrow_and_update();
|
|
// What is shown of the account changes too, ahead of the rest.
|
|
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
|
|
assert!(matches!(
|
|
next_input(
|
|
&mut stream,
|
|
&mut receiver,
|
|
&mut requests,
|
|
&mut tick,
|
|
&mut identity,
|
|
&mut data
|
|
)
|
|
.await,
|
|
Input::MytsDataChanged
|
|
));
|
|
data.borrow_and_update();
|
|
let (mut network, mut timers, mut audio) = (0, 0, 0);
|
|
for _ in 0..512 {
|
|
tokio::time::advance(Duration::from_millis(1)).await;
|
|
match next_input(
|
|
&mut stream,
|
|
&mut receiver,
|
|
&mut requests,
|
|
&mut tick,
|
|
&mut identity,
|
|
&mut data,
|
|
)
|
|
.await
|
|
{
|
|
Input::Item(_) => network += 1,
|
|
Input::Tick => timers += 1,
|
|
Input::Cmd(_) => audio += 1,
|
|
_ => panic!("unexpected account change"),
|
|
}
|
|
}
|
|
assert!(network > 0 && timers > 0 && audio > 0);
|
|
}
|
|
|
|
fn account_data(myts_id: &[u8]) -> tsclientlib::MytsData {
|
|
let signed = |data: &[u8]| tsclientlib::Signed { certificate: vec![1], data: data.into() };
|
|
tsclientlib::MytsData {
|
|
myts_id: myts_id.to_vec(),
|
|
avatar: signed(b"avatar"),
|
|
badges: signed(b"badges"),
|
|
badge_ids: vec!["b1".into()],
|
|
user_tag: Some(tsclientlib::UserTag {
|
|
tag: "a@myteamspeak.com".into(),
|
|
token: vec![2],
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// The User Tag is set where it is not shown yet, or after a new account
|
|
/// proof, and cleared where it is no longer wanted: on TeamSpeak 6
|
|
/// servers only.
|
|
#[test]
|
|
fn the_user_tag_is_set_where_it_changed() {
|
|
let tag = |tag: &str| tsclientlib::UserTag { tag: tag.into(), token: vec![2] };
|
|
let (a, b) = (tag("a@myteamspeak.com"), tag("b@myteamspeak.com"));
|
|
let update =
|
|
|wanted, shown, user_tags, again| user_tag_update(wanted, shown, user_tags, again, 5);
|
|
let set = Some(a.value(5));
|
|
assert!(set.as_deref().unwrap().starts_with(r#"{"myts_token":"Ag==","tag":"a@"#));
|
|
assert_eq!(update(Some(&a), None, true, false), set);
|
|
assert_eq!(update(Some(&a), Some(&a), true, false), None, "unchanged");
|
|
assert_eq!(update(Some(&a), Some(&a), true, true), set, "after a new account proof");
|
|
assert_eq!(update(Some(&a), Some(&b), true, false), set, "another tag");
|
|
assert_eq!(update(None, Some(&a), true, false).as_deref(), Some(""), "cleared");
|
|
assert_eq!(update(None, Some(&a), true, true).as_deref(), Some(""));
|
|
assert_eq!(update(None, None, true, true), None, "nothing to clear");
|
|
// Not a TeamSpeak 6 server: nothing, set or cleared.
|
|
assert_eq!(update(Some(&a), None, false, true), None);
|
|
assert_eq!(update(None, Some(&a), false, false), None);
|
|
}
|
|
|
|
/// The server publishes the ids of the badges that verified.
|
|
#[test]
|
|
fn badges_the_server_dropped_are_named() {
|
|
let sent: Vec<String> = ["b1", "b2", "b3"].map(String::from).to_vec();
|
|
assert!(badges_dropped(&sent, "b1,b2,b3").is_empty());
|
|
assert!(badges_dropped(&sent, "b3,b1,b2").is_empty());
|
|
assert_eq!(badges_dropped(&sent, "b1,b3"), ["b2"]);
|
|
assert_eq!(badges_dropped(&sent, ""), ["b1", "b2", "b3"]);
|
|
assert!(badges_dropped(&[], "b1").is_empty());
|
|
}
|
|
|
|
/// A voice source that never connects (a silent UDP peer) presenting
|
|
/// the account with myTS ID `[1; 33]`, told to show `data`.
|
|
fn unconnected(server: &tokio::net::UdpSocket, data: tsclientlib::MytsData) -> Voice {
|
|
// Scalar one and the standard compressed Edwards base point.
|
|
let mut private = [0; 32];
|
|
private[0] = 1;
|
|
let mut public = [0x66; 32];
|
|
public[0] = 0x58;
|
|
let identity =
|
|
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
|
|
let (events, _) = broadcast::channel(8);
|
|
let link = LinkCtx {
|
|
session: 1,
|
|
events,
|
|
frames: broadcast::channel(1).0,
|
|
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
|
|
};
|
|
let account = Watches::of(
|
|
watch::channel(Some(Arc::new(identity))).1,
|
|
watch::channel(Some(Arc::new(data))).1,
|
|
);
|
|
Voice {
|
|
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
|
|
link,
|
|
account,
|
|
events: mpsc::unbounded_channel().0,
|
|
server_uid: String::new(),
|
|
talking: HashMap::new(),
|
|
pending: HashMap::new(),
|
|
jobs: HashMap::new(),
|
|
myts_data_due: false,
|
|
myts_shown: tsclientlib::MytsData::default(),
|
|
streams: None,
|
|
streaming_clients: BTreeMap::new(),
|
|
}
|
|
}
|
|
|
|
/// A reconnect (tsclientlib's own) leaves the server without the
|
|
/// account's avatar: it goes again once connected, not before.
|
|
#[tokio::test]
|
|
async fn account_data_waits_for_the_connection() {
|
|
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let mut voice = unconnected(&server, account_data(&[1; 33]));
|
|
voice.send_myts_data(true);
|
|
assert!(voice.myts_data_due && voice.pending.is_empty());
|
|
assert_eq!(voice.myts_shown, tsclientlib::MytsData::default(), "nothing shown yet");
|
|
voice.myts_data_due = false;
|
|
voice.myts_shown = account_data(&[1; 33]);
|
|
let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test");
|
|
voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap();
|
|
assert!(voice.myts_data_due);
|
|
assert_eq!(
|
|
voice.myts_shown,
|
|
tsclientlib::MytsData::default(),
|
|
"a new client shows nothing"
|
|
);
|
|
// Not connected yet: still due.
|
|
let _ = voice.item(StreamItem::BookEvents(Vec::new()));
|
|
assert!(voice.myts_data_due && voice.pending.is_empty());
|
|
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
|
|
}
|
|
|
|
/// Only what is signed for the myTS ID the connection presents is shown.
|
|
#[tokio::test]
|
|
async fn account_data_is_for_the_presented_myts_id() {
|
|
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let voice = unconnected(&server, account_data(&[1; 33]));
|
|
assert_eq!(voice.myts_wanted(), account_data(&[1; 33]));
|
|
let other = unconnected(&server, account_data(&[2; 33]));
|
|
assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default());
|
|
let mut signed_out = unconnected(&server, account_data(&[1; 33]));
|
|
signed_out.account.identity = watch::channel(None).1;
|
|
assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default());
|
|
for voice in [voice, other, signed_out] {
|
|
timeout(Duration::from_millis(100), shutdown_connection(voice.con))
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
}
|
|
|
|
/// `SessionLink` copies the bytes of a transfer itself. A transfer command
|
|
/// that reaches this link anyway fails that transfer with its report, and
|
|
/// not the connection, which every other request of the session rides on.
|
|
#[tokio::test]
|
|
async fn a_transfer_command_fails_the_transfer_and_not_the_connection() {
|
|
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let mut voice = unconnected(&server, account_data(&[1; 33]));
|
|
let states = Arc::new(std::sync::Mutex::new(Vec::new()));
|
|
let report: crate::files::Report = {
|
|
let states = states.clone();
|
|
Arc::new(move |state| states.lock().unwrap().push(state))
|
|
};
|
|
let file = || Remote { channel: 1, password: None, path: "/a".into() };
|
|
let kept = "the connection goes on";
|
|
voice
|
|
.command(LinkCmd::Download {
|
|
transfer: Some(1),
|
|
file: file(),
|
|
sink: crate::files::Sink::Memory,
|
|
report: report.clone(),
|
|
})
|
|
.expect(kept);
|
|
voice
|
|
.command(LinkCmd::Upload {
|
|
transfer: None,
|
|
file: file(),
|
|
from: "a".into(),
|
|
overwrite: false,
|
|
resume: false,
|
|
report,
|
|
})
|
|
.expect(kept);
|
|
// Nothing runs, so there is nothing to cancel and nobody to tell.
|
|
voice.command(LinkCmd::CancelTransfer(1)).expect(kept);
|
|
let failed = TransferState::Failed("this link does not run transfers itself".into());
|
|
assert_eq!(*states.lock().unwrap(), [failed.clone(), failed]);
|
|
assert!(voice.jobs.is_empty() && voice.pending.is_empty());
|
|
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn shutdown_never_polls_a_connecting_connection() {
|
|
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let mut con =
|
|
Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap();
|
|
assert!(matches!(con.update_myts_identity(None), Err(tsclientlib::Error::NotConnected)));
|
|
// tsclientlib returns Ok here despite retaining its Connecting future.
|
|
assert!(con.disconnect(DisconnectOptions::new()).is_ok());
|
|
timeout(Duration::from_millis(100), shutdown_connection(con)).await.unwrap().unwrap();
|
|
let mut packet = [0; 2048];
|
|
assert!(matches!(server.try_recv_from(&mut packet), Err(error)
|
|
if error.kind() == std::io::ErrorKind::WouldBlock));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn account_change_cancels_pending_handshake() {
|
|
// A silent UDP peer keeps the handshake in flight without an external server.
|
|
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let (account, identity) = watch::channel(None);
|
|
let (events, _) = broadcast::channel(8);
|
|
let link = LinkCtx {
|
|
session: 1,
|
|
events,
|
|
frames: broadcast::channel(1).0,
|
|
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
|
|
};
|
|
let watches = Watches::of(identity, watch::channel(None).1);
|
|
let (_commands, commands) = mpsc::unbounded_channel();
|
|
let (events, mut received) = mpsc::unbounded_channel();
|
|
let task = tokio::spawn(run(
|
|
ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"),
|
|
link,
|
|
watches,
|
|
commands,
|
|
events,
|
|
));
|
|
let mut packet = [0; 2048];
|
|
let (_, first) =
|
|
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
|
|
// A logout/clear notification must cancel the old socket and restart.
|
|
account.send_replace(None);
|
|
let second = timeout(Duration::from_secs(5), async {
|
|
loop {
|
|
let (_, peer) = server.recv_from(&mut packet).await.unwrap();
|
|
if peer != first {
|
|
break peer;
|
|
}
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert_ne!(first, second);
|
|
// Losing the account authority fails closed immediately, not after connect timeout.
|
|
drop(account);
|
|
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
|
|
assert!(
|
|
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
|
|
);
|
|
assert!(received.try_recv().is_err());
|
|
}
|
|
}
|