diff --git a/crates/voelin-gateway/src/config.rs b/crates/voelin-gateway/src/config.rs index ad95174..0823be4 100644 --- a/crates/voelin-gateway/src/config.rs +++ b/crates/voelin-gateway/src/config.rs @@ -160,7 +160,7 @@ pub static KEYS: &[KeyDef] = &[ "relay.format", Kind::Str, "\"[{nick}] {text}\"", - "How posts appear in TeamSpeak; {nick} and {text} are replaced", + "How posts appear when the relay cannot take the user's nickname; {nick} and {text} are replaced", ), key( "relay.idle_teardown_secs", diff --git a/crates/voelin-gateway/src/hub.rs b/crates/voelin-gateway/src/hub.rs index d9d9539..5eee64e 100644 --- a/crates/voelin-gateway/src/hub.rs +++ b/crates/voelin-gateway/src/hub.rs @@ -19,8 +19,8 @@ use voelin_gateway_proto::{ Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo, UniqueIds, UserRef, feature, identity_level, verify_auth, }; -use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text}; -use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool}; +use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; +use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as}; use voelin_query::{Command, Connect, QueryClient}; use crate::config::{Bootstrap, Layers, Runtime}; @@ -206,6 +206,8 @@ pub struct Hub { /// Serializes rebuilding the relay pool. relay_rebuild: tokio::sync::Mutex<()>, lookup: QueryClient, + /// One server-chat post at a time: each borrows the poster's nickname. + lookup_posting: tokio::sync::Mutex<()>, perms: PermResolver, groups: GroupResolver, pub db: Db, @@ -268,6 +270,7 @@ impl Hub { relays: RwLock::new(relays), relay_rebuild: Default::default(), lookup, + lookup_posting: Default::default(), perms, groups: GroupResolver::default(), db, @@ -751,16 +754,20 @@ impl Hub { } None => text.to_string(), }; - let full = relay_text(&rt.relay.format, &user.nickname, &relayed); + // Posts go out under the user's nickname; `relay.format` only when the + // session cannot take it. match target { ChatTarget::Server => { - for part in voelin_model::split_message(&full, 1024) { - self.lookup - .send( - &Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part), - ) - .await?; - } + let _posting = self.lookup_posting.lock().await; + post_as( + &self.lookup, + &lookup_nickname(&rt.relay.nickname), + &user.nickname, + &relayed, + &rt.relay.format, + |part| Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part), + ) + .await?; } ChatTarget::Channel(cid) => { if !self.readers.lock().unwrap().contains_key(cid) { @@ -768,8 +775,7 @@ impl Hub { self.add_reader(*cid).await?; self.remove_reader(*cid); } - // The pool's format is `{text}`: `full` is already formatted. - self.relays().send(*cid, &user.nickname, &full).await?; + self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?; } ChatTarget::Private(_) => unreachable!("checked by require_post"), } @@ -797,14 +803,17 @@ impl Hub { fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool { let mut config = RelayConfig::new(connect.clone()); config.nickname = nickname.to_string(); - // Posts are formatted by the hub, with the current settings. - config.format = "{text}".into(); RelayPool::new(config) } +/// The lookup session's own name, given `relay.nickname`. +fn lookup_nickname(nickname: &str) -> String { + format!("{nickname} Gateway") +} + async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) { let _ = lookup - .send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway"))) + .send(&Command::new("clientupdate").arg("client_nickname", lookup_nickname(nickname))) .await; } diff --git a/crates/voelin-gateway/src/tests/fake.rs b/crates/voelin-gateway/src/tests/fake.rs index 51e5dd3..d7e31db 100644 --- a/crates/voelin-gateway/src/tests/fake.rs +++ b/crates/voelin-gateway/src/tests/fake.rs @@ -49,8 +49,12 @@ pub struct State { pub server_groups: HashMap>, /// (target mode, channel of the posting connection, text) pub posted: Vec<(u8, u64, String)>, + /// The nickname of the posting connection, for each of `posted`. + pub posters: Vec, /// Nicknames set with clientupdate. pub nicknames: Vec, + /// The current nickname of each query connection. + names: HashMap, /// Connections that registered for server events (the observer). observers: Vec>, /// Relay connections by channel. @@ -120,6 +124,17 @@ impl FakeServer { self.state.lock().unwrap().posted.clone() } + /// What was posted as `(nickname of the poster, text)`. + pub fn posted_by(&self) -> Vec<(String, String)> { + let s = self.state.lock().unwrap(); + s.posters.iter().cloned().zip(s.posted.iter().map(|p| p.2.clone())).collect() + } + + /// The nickname a query connection has now. + pub fn nickname_of(&self, clid: u16) -> Option { + self.state.lock().unwrap().names.get(&clid).cloned() + } + async fn connection(self, stream: tokio::net::TcpStream) { let (r, mut w) = stream.into_split(); let mut lines = BufReader::new(r).lines(); @@ -192,6 +207,12 @@ impl FakeServer { "whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]), "clientupdate" => { if let Some(nick) = arg("client_nickname") { + let in_use = s.online.iter().any(|c| c.nickname == nick) + || s.names.iter().any(|(id, n)| *id != clid && *n == nick); + if in_use { + return "error id=513 msg=nickname\\sis\\salready\\sin\\suse\n\r".into(); + } + s.names.insert(clid, nick.clone()); s.nicknames.push(nick); } ok @@ -262,6 +283,8 @@ impl FakeServer { "sendtextmessage" => { let mode = num("targetmode") as u8; s.posted.push((mode, *channel, arg("msg").unwrap_or_default())); + let poster = s.names.get(&clid).cloned().unwrap_or_default(); + s.posters.push(poster); ok } _ => ok, diff --git a/crates/voelin-gateway/src/tests/mod.rs b/crates/voelin-gateway/src/tests/mod.rs index e8c5116..cfecbbc 100644 --- a/crates/voelin-gateway/src/tests/mod.rs +++ b/crates/voelin-gateway/src/tests/mod.rs @@ -173,7 +173,11 @@ async fn chat_pins_reactions_topics() { unreachable!() }; assert_eq!((id, message.text.as_str()), (hello.id, "hello")); - assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into()))); + // Under Bob's name: "Bob1", as Bob is online with voice as "Bob". The + // relay takes its own name back after the post. + assert!(fx.fake.posted().contains(&(2, 1, "hello".into()))); + assert!(fx.fake.posted_by().contains(&("Bob1".into(), "hello".into()))); + assert_eq!(fx.fake.state.lock().unwrap().nicknames.last().unwrap(), "Chat Relay 1"); // Pins: moderators only by default; Alice is an admin. assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden); @@ -213,7 +217,7 @@ async fn chat_pins_reactions_topics() { assert_eq!(t.id, topic.id); let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap(); assert_eq!(in_topic.topic_id, Some(topic.id)); - assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into()))); + assert!(fx.fake.posted_by().contains(&("Bob1".into(), "[#Plans] saturday?".into()))); expect( &mut c_rx, "prefixed chat event", @@ -456,7 +460,7 @@ async fn admin_settings_apply_live() { // Feature switches reach connected clients at once. let first = b.post(LOBBY, "one".into(), None).await.unwrap(); - assert!(fx.fake.posted().contains(&(2, 1, " one".into()))); + assert!(fx.fake.posted_by().contains(&("Bob1".into(), "one".into()))); let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap(); assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db); expect( @@ -506,10 +510,22 @@ async fn admin_settings_apply_live() { // 0: no limit. a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap(); - // Relay settings apply without a restart. + // Relay settings apply without a restart. The format is for posts the + // relay cannot make under Bob's name: every variant of it is taken. + for (clid, nick) in [(21, "Bob1"), (22, "Bob2"), (23, "Bob3")] { + fx.fake.add_online(Online { + clid, + cid: 2, + uid: format!("other-{nick}"), + nickname: nick.into(), + server_groups: Vec::new(), + streaming: false, + }); + } a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap(); b.post(LOBBY, "two".into(), None).await.unwrap(); assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into()))); + assert!(fx.fake.posted_by().contains(&("Chat Relay 1".into(), "Bob: two".into()))); a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap(); for _ in 0..100 { if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") { diff --git a/crates/voelin-gateway/tsgw.example.toml b/crates/voelin-gateway/tsgw.example.toml index 4f355a3..9f2cb7a 100644 --- a/crates/voelin-gateway/tsgw.example.toml +++ b/crates/voelin-gateway/tsgw.example.toml @@ -42,6 +42,8 @@ token_ttl_hours = 720 [relay] nickname = "Chat Relay" +# Posts go out under the user's nickname; this form only when the relay +# cannot take it. format = "[{nick}] {text}" idle_teardown_secs = 120 # Each relay is one query connection; stay below the server's per-IP limit. diff --git a/crates/voelin-observer/src/lib.rs b/crates/voelin-observer/src/lib.rs index efe1e70..94e0d7f 100644 --- a/crates/voelin-observer/src/lib.rs +++ b/crates/voelin-observer/src/lib.rs @@ -14,4 +14,4 @@ mod relay; pub use convert::{channel_from_row, client_from_row, delta_from_notification, is_text_message}; pub use observer::{Observer, ObserverConfig, ObserverEvent}; -pub use relay::{RelayConfig, RelayEvent, RelayPool}; +pub use relay::{RelayConfig, RelayEvent, RelayPool, post_as}; diff --git a/crates/voelin-observer/src/relay.rs b/crates/voelin-observer/src/relay.rs index c980869..3aab5cd 100644 --- a/crates/voelin-observer/src/relay.rs +++ b/crates/voelin-observer/src/relay.rs @@ -3,7 +3,7 @@ //! TeamSpeak only delivers channel chat to clients in that channel, and a //! client can only post to its own channel. A relay session is an invisible //! query client moved into the channel; it forwards what is said there and -//! posts messages on behalf of users as `[Nick] text`. +//! posts messages on behalf of users under their own nickname ([`post_as`]). use std::collections::HashMap; use std::sync::Arc; @@ -23,13 +23,17 @@ const ERR_ALREADY_MEMBER: u32 = 770; /// TeamSpeak's limit for one text message. const MAX_MESSAGE_BYTES: usize = 1024; +/// TeamSpeak's limits for a nickname, in characters. +const MIN_NICKNAME_CHARS: usize = 3; +const MAX_NICKNAME_CHARS: usize = 30; #[derive(Clone, Debug)] pub struct RelayConfig { pub connect: Connect, /// Base nickname; the channel id is appended because nicknames are unique. pub nickname: String, - /// How posts appear, with `{nick}` and `{text}` placeholders. + /// How posts appear when the relay cannot take the author's nickname + /// ([`post_as`]), with `{nick}` and `{text}` placeholders. pub format: String, } @@ -49,6 +53,10 @@ pub enum RelayEvent { struct Session { client: QueryClient, + /// The relay's own nickname, taken back after each post. + nickname: String, + /// One post at a time: each borrows the author's nickname. + posting: Arc>, task: JoinHandle<()>, } @@ -92,7 +100,7 @@ impl RelayPool { return Err(voelin_query::Error::Unsupported("relays need a transport with events")); }; let own_id = client.own_client_id().await?; - set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await; + let nickname = set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await; match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await { // Query clients start in the default channel. @@ -104,7 +112,7 @@ impl RelayPool { client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?; info!(channel, own_id, "relay opened"); let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone())); - sessions.insert(channel, Session { client, task }); + sessions.insert(channel, Session { client, nickname, posting: Default::default(), task }); Ok(()) } @@ -126,48 +134,118 @@ impl RelayPool { } } - /// Post `text` in `channel` on behalf of `nick`, opening a relay if needed. + /// Post `text` in `channel` as `nick` wrote it ([`post_as`]), opening a + /// relay if needed. pub async fn send( &self, channel: ChannelId, nick: &str, text: &str, + ) -> voelin_query::Result<()> { + self.post(channel, nick, text, &self.config.format).await + } + + /// [`RelayPool::send`] with another fallback `format` than the pool's. + pub async fn post( + &self, + channel: ChannelId, + nick: &str, + text: &str, + format: &str, ) -> voelin_query::Result<()> { self.open(channel).await?; - let client = match self.sessions.lock().await.get(&channel) { - Some(s) => s.client.clone(), + let (client, nickname, posting) = match self.sessions.lock().await.get(&channel) { + Some(s) => (s.client.clone(), s.nickname.clone(), s.posting.clone()), None => return Err(voelin_query::Error::Closed), }; - let full = relay_text(&self.config.format, nick, text); - for part in split_message(&full, MAX_MESSAGE_BYTES) { - client - .send( - &Command::new("sendtextmessage") - .arg("targetmode", 2) - .arg("target", channel) - .arg("msg", part), - ) - .await?; - } - Ok(()) + let _posting = posting.lock().await; + post_as(&client, &nickname, nick, text, format, |part| { + Command::new("sendtextmessage") + .arg("targetmode", 2) + .arg("target", channel) + .arg("msg", part) + }) + .await } } +/// Post `text` through the query session `client` as if `nick` wrote it: the +/// session takes the nickname for the post (or `nick1`, `nick2`, … while +/// someone has it, as TeamSpeak names a second client of the same name) and +/// goes back to `own_nickname` afterwards, so it never keeps someone's name. +/// When it cannot take any (too short, refused), the post goes out under the +/// session's own name as `format` (`{nick}`, `{text}`). `command` makes the +/// `sendtextmessage` for one part of the text. +/// +/// Callers serialize posts through one session: each borrows a nickname. +pub async fn post_as( + client: &QueryClient, + own_nickname: &str, + nick: &str, + text: &str, + format: &str, + command: impl Fn(String) -> Command, +) -> voelin_query::Result<()> { + let taken = take_nickname(client, nick).await; + let full = if taken { text.to_owned() } else { relay_text(format, nick, text) }; + let mut result = Ok(()); + for part in split_message(&full, MAX_MESSAGE_BYTES) { + result = client.send(&command(part)).await.map(drop); + if result.is_err() { + break; + } + } + if taken && !own_nickname.is_empty() { + set_nickname(client, own_nickname).await; + } + result +} + +/// Name the session `nick` or a numbered variant; whether it did. +async fn take_nickname(client: &QueryClient, nick: &str) -> bool { + for nickname in author_nicknames(nick) { + match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await { + Ok(_) => return true, + Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue, + Err(e) => { + debug!(%e, "could not take the author's nickname"); + return false; + } + } + } + false +} + +/// The names a post by `nick` may go out under, in order: the nickname +/// itself, then `nick1` to `nick3`, each within TeamSpeak's length limits. +fn author_nicknames(nick: &str) -> Vec { + let nick = nick.trim(); + if nick.chars().count() < MIN_NICKNAME_CHARS { + return Vec::new(); + } + let fit = |suffix: &str| { + let head: String = nick.chars().take(MAX_NICKNAME_CHARS - suffix.len()).collect(); + format!("{}{suffix}", head.trim_end()) + }; + std::iter::once(fit("")).chain((1..=3).map(|n| fit(&n.to_string()))).collect() +} + /// Nicknames are unique per server; try a few numbered variants. The name is -/// cosmetic, so failing keeps the server-assigned one. -async fn set_nickname(client: &QueryClient, base: &str) { +/// cosmetic, so failing keeps the server-assigned one. The name it got. +async fn set_nickname(client: &QueryClient, base: &str) -> String { for attempt in 1..=5 { let nickname = if attempt == 1 { base.to_string() } else { format!("{base} ({attempt})") }; match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await { - Ok(_) => return, + Ok(_) => return nickname, Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue, Err(e) => { warn!(%e, %nickname, "could not set relay nickname"); - return; + return base.to_owned(); } } } warn!(base, "all relay nicknames in use"); + base.to_owned() } async fn forward( @@ -193,3 +271,22 @@ async fn forward( } let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn posts_go_out_under_the_authors_name_then_numbered_variants() { + assert_eq!(author_nicknames(" Alice "), ["Alice", "Alice1", "Alice2", "Alice3"]); + // Too short for TeamSpeak: the relay's own name and the format. + assert!(author_nicknames("Al").is_empty()); + let long = "x".repeat(40); + let names = author_nicknames(&long); + assert_eq!(names[0], "x".repeat(30)); + assert_eq!(names[1], format!("{}1", "x".repeat(29))); + assert!(names.iter().all(|n| n.chars().count() <= MAX_NICKNAME_CHARS)); + // Characters, not bytes. + assert_eq!(author_nicknames(&"é".repeat(31))[0].chars().count(), 30); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index c03a91c..bb2f601 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -41,7 +41,7 @@ the admin grants them to the guest query group. | Feature | Mechanism | |---|---| | Server chat | Voice connection: `targetmode=3`. Without one: gateway or own query session (`servernotifyregister event=textserver`) | -| Channel chat without joining | Relay pool (`voelin-observer`): invisible query sessions sit in channels and relay both ways; posts appear as `[Nick] text` | +| Channel chat without joining | Relay pool (`voelin-observer`): invisible query sessions sit in channels and relay both ways; posts appear under the author's nickname | | Chat history | Every message a session sees is stored on the device (`voelin-store`); a gateway's stored history fills in what the device missed (sync by revision, paging by time) | | Pins, reactions, topics, events, stream directory, activity | Gateway features (`tsgw`), driven through `Command::Gateway` / `Event::Gateway` | | Voice | tsproto UDP transport, Opus (`opus2`), echo cancellation / noise suppression (sonora), own jitter buffer, cpal / AAudio | diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index 5738d28..2c545d1 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -15,7 +15,7 @@ appear in the channel as `[#topic] text`). | Feature | How | |---|---| | Presence | One query session watches the server; each user sees the channels their `i_channel_subscribe_power` allows, without query clients | -| Channel chat | A relay query session is moved into each channel someone opened; it forwards what is said and posts users' messages as `[Nick] text` | +| Channel chat | A relay query session is moved into each channel someone opened; it forwards what is said and posts users' messages under their own nickname, as if they wrote them | | Server chat | Read by the watcher, posted by the gateway's lookup session | | History | Relayed messages are stored (SQLite) with stable ids; pages by id or time in both directions, without a size limit unless you set one; `sync` returns what changed since a revision | | Pins | Pinned messages per chat, kept even when older messages are pruned | @@ -26,7 +26,13 @@ appear in the channel as `[#topic] text`). | Activity feed | Streams started and stopped, events scheduled, starting or cancelled, topics started, messages pinned | The nickname in relayed posts is the one the server has on record for the -user's identity (from `clientdbinfo`), not something the user can choose. +user's identity (from `clientdbinfo`), not something the user can choose. For +each post the relay (or, for server chat, the lookup session) takes that +nickname, sends the message and takes its own name back; while someone on the +server has the nickname it uses `Nick1` to `Nick3`, as TeamSpeak names a second +client of the same name. Only when it can take none of them (a nickname under +three characters, the server refusing the change) does the post go out under +the relay's own name, as `relay.format` (`[Nick] text`). Each feature can be turned off (`features.*`); pins, reactions and topics need `history.enabled`. @@ -187,9 +193,9 @@ docker run -v $PWD/tsgw.toml:/etc/tsgw/tsgw.toml -e TSGW_QUERY_PASSWORD=… -p 7 Query clients are not hidden by the server; official clients hide them from users whose `i_client_serverquery_view_power` is below the query client's needed view power (100 by default). Server Admins, and third-party clients -that ignore the rule, see the gateway's sessions. Relayed channels show the -relay's posts under its own nickname (`Chat Relay `), so people in the -channel can tell the messages come through the gateway. +that ignore the rule, see the gateway's sessions. Relayed posts show the +user's nickname, like a message the user wrote in TeamSpeak; whoever can see +query clients sees that it came from a query session. ## Configuration @@ -241,7 +247,7 @@ you set here. | `auth.min_security_level` | `0` | On top of the server's own requirement | | `auth.token_ttl_hours` | `720` | Lifetime of login tokens | | `relay.nickname` | `"Chat Relay"` | Relay sessions are named ` `, the lookup session ` Gateway` | -| `relay.format` | `"[{nick}] {text}"` | How posts appear in TeamSpeak | +| `relay.format` | `"[{nick}] {text}"` | How posts appear when the relay cannot take the user's nickname | | `relay.idle_teardown_secs` | `120` | Close a relay this long after its last reader left | | `relay.max_channel_relays` | `6` | Concurrent relays (0: no limit) | | `relay.pinned_channels` | `[]` | Always relayed, so their history is complete |