Skip to main content

zaun_community_protocol/command/
voice.rs

1//! Voice commands (specification §8.12, "Voice channels").
2//!
3//! Media never travels through the host. Participants connect to each other with WebRTC (a
4//! mesh of at most `mesh_max`), and the host only:
5//! - decides who may be in which voice channel (`CONNECT`, `SPEAK`, the moderation bits,
6//!   timeouts, lockdown, `user_limit`);
7//! - relays `voice.signal` (SDP and ICE) and `voice.keys` (media keys wrapped for one
8//!   participant) to the one participant they name, live and never stored;
9//! - tells clients its ICE servers and whether direct paths are allowed ([`IcePolicy`]).
10//!
11//! Key packages and wrapped keys are opaque here: their format and cryptography are the
12//! media layer's (`crypto::voice`).
13//!
14//! [`IcePolicy`]: super::object::IcePolicy
15
16use serde::{Deserialize, Serialize};
17
18use super::object::{IcePolicy, IceServer, Opaque, VoiceParticipant};
19use super::{BodyError, Validate, check};
20use crate::ids::{ChannelId, MemberId, VoiceSessionId};
21use crate::limits::{
22    VOICE_KEY_PACKAGE_MAX, VOICE_MESH_MAX, VOICE_SENDER_KEYS_MAX, VOICE_SIGNAL_MAX,
23    VOICE_WRAPPED_KEY_MAX,
24};
25
26fn opaque(field: &str, value: &Opaque, max: usize) -> Result<(), BodyError> {
27    if value.is_empty() {
28        return Err(BodyError::bad(field, "empty"));
29    }
30    if value.len() > max {
31        return Err(BodyError::too_large(field, max));
32    }
33    Ok(())
34}
35
36/// `voice.join`: enter a voice channel (leaving any other one).
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct Join {
39    /// The voice channel (or on the envelope).
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub channel_id: Option<ChannelId>,
42    /// The member's key package for this stay, at most 6 KiB.
43    pub key_package: Opaque,
44    /// Join muted.
45    #[serde(default)]
46    pub self_mute: bool,
47    /// Join deafened.
48    #[serde(default)]
49    pub self_deaf: bool,
50}
51
52/// The `voice.join` response.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Joined {
55    /// The voice channel.
56    pub channel_id: ChannelId,
57    /// The joiner's new stay.
58    pub voice_session: VoiceSessionId,
59    /// Everyone in the channel, the joiner included, oldest first, with key packages.
60    pub participants: Vec<VoiceParticipant>,
61    /// ICE servers to use.
62    pub ice_servers: Vec<IceServer>,
63    /// Which candidates to use.
64    pub ice_policy: IcePolicy,
65    /// The host's participant cap for any voice channel.
66    pub mesh_max: u32,
67}
68
69/// `voice.leave`: leave the voice channel the member is in.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
71pub struct Leave {}
72
73/// `voice.update`: the member's own mute and deafen.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
75pub struct Update {
76    /// New self-mute.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub self_mute: Option<bool>,
79    /// New self-deafen.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub self_deaf: Option<bool>,
82}
83
84/// `voice.signal`: WebRTC signalling for one other participant of the same channel.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct Signal {
87    /// The participant it is for.
88    pub to: MemberId,
89    /// That participant's current stay; a stale one is refused.
90    pub voice_session: VoiceSessionId,
91    /// SDP or ICE, opaque, at most 8 KiB.
92    pub data: Opaque,
93}
94
95/// One entry of `voice.keys`.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct KeyFor {
98    /// The participant it is for.
99    pub to: MemberId,
100    /// The sender's media key wrapped for that participant, opaque, at most 1.5 KiB.
101    pub wrapped: Opaque,
102}
103
104/// `voice.keys`: the sender's media key for `epoch`, wrapped for each other participant.
105/// A whole mesh always fits in one command, so an epoch is never split.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Keys {
108    /// The sender's key epoch.
109    pub epoch: u64,
110    /// The sender's signed message for this epoch, the same for every recipient (it covers
111    /// every wrapped key), opaque, at most 6 KiB. Each recipient receives it.
112    pub sender_keys: Opaque,
113    /// One entry per recipient, at most `mesh_max − 1` and each recipient once.
114    pub keys: Vec<KeyFor>,
115}
116
117/// `voice.moderate`: server mute or deafen, move or disconnect another member.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119pub struct Moderate {
120    /// The member acted on.
121    pub member_id: MemberId,
122    /// Server mute (`MUTE_MEMBERS`).
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub server_mute: Option<bool>,
125    /// Server deafen (`DEAFEN_MEMBERS`).
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub server_deaf: Option<bool>,
128    /// Move to this voice channel (`MOVE_MEMBERS` in both channels).
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub move_to: Option<ChannelId>,
131    /// Disconnect from voice (`MOVE_MEMBERS`).
132    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
133    pub disconnect: bool,
134}
135
136impl Validate for Join {
137    fn validate(&self) -> Result<(), BodyError> {
138        opaque("key_package", &self.key_package, VOICE_KEY_PACKAGE_MAX)
139    }
140}
141
142impl Validate for Leave {
143    fn validate(&self) -> Result<(), BodyError> {
144        Ok(())
145    }
146}
147
148impl Validate for Update {
149    fn validate(&self) -> Result<(), BodyError> {
150        if self.self_mute.is_none() && self.self_deaf.is_none() {
151            return Err(BodyError::bad("body", "nothing to update"));
152        }
153        Ok(())
154    }
155}
156
157impl Validate for Signal {
158    fn validate(&self) -> Result<(), BodyError> {
159        opaque("data", &self.data, VOICE_SIGNAL_MAX)
160    }
161}
162
163impl Validate for Keys {
164    fn validate(&self) -> Result<(), BodyError> {
165        check::json_safe("epoch", self.epoch)?;
166        opaque("sender_keys", &self.sender_keys, VOICE_SENDER_KEYS_MAX)?;
167        if self.keys.is_empty() {
168            return Err(BodyError::bad("keys", "empty"));
169        }
170        check::count("keys", self.keys.len(), VOICE_MESH_MAX as usize - 1)?;
171        check::unique("keys", self.keys.iter().map(|k| &k.to))?;
172        self.keys
173            .iter()
174            .try_for_each(|k| opaque("keys", &k.wrapped, VOICE_WRAPPED_KEY_MAX))
175    }
176}
177
178impl Validate for Moderate {
179    fn validate(&self) -> Result<(), BodyError> {
180        let moves = usize::from(self.move_to.is_some()) + usize::from(self.disconnect);
181        if moves > 1 {
182            return Err(BodyError::bad("move_to", "move or disconnect, not both"));
183        }
184        if moves == 0 && self.server_mute.is_none() && self.server_deaf.is_none() {
185            return Err(BodyError::bad("body", "nothing to do"));
186        }
187        Ok(())
188    }
189}