Files
VoelinClient/crates/voelin-gateway/src/hub.rs
T
Claude 79a12654c8 myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed
Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
  from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
  ID), the signed badges from getSignedBadges and the User Tag's token from
  /tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
  (block types 4-7, leaf type 6, validity, key from the root, cofactorless
  Ed25519); each part is sent with a certificate that verifies it, in
  separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
  ({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
  self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
  three badges to show. The log says what the server published.

Banners:
- The URL (without query) is logged on the first failure; stalls, connect
  failures and missing answers are named; 400/404/410 are retried after
  15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
  downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
  are used, SOCKS included; redirects are followed hop by hop.

Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
  30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
  restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
  losses and the first presence.

tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
  terminal) and lifecycle logs: startup summary, the address the server
  sees for queries, WebSocket connections, logins, refusals, slow requests,
  ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
  connects time out after 10 s; a silent server cannot wedge a connection;
  SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
  counted, every connection holds on a 524).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-06 18:28:09 +00:00

936 lines
28 KiB
Rust

//! State shared by all sessions: one observer, one relay pool, one query
//! session for lookups, storage, runtime settings and fan-out of events.
//!
//! The chat features (pins, reactions, topics), events and the activity
//! feed are in `features.rs`, the stream directory in `streams.rs`, the
//! background tasks in `tasks.rs`.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
use anyhow::{Context, Result};
use base64::prelude::*;
use rand::RngExt;
use sha2::{Digest, Sha256};
use tokio::sync::broadcast;
use tracing::{info, warn};
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};
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
use voelin_query::{Command, Connect};
use crate::config::{Layers, Runtime};
use crate::db::{Db, TokenInfo};
use crate::lookup::Lookup;
use crate::perms::{
ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective,
granted, rule_allows,
};
use crate::settings::Settings;
use crate::streams::Directory;
pub fn now_secs() -> i64 {
now_ms() / 1000
}
pub fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
/// A logged-in user.
#[derive(Clone, Debug)]
pub struct User {
pub uid: String,
pub cldbid: u64,
/// Last nickname the server saw; used in relayed posts (not user-chosen,
/// so nobody can post under someone else's name).
pub nickname: String,
/// Effective `i_channel_subscribe_power`, used to filter presence.
pub subscribe_power: i64,
}
impl User {
pub fn user_ref(&self) -> UserRef {
UserRef { uid: self.uid.clone(), name: self.nickname.clone() }
}
}
/// An error to send to the client.
#[derive(Debug)]
pub struct Denied(pub ErrorCode, pub String);
impl Denied {
pub fn new(code: ErrorCode, msg: impl Into<String>) -> Self {
Self(code, msg.into())
}
pub fn forbidden(msg: impl Into<String>) -> Self {
Self::new(ErrorCode::Forbidden, msg)
}
pub fn not_found(what: &str) -> Self {
Self::new(ErrorCode::NotFound, format!("no such {what}"))
}
pub fn bad(msg: impl Into<String>) -> Self {
Self::new(ErrorCode::BadRequest, msg)
}
pub fn quota(msg: impl Into<String>) -> Self {
Self::new(ErrorCode::QuotaExceeded, msg)
}
}
impl From<voelin_query::Error> for Denied {
fn from(e: voelin_query::Error) -> Self {
Denied::new(ErrorCode::Unavailable, e.to_string())
}
}
impl From<rusqlite::Error> for Denied {
fn from(e: rusqlite::Error) -> Self {
warn!(error = %e, "database error");
Denied::new(ErrorCode::Internal, "database error")
}
}
/// Something sessions may want to forward; each session filters by what it
/// opened, subscribed to and may see.
#[derive(Clone, Debug)]
pub enum HubEvent {
Chat(HistoryEntry),
Pinned(PinInfo),
Unpinned {
target: ChatTarget,
message_id: i64,
by: UserRef,
},
Reaction {
target: ChatTarget,
message_id: i64,
emoji: String,
user: UserRef,
added: bool,
count: u32,
},
Topic(TopicInfo),
Event(EventInfo),
EventDeleted {
id: i64,
channel: Option<ChannelId>,
},
Reminder {
event: EventInfo,
starts_in_ms: i64,
},
StreamStarted(StreamEntry),
StreamUpdated(StreamEntry),
StreamEnded {
id: String,
channel: Option<ChannelId>,
reason: String,
},
Activity(ActivityEntry),
/// Features changed; sessions recompute their capabilities.
Capabilities,
}
/// Optional features, for [`Hub::feature_enabled`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Feature {
History,
Pins,
Reactions,
Topics,
Events,
Streams,
Activity,
}
impl Feature {
pub fn name(self) -> &'static str {
match self {
Feature::History => feature::HISTORY,
Feature::Pins => feature::PINS,
Feature::Reactions => feature::REACTIONS,
Feature::Topics => feature::TOPICS,
Feature::Events => feature::EVENTS,
Feature::Streams => feature::STREAMS,
Feature::Activity => feature::ACTIVITY,
}
}
pub fn enabled(self, rt: &Runtime) -> bool {
let f = &rt.features;
match self {
Feature::History => rt.history.enabled,
// These live on stored messages.
Feature::Pins => rt.history.enabled && f.pins,
Feature::Reactions => rt.history.enabled && f.reactions,
Feature::Topics => rt.history.enabled && f.topics,
Feature::Events => f.events,
Feature::Streams => f.streams,
Feature::Activity => f.activity,
}
}
pub const ALL: [Feature; 7] = [
Feature::History,
Feature::Pins,
Feature::Reactions,
Feature::Topics,
Feature::Events,
Feature::Streams,
Feature::Activity,
];
}
pub struct Hub {
pub settings: Settings,
pub gateway_id: String,
pub server_uid: String,
pub server_name: String,
pub is_ts6: bool,
needed_level: u8,
default_channel: ChannelId,
pub observer: Observer,
connect: Connect,
relays: RwLock<RelayPool>,
/// Serializes rebuilding the relay pool.
relay_rebuild: tokio::sync::Mutex<()>,
pub(crate) lookup: Arc<Lookup>,
/// 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,
events: broadcast::Sender<Arc<HubEvent>>,
/// Readers per relayed channel, and when the last one left.
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
/// Message ids while history is off.
next_message_id: Mutex<i64>,
pub(crate) directory: Mutex<Directory>,
}
impl Hub {
/// Connect to the server, open the database and start the background
/// tasks. Waits for the TeamSpeak server as long as it takes.
pub async fn start(layers: Layers) -> Result<Arc<Self>> {
let started = Instant::now();
let boot = layers.bootstrap()?;
let db = Db::open(&boot.db_path)
.with_context(|| format!("failed to open {}", boot.db_path.display()))?;
let settings = Settings::new(layers, &db)?;
let rt = settings.current();
// Clones share the count of commands for the flood protection.
let connect = boot.query_connect();
let lookup = Lookup::open(connect.clone(), lookup_nickname(&rt.relay.nickname)).await;
lookup.log_address(boot.allowlisted).await;
let server = ServerFacts::load_until_it_works(&lookup, &connect).await;
let perms = PermResolver::new(server.perm_ids);
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = new_relay_pool(&connect, &rt.relay.nickname);
let directory = Directory::load(&db);
info!(
server_name = %server.name,
server_uid = %server.uid,
version = %server.version,
is_ts6 = server.is_ts6,
default_channel = server.default_channel,
needed_level = server.needed_level,
elapsed_ms = started.elapsed().as_millis() as u64,
"gateway connected to server"
);
let hub = Arc::new(Self {
gateway_id: boot.gateway_id(),
settings,
server_uid: server.uid,
server_name: server.name,
is_ts6: server.is_ts6,
needed_level: server.needed_level,
default_channel: server.default_channel,
observer,
connect,
relays: RwLock::new(relays),
relay_rebuild: Default::default(),
lookup,
lookup_posting: Default::default(),
perms,
groups: GroupResolver::default(),
db,
events: broadcast::channel(4096).0,
readers: Default::default(),
next_message_id: Mutex::new(0),
directory: Mutex::new(directory),
});
crate::tasks::spawn_all(&hub);
// Apps may log in meanwhile.
for &cid in &rt.relay.pinned_channels {
hub.open_relay_soon(cid);
}
Ok(hub)
}
pub fn runtime(&self) -> Arc<Runtime> {
self.settings.current()
}
pub fn subscribe(&self) -> broadcast::Receiver<Arc<HubEvent>> {
self.events.subscribe()
}
pub fn emit(&self, event: HubEvent) {
let _ = self.events.send(Arc::new(event));
}
pub fn relays(&self) -> RelayPool {
self.relays.read().unwrap().clone()
}
pub(crate) fn is_own_client(&self, id: u16) -> bool {
self.lookup.is_own(id)
}
/// Features for the `hello` message.
pub fn capabilities(&self) -> Vec<String> {
let rt = self.runtime();
let mut caps = vec![feature::PRESENCE.to_string(), feature::RELAY.to_string()];
caps.extend(
Feature::ALL.into_iter().filter(|f| f.enabled(&rt)).map(|f| f.name().to_string()),
);
caps
}
/// Features for one user: [`Hub::capabilities`] plus `admin`.
pub async fn user_capabilities(&self, user: &User) -> Vec<String> {
let mut caps = self.capabilities();
if self.is_admin(user).await.unwrap_or(false) {
caps.push(feature::ADMIN.to_string());
}
caps
}
pub fn feature_enabled(&self, feature: Feature) -> bool {
feature.enabled(&self.runtime())
}
/// Fail with `feature_disabled` unless the feature is on.
pub fn require(&self, feature: Feature) -> Result<(), Denied> {
if self.feature_enabled(feature) {
Ok(())
} else {
Err(Denied::new(
ErrorCode::FeatureDisabled,
format!("{} is turned off on this gateway", feature.name()),
))
}
}
/// Rebuild the relay pool, e.g. for a new nickname; open relays move over.
pub(crate) async fn rebuild_relays(self: &Arc<Self>, nickname: &str) {
let _guard = self.relay_rebuild.lock().await;
let pool = new_relay_pool(&self.connect, nickname);
tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe()));
let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool);
// Also the relays being opened now, which open no more in the old pool.
let channels = old.close_all().await;
drop(old);
self.lookup.set_nickname(&lookup_nickname(nickname)).await;
let pool = self.relays();
for cid in channels {
// A failure is logged by the pool.
if pool.open(cid).await.is_err() && self.relay_wanted(cid) {
let hub = self.clone();
tokio::spawn(async move { hub.reopen_relay(cid).await });
}
}
info!(nickname, "relays renamed");
}
/// Open a channel's relay in the background, and while that fails, again
/// for as long as it is wanted ([`Hub::reopen_relay`]).
fn open_relay_soon(self: &Arc<Self>, cid: ChannelId) {
let hub = self.clone();
tokio::spawn(async move {
// A failure is logged by the pool.
if hub.relays().open(cid).await.is_err() {
hub.reopen_relay(cid).await;
}
});
}
/// Pinned channels changed: open new ones, let removed ones idle out.
pub(crate) fn apply_pinned_channels(self: &Arc<Self>, old: &[u64], new: &[u64]) {
for cid in new.iter().filter(|c| !old.contains(c)) {
self.open_relay_soon(*cid);
}
for cid in old.iter().filter(|c| !new.contains(c)) {
// The idle teardown closes it once nobody reads it.
self.readers.lock().unwrap().entry(*cid).or_insert((0, Instant::now()));
}
}
/// Someone reads the channel, or it is pinned.
pub(crate) fn relay_wanted(&self, cid: ChannelId) -> bool {
self.runtime().relay.pinned_channels.contains(&cid)
|| self.readers.lock().unwrap().get(&cid).is_some_and(|(n, _)| *n > 0)
}
/// Open a relay the server dropped again, waiting longer after each
/// failure, for as long as it is wanted.
pub(crate) async fn reopen_relay(&self, cid: ChannelId) {
let mut attempt = 0;
while self.relay_wanted(cid) {
attempt += 1;
tokio::time::sleep(self.connect.retry_delay(attempt)).await;
// A failure is logged by the pool.
if self.relays().open(cid).await.is_ok() {
info!(channel = cid, attempt, "relay reopened");
return;
}
}
}
/// Channels whose relay nobody needs any more.
pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec<ChannelId> {
let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs);
let mut readers = self.readers.lock().unwrap();
let channels: Vec<ChannelId> = readers
.iter()
.filter(|(cid, (n, since))| {
*n == 0 && since.elapsed() >= idle && !rt.relay.pinned_channels.contains(cid)
})
.map(|(cid, _)| *cid)
.collect();
for cid in &channels {
readers.remove(cid);
}
channels
}
// Authentication
/// Verify a signed challenge and look the identity up on the server.
pub async fn authenticate(
&self,
omega: &str,
key_offset: u64,
ts: i64,
signature: &str,
nonce: &str,
) -> Result<(User, String, i64), Denied> {
let ids: UniqueIds = verify_auth(
omega,
signature,
&self.gateway_id,
&self.server_uid,
nonce,
ts,
now_secs(),
)
.map_err(|e| Denied::new(ErrorCode::AuthFailed, e.to_string()))?;
let uid = ids.for_server(self.is_ts6).to_string();
let needed = self.needed_level.max(self.runtime().auth.min_security_level);
let level = identity_level(omega, key_offset);
if level < needed {
return Err(Denied::new(
ErrorCode::LevelTooLow,
format!("identity level {level}, server needs {needed}"),
));
}
let user = self.lookup_user(&uid).await?;
let (token, expires) = self.issue_token(&user)?;
self.audit(Some(&user.uid), "login", "signature");
Ok((user, token, expires))
}
/// Log in with a token from an earlier login.
pub async fn resume(&self, token: &str) -> Result<(User, String, i64), Denied> {
let info = self
.db
.token(&hash_token(token), now_secs())?
.ok_or_else(|| Denied::new(ErrorCode::AuthFailed, "unknown or expired token"))?;
let user = self.lookup_user(&info.uid).await?;
self.audit(Some(&user.uid), "login", "token");
Ok((user, token.to_string(), info.expires))
}
fn issue_token(&self, user: &User) -> Result<(String, i64), Denied> {
let bytes: [u8; 32] = rand::rng().random();
let token = BASE64_URL_SAFE_NO_PAD.encode(bytes);
let expires = now_secs() + self.runtime().auth.token_ttl_hours as i64 * 3600;
self.db.add_token(
&hash_token(&token),
&TokenInfo { uid: user.uid.clone(), cldbid: user.cldbid, expires },
)?;
Ok((token, expires))
}
async fn lookup_user(&self, uid: &str) -> Result<User, Denied> {
let rt = self.runtime();
if rt.auth.deny_uids.iter().any(|d| d == uid) {
return Err(Denied::forbidden("not allowed on this gateway"));
}
let bans = self.lookup.send(&Command::new("banlist")).await.unwrap_or_default();
if bans.iter().any(|b| b.get("uid") == Some(uid)) {
return Err(Denied::new(ErrorCode::Banned, "banned on this server"));
}
let found =
self.lookup.send(&Command::new("clientdbfind").arg("pattern", uid).flag("uid")).await?;
let cldbid: u64 = found.first().and_then(|r| r.parse("cldbid")).ok_or_else(|| {
Denied::new(ErrorCode::UnknownIdentity, "connect to the server with voice once first")
})?;
let info = self.lookup.send(&Command::new("clientdbinfo").arg("cldbid", cldbid)).await?;
let nickname =
info.first().and_then(|r| r.get("client_nickname")).unwrap_or("unknown").to_string();
if !rt.auth.require_server_groups.is_empty() {
let groups = self.groups.server_groups(&self.lookup, cldbid).await?;
if !groups.iter().any(|g| rt.auth.require_server_groups.contains(g)) {
return Err(Denied::forbidden("missing required server group"));
}
}
let entries = self.perms.entries(&self.lookup, cldbid, self.default_channel).await?;
let subscribe_power = effective(&entries, self.perms.ids.subscribe_power);
Ok(User { uid: uid.to_string(), cldbid, nickname, subscribe_power })
}
// Authorization
pub async fn channel_access(
&self,
user: &User,
cid: ChannelId,
) -> Result<ChannelAccess, Denied> {
let has_password = {
let presence = self.observer.presence();
let presence = presence.read().unwrap();
let Some(channel) = presence.channels.get(&cid) else {
return Err(Denied::bad(format!("no channel {cid}")));
};
if channel.needed_subscribe_power as i64 > user.subscribe_power {
return Ok(ChannelAccess { read: false, post: false });
}
channel.has_password
};
let entries = self.perms.entries(&self.lookup, user.cldbid, cid).await?;
Ok(channel_access(&entries, &self.perms.ids, has_password))
}
pub async fn can_post_server_chat(&self, user: &User) -> Result<bool, Denied> {
let entries = self.perms.entries(&self.lookup, user.cldbid, self.default_channel).await?;
Ok(effective(&entries, self.perms.ids.server_text_send) > 0)
}
/// Whether the user may see a channel at all (presence filter).
pub fn channel_visible(&self, user: &User, cid: ChannelId) -> bool {
let presence = self.observer.presence();
let p = presence.read().unwrap();
p.channels
.get(&cid)
.is_some_and(|c| c.needed_subscribe_power as i64 <= user.subscribe_power)
}
/// The user may read `target`.
pub async fn require_read(&self, user: &User, target: &ChatTarget) -> Result<(), Denied> {
match target {
ChatTarget::Server => Ok(()),
ChatTarget::Channel(cid) => {
if self.channel_access(user, *cid).await?.read {
Ok(())
} else {
Err(Denied::forbidden("no access to this channel"))
}
}
ChatTarget::Private(_) => Err(Denied::bad("private chat is not relayed")),
}
}
/// The user may write in `target`.
pub async fn require_post(&self, user: &User, target: &ChatTarget) -> Result<(), Denied> {
let allowed = match target {
ChatTarget::Server => self.can_post_server_chat(user).await?,
ChatTarget::Channel(cid) => self.channel_access(user, *cid).await?.post,
ChatTarget::Private(_) => return Err(Denied::bad("private chat is not relayed")),
};
if allowed { Ok(()) } else { Err(Denied::forbidden("no permission to post here")) }
}
async fn user_groups(
&self,
user: &User,
channel: Option<ChannelId>,
) -> Result<UserGroups, Denied> {
let online = {
let presence = self.observer.presence();
let p = presence.read().unwrap();
p.clients
.values()
.find(|c| {
c.uid.as_deref() == Some(user.uid.as_str()) && !c.server_groups.is_empty()
})
.map(|c| c.server_groups.clone())
};
let server = match online {
Some(groups) => groups,
None => self.groups.server_groups(&self.lookup, user.cldbid).await?,
};
let channel = match channel {
Some(cid) => self.groups.channel_groups(&self.lookup, user.cldbid, cid).await?,
None => Vec::new(),
};
Ok(UserGroups { server, channel })
}
async fn rule_allows(
&self,
user: &User,
action: Action,
channel: Option<ChannelId>,
) -> Result<Option<bool>, Denied> {
let rt = self.runtime();
let Some(rule) = rt.perm.get(action) else { return Ok(None) };
let needs_channel = !rule.channel_groups.is_empty() && !rule.everyone;
let groups = self.user_groups(user, channel.filter(|_| needs_channel)).await?;
Ok(Some(rule_allows(rule, &groups)))
}
pub async fn is_admin(&self, user: &User) -> Result<bool, Denied> {
if let Some(allowed) = self.rule_allows(user, Action::Admin, None).await? {
return Ok(allowed);
}
let entries = self.perms.entries(&self.lookup, user.cldbid, self.default_channel).await?;
Ok(granted(&entries, self.perms.ids.server_modify_name))
}
/// Whether a rule (or the action's default) lets the user act, server-wide
/// or in `channel`. Access to the chat itself is checked separately.
pub async fn allowed(
&self,
user: &User,
action: Action,
channel: Option<ChannelId>,
) -> Result<bool, Denied> {
if action == Action::Unknown {
return Ok(false);
}
if self.is_admin(user).await? {
return Ok(true);
}
if action == Action::Admin {
return Ok(false);
}
if action == Action::Pin && Box::pin(self.allowed(user, Action::Moderate, channel)).await? {
return Ok(true);
}
if let Some(allowed) = self.rule_allows(user, action, channel).await? {
return Ok(allowed);
}
Ok(match action {
Action::React | Action::CreateTopic | Action::Rsvp | Action::Stream => true,
Action::CreateEvent => match channel {
Some(cid) => self.channel_access(user, cid).await?.post,
None => self.can_post_server_chat(user).await?,
},
Action::Moderate => match channel {
Some(cid) => {
let entries = self.perms.entries(&self.lookup, user.cldbid, cid).await?;
granted(&entries, self.perms.ids.channel_modify_name)
}
None => false,
},
// Moderators, handled above.
Action::Pin => false,
Action::Admin | Action::Unknown => false,
})
}
pub async fn require_allowed(
&self,
user: &User,
action: Action,
channel: Option<ChannelId>,
) -> Result<(), Denied> {
if self.allowed(user, action, channel).await? {
Ok(())
} else {
Err(Denied::forbidden(format!("not allowed to {}", action.as_str().replace('_', " "))))
}
}
/// Presence as this user may see it: channels within their subscribe
/// power, no query clients.
pub fn filtered_presence(&self, user: &User) -> Presence {
let presence = self.observer.presence();
let p = presence.read().unwrap();
let channels: std::collections::BTreeMap<_, _> = p
.channels
.iter()
.filter(|(_, c)| c.needed_subscribe_power as i64 <= user.subscribe_power)
.map(|(id, c)| (*id, c.clone()))
.collect();
let clients = p
.clients
.iter()
.filter(|(_, c)| !c.is_query && channels.contains_key(&c.channel))
.map(|(id, c)| (*id, c.clone()))
.collect();
Presence { server_name: p.server_name.clone(), channels, clients, ..Presence::default() }
}
// Chat
/// Store (if history is on) and fan out a message.
pub fn publish(&self, msg: ChatMessage, topic_id: Option<i64>) -> HistoryEntry {
let entry = if self.runtime().history.enabled {
self.db.add_message(msg.clone(), topic_id).unwrap_or_else(|error| {
warn!(%error, "failed to store message");
HistoryEntry { topic_id, ..HistoryEntry::new(-1, msg) }
})
} else {
let mut next = self.next_message_id.lock().unwrap();
*next += 1;
HistoryEntry { topic_id, ..HistoryEntry::new(*next, msg) }
};
if let Some(topic) = topic_id.and_then(|t| self.db.topic(t).ok().flatten()) {
self.emit(HubEvent::Topic(topic));
}
self.emit(HubEvent::Chat(entry.clone()));
entry
}
/// A message seen in TeamSpeak. Posts in the topic format (from official
/// clients) join that topic.
pub(crate) fn publish_incoming(&self, mut msg: ChatMessage) {
let mut topic_id = None;
if self.feature_enabled(Feature::Topics)
&& let Some((title, text)) =
parse_topic_post(&self.runtime().topics.relay_format, &msg.text)
&& let Ok(Some(topic)) = self.db.topic_by_title(&msg.target, title)
{
topic_id = Some(topic.id);
msg.text = text.to_string();
}
self.publish(msg, topic_id);
}
/// Start reading a channel for one more session.
pub async fn add_reader(&self, cid: ChannelId) -> Result<(), Denied> {
let max = self.runtime().relay.max_channel_relays as usize;
{
let readers = self.readers.lock().unwrap();
if max > 0 && !readers.contains_key(&cid) && readers.len() >= max {
return Err(Denied::new(
ErrorCode::Unavailable,
"too many relayed channels, try later",
));
}
}
loop {
let pool = self.relays();
match pool.open(cid).await {
// Replaced on the way (a new nickname): open in the new pool.
Err(_) if pool.is_closed() => continue,
result => result?,
}
break;
}
self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1;
Ok(())
}
pub fn remove_reader(&self, cid: ChannelId) {
if let Some(entry) = self.readers.lock().unwrap().get_mut(&cid) {
entry.0 = entry.0.saturating_sub(1);
entry.1 = Instant::now();
}
}
/// Post on behalf of `user`, optionally into a topic; the message is
/// published to readers directly (the relay's echo is dropped).
pub async fn post(
&self,
user: &User,
target: &ChatTarget,
text: &str,
topic: Option<i64>,
) -> Result<HistoryEntry, Denied> {
let rt = self.runtime();
if rt.quota.message_bytes > 0 && text.len() as u64 > rt.quota.message_bytes {
return Err(Denied::quota(format!(
"messages are limited to {} bytes",
rt.quota.message_bytes
)));
}
self.require_post(user, target).await?;
let relayed = match topic {
Some(id) => {
self.require(Feature::Topics)?;
let topic = self.db.topic(id)?.ok_or_else(|| Denied::not_found("topic"))?;
if topic.target != *target {
return Err(Denied::bad("the topic belongs to another chat"));
}
if topic.archived {
return Err(Denied::forbidden("the topic is archived"));
}
rt.topics.relay_format.replace("{topic}", &topic.title).replace("{text}", text)
}
None => text.to_string(),
};
// Posts go out under the user's nickname; `relay.format` only when the
// session cannot take it.
match target {
ChatTarget::Server => {
let _posting = self.lookup_posting.lock().await;
post_as(
&self.lookup.client().await,
&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) {
// Posting without reading still needs a relay in the channel.
self.add_reader(*cid).await?;
self.remove_reader(*cid);
}
self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?;
}
ChatTarget::Private(_) => unreachable!("checked by require_post"),
}
self.audit(Some(&user.uid), "post", &format!("{target:?}"));
Ok(self.publish(
ChatMessage {
target: target.clone(),
author_name: user.nickname.clone(),
author_uid: Some(user.uid.clone()),
author_id: None,
text: text.to_string(),
ts_ms: now_ms(),
via_relay: true,
blocked: false,
},
topic,
))
}
pub fn audit(&self, uid: Option<&str>, action: &str, detail: &str) {
self.db.audit(now_secs(), uid, action, detail);
}
}
fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool {
let mut config = RelayConfig::new(connect.clone());
config.nickname = nickname.to_string();
RelayPool::new(config)
}
/// The lookup session's own name, given `relay.nickname`.
fn lookup_nickname(nickname: &str) -> String {
format!("{nickname} Gateway")
}
/// What the gateway reads from the server once, at start.
struct ServerFacts {
version: String,
is_ts6: bool,
uid: String,
name: String,
needed_level: u8,
default_channel: ChannelId,
perm_ids: PermIds,
}
impl ServerFacts {
async fn load_until_it_works(lookup: &Lookup, connect: &Connect) -> Self {
let mut attempt = 0;
loop {
attempt += 1;
match Self::load(lookup).await {
Ok(facts) => return facts,
Err(error) => {
let retry_in = connect.retry_delay(attempt);
warn!(
error = format!("{error:#}"),
attempt,
retry_in_s = retry_in.as_secs_f32(),
"could not read the server's settings; trying again"
);
tokio::time::sleep(retry_in).await;
}
}
}
}
async fn load(lookup: &Lookup) -> Result<Self> {
// Failures are logged by the caller.
let info = lookup.send_quiet(&Command::new("serverinfo")).await.context("serverinfo")?;
let info = info.first().context("empty serverinfo")?;
let version = info.get("virtualserver_version").unwrap_or_default().to_string();
let channels = lookup
.send_quiet(&Command::new("channellist").flag("flags"))
.await
.context("channellist")?;
Ok(Self {
is_ts6: matches!(ServerFlavor::from_version_string(&version), ServerFlavor::Ts6(_)),
version,
uid: info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(),
name: info.get("virtualserver_name").unwrap_or_default().to_string(),
needed_level: info.parse("virtualserver_needed_identity_security_level").unwrap_or(8),
default_channel: channels
.iter()
.find(|r| r.flag("channel_flag_default") == Some(true))
.and_then(|r| r.parse("cid"))
.unwrap_or(1),
perm_ids: PermIds::load(lookup).await.context("looking up permission ids")?,
})
}
}
/// Split `text` by a topic format like `[#{topic}] {text}` into title and
/// the rest.
pub fn parse_topic_post<'a>(format: &str, text: &'a str) -> Option<(&'a str, &'a str)> {
let (prefix, rest) = format.split_once("{topic}")?;
let (middle, suffix) = rest.split_once("{text}")?;
if middle.is_empty() {
return None;
}
let body = text.strip_prefix(prefix)?.strip_suffix(suffix)?;
let (title, text) = body.split_once(middle)?;
(!title.is_empty()).then_some((title, text))
}
pub fn hash_token(token: &str) -> String {
BASE64_STANDARD.encode(Sha256::digest(token.as_bytes()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn topic_posts_parse() {
assert_eq!(
parse_topic_post("[#{topic}] {text}", "[#Raid] go now"),
Some(("Raid", "go now"))
);
assert_eq!(parse_topic_post("[#{topic}] {text}", "[#Raid]go"), None);
assert_eq!(parse_topic_post("[#{topic}] {text}", "hello"), None);
assert_eq!(parse_topic_post("{text}", "hello"), None);
assert_eq!(parse_topic_post("{topic}: {text} <<", "T: x <<"), Some(("T", "x")));
}
}