Implement Rust and Slint native client migration and fix desktop startup
This commit is contained in:
1 parent
0d11f8f99d
commit
eb24965076
1303 files changed
+732670
-2375
No files matched your search
@@ -60,6 +60,3 @@ windows-sys = { version = "0.61", features = [
|
||||
dbus = { version = "0.9", features = ["vendored"] }
|
||||
x11rb = "0.13"
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 4
|
||||
+186
-57
@@ -204,12 +204,52 @@ pub const HINT_PERMISSIONS: &[&str] = &[
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PrivilegeKeyKind { ServerGroup, ChannelGroup }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum PropertyScope { ChannelCreate, ChannelEdit, ServerEdit }
|
||||
|
||||
/// Immutable, scope-bound wire properties. Constructors accept typed JSON values,
|
||||
/// not serialized JSON or wire strings: booleans/numbers retain their types and
|
||||
/// password values are plaintext at this boundary and hashed exactly once.
|
||||
/// The derived channel password flag cannot be supplied by the caller.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Properties {
|
||||
scope: PropertyScope,
|
||||
values: Vec<(&'static str, String)>,
|
||||
}
|
||||
|
||||
impl Properties {
|
||||
pub fn channel_create(value: Map<String, Value>) -> Result<Self, ErrorObj> {
|
||||
let values = properties(value, CHANNEL_CREATE)?;
|
||||
if !values.iter().any(|(k, _)| *k == "channel_name") { return Err(bad("channel_name is required")); }
|
||||
Ok(Self { scope: PropertyScope::ChannelCreate, values })
|
||||
}
|
||||
pub fn channel_edit(value: Map<String, Value>) -> Result<Self, ErrorObj> {
|
||||
let values = properties(value, CHANNEL_EDIT)?;
|
||||
if values.is_empty() { return Err(bad("properties must not be empty")); }
|
||||
Ok(Self { scope: PropertyScope::ChannelEdit, values })
|
||||
}
|
||||
pub fn server_edit(value: Map<String, Value>) -> Result<Self, ErrorObj> {
|
||||
let values = properties(value, SERVER_EDIT)?;
|
||||
if values.is_empty() { return Err(bad("properties must not be empty")); }
|
||||
Ok(Self { scope: PropertyScope::ServerEdit, values })
|
||||
}
|
||||
fn check_scope(&self, scope: PropertyScope) -> Result<(), ErrorObj> {
|
||||
if self.scope != scope { return Err(bad("properties belong to a different command")); }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Properties {
|
||||
type Target = [(&'static str, String)];
|
||||
fn deref(&self) -> &Self::Target { &self.values }
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdminCommand {
|
||||
Extra(extra::Command),
|
||||
Context,
|
||||
ChannelCreate { generation: u64, parent_id: u64, properties: Vec<(&'static str, String)> },
|
||||
ChannelEdit { generation: u64, channel_id: u64, properties: Vec<(&'static str, String)> },
|
||||
ChannelCreate { generation: u64, parent_id: u64, properties: Properties },
|
||||
ChannelEdit { generation: u64, channel_id: u64, properties: Properties },
|
||||
ChannelMove { generation: u64, channel_id: u64, parent_id: u64, order: Option<u64> },
|
||||
ChannelDelete { generation: u64, channel_id: u64, force: bool, confirm: String },
|
||||
ChannelSubscribe { channel_id: u64, subscribe: bool },
|
||||
@@ -230,7 +270,7 @@ pub enum AdminCommand {
|
||||
TempPasswordAdd { generation: u64, password: String, description: String, duration_s: u64, channel_id: u64, channel_password: String },
|
||||
TempPasswordDelete { generation: u64, password: String, confirm: String },
|
||||
ServerInfo,
|
||||
ServerEdit { generation: u64, confirm: String, properties: Vec<(&'static str, String)> },
|
||||
ServerEdit { generation: u64, confirm: String, properties: Properties },
|
||||
ServerGroupPermList { group_id: u64 },
|
||||
ChannelGroupPermList { group_id: u64 },
|
||||
ChannelPermList { channel_id: u64 },
|
||||
@@ -466,130 +506,165 @@ struct ServerEditArgs { generation: u64, confirm: String, properties: Map<String
|
||||
|
||||
pub fn parse(cmd: &str, raw: Option<&serde_json::value::RawValue>) -> Result<AdminCommand, ErrorObj> {
|
||||
use AdminCommand as C;
|
||||
let token = |t: &str| check_str("token", t, 255, false);
|
||||
if extra::recognizes(cmd) { return extra::parse(cmd, raw).map(C::Extra); }
|
||||
Ok(match cmd {
|
||||
let command = match cmd {
|
||||
"admin_context" => { args::<Empty>(raw)?; C::Context }
|
||||
"channel_create" => {
|
||||
let a: CreateArgs = args(raw)?;
|
||||
let properties = properties(a.properties, CHANNEL_CREATE)?;
|
||||
if !properties.iter().any(|(k, _)| *k == "channel_name") {
|
||||
return Err(bad("channel_name is required"));
|
||||
}
|
||||
C::ChannelCreate { generation: generation(a.generation)?, parent_id: a.parent_id, properties }
|
||||
let properties = Properties::channel_create(a.properties)?;
|
||||
C::ChannelCreate { generation: a.generation, parent_id: a.parent_id, properties }
|
||||
}
|
||||
"channel_edit" => {
|
||||
let a: EditArgs = args(raw)?;
|
||||
let properties = properties(a.properties, CHANNEL_EDIT)?;
|
||||
if properties.is_empty() { return Err(bad("properties must not be empty")); }
|
||||
C::ChannelEdit { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, properties }
|
||||
let properties = Properties::channel_edit(a.properties)?;
|
||||
C::ChannelEdit { generation: a.generation, channel_id: a.channel_id, properties }
|
||||
}
|
||||
"channel_move" => {
|
||||
let a: MoveArgs = args(raw)?;
|
||||
if a.parent_id == a.channel_id { return Err(bad("a channel cannot be its own parent")); }
|
||||
C::ChannelMove { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, parent_id: a.parent_id, order: a.order }
|
||||
C::ChannelMove { generation: a.generation, channel_id: a.channel_id, parent_id: a.parent_id, order: a.order }
|
||||
}
|
||||
"channel_delete" => {
|
||||
let a: DeleteArgs = args(raw)?;
|
||||
C::ChannelDelete { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, force: a.force, confirm: a.confirm }
|
||||
C::ChannelDelete { generation: a.generation, channel_id: a.channel_id, force: a.force, confirm: a.confirm }
|
||||
}
|
||||
"channel_subscribe" => {
|
||||
let a: SubscribeArgs = args(raw)?;
|
||||
C::ChannelSubscribe { channel_id: positive("channel_id", a.channel_id)?, subscribe: a.subscribe }
|
||||
C::ChannelSubscribe { channel_id: a.channel_id, subscribe: a.subscribe }
|
||||
}
|
||||
"channel_subscribe_all" => C::ChannelSubscribeAll { subscribe: args::<SubscribeAllArgs>(raw)?.subscribe },
|
||||
"channel_description" => C::ChannelDescription { channel_id: positive("channel_id", args::<ChannelArgs>(raw)?.channel_id)? },
|
||||
"channel_description" => C::ChannelDescription { channel_id: args::<ChannelArgs>(raw)?.channel_id },
|
||||
"set_away" => {
|
||||
let a: AwayArgs = args(raw)?;
|
||||
if !a.away && a.message.is_some() { return Err(bad("message is only allowed with away: true")); }
|
||||
check_opt("message", &a.message, 80)?;
|
||||
C::SetAway { away: a.away, message: a.message }
|
||||
}
|
||||
"talk_request" => {
|
||||
let a: TalkRequestArgs = args(raw)?;
|
||||
if !a.request && a.message.is_some() { return Err(bad("message is only allowed with request: true")); }
|
||||
check_opt("message", &a.message, 50)?;
|
||||
C::TalkRequest { request: a.request, message: a.message }
|
||||
}
|
||||
"talk_power" => {
|
||||
let a: TalkPowerArgs = args(raw)?;
|
||||
let target = menu::Target { client_id: a.client_id, uid: a.uid };
|
||||
menu::validate_target(&target)?;
|
||||
C::TalkPower { generation: generation(a.generation)?, target, grant: a.grant }
|
||||
C::TalkPower { generation: a.generation, target, grant: a.grant }
|
||||
}
|
||||
"ban_list" => { args::<Empty>(raw)?; C::BanList }
|
||||
"ban_add" => {
|
||||
let a: BanAddArgs = args(raw)?;
|
||||
for (field, v) in [("ip", &a.ip), ("name", &a.name), ("uid", &a.uid)] { check_opt(field, v, 255)?; }
|
||||
check_opt("reason", &a.reason, 512)?;
|
||||
let given = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.is_empty());
|
||||
if !given(&a.ip) && !given(&a.name) && !given(&a.uid) {
|
||||
return Err(bad("at least one of ip, name or uid is required"));
|
||||
}
|
||||
if a.duration_s > u32::MAX as u64 { return Err(bad("duration_s is too large")); }
|
||||
C::BanAdd { generation: generation(a.generation)?, ip: a.ip, name: a.name, uid: a.uid, duration_s: a.duration_s, reason: a.reason }
|
||||
C::BanAdd { generation: a.generation, ip: a.ip, name: a.name, uid: a.uid, duration_s: a.duration_s, reason: a.reason }
|
||||
}
|
||||
"ban_delete" => {
|
||||
let a: BanDeleteArgs = args(raw)?;
|
||||
C::BanDelete { generation: generation(a.generation)?, ban_id: positive("ban_id", a.ban_id)?, confirm: a.confirm }
|
||||
C::BanDelete { generation: a.generation, ban_id: a.ban_id, confirm: a.confirm }
|
||||
}
|
||||
"ban_delete_all" => {
|
||||
let a: ConfirmArgs = args(raw)?;
|
||||
C::BanDeleteAll { generation: generation(a.generation)?, confirm: a.confirm }
|
||||
C::BanDeleteAll { generation: a.generation, confirm: a.confirm }
|
||||
}
|
||||
"privilege_key_list" => { args::<Empty>(raw)?; C::PrivilegeKeyList }
|
||||
"privilege_key_add" => {
|
||||
let a: KeyAddArgs = args(raw)?;
|
||||
check_str("description", &a.description, 255, true)?;
|
||||
let (kind, channel_id) = match (a.kind.as_str(), a.channel_id) {
|
||||
("server_group", None) => (PrivilegeKeyKind::ServerGroup, 0),
|
||||
("channel_group", Some(cid)) => (PrivilegeKeyKind::ChannelGroup, positive("channel_id", cid)?),
|
||||
("channel_group", Some(cid)) => (PrivilegeKeyKind::ChannelGroup, cid),
|
||||
("server_group", Some(_)) => return Err(bad("channel_id is only allowed for kind channel_group")),
|
||||
("channel_group", None) => return Err(bad("channel_id is required for kind channel_group")),
|
||||
_ => return Err(bad("kind must be 'server_group' or 'channel_group'")),
|
||||
};
|
||||
C::PrivilegeKeyAdd { generation: generation(a.generation)?, kind, group_id: positive("group_id", a.group_id)?, channel_id, description: a.description }
|
||||
C::PrivilegeKeyAdd { generation: a.generation, kind, group_id: a.group_id, channel_id, description: a.description }
|
||||
}
|
||||
"privilege_key_delete" => {
|
||||
let a: TokenArgs = args(raw)?;
|
||||
token(&a.token)?;
|
||||
let confirm = a.confirm.ok_or_else(|| bad("confirm is required"))?;
|
||||
C::PrivilegeKeyDelete { generation: generation(a.generation)?, token: a.token, confirm }
|
||||
C::PrivilegeKeyDelete { generation: a.generation, token: a.token, confirm }
|
||||
}
|
||||
"privilege_key_use" => {
|
||||
let a: TokenArgs = args(raw)?;
|
||||
token(&a.token)?;
|
||||
if a.confirm.is_some() { return Err(bad("confirm is not used by privilege_key_use")); }
|
||||
C::PrivilegeKeyUse { generation: generation(a.generation)?, token: a.token }
|
||||
C::PrivilegeKeyUse { generation: a.generation, token: a.token }
|
||||
}
|
||||
"temp_password_list" => { args::<Empty>(raw)?; C::TempPasswordList }
|
||||
"temp_password_add" => {
|
||||
let a: TempAddArgs = args(raw)?;
|
||||
check_str("password", &a.password, 255, false)?;
|
||||
check_str("description", &a.description, 255, true)?;
|
||||
check_str("channel_password", &a.channel_password, 255, true)?;
|
||||
if a.duration_s == 0 || a.duration_s > u32::MAX as u64 { return Err(bad("duration_s must be 1..=4294967295")); }
|
||||
if a.channel_id == 0 && !a.channel_password.is_empty() { return Err(bad("channel_password needs channel_id")); }
|
||||
C::TempPasswordAdd { generation: generation(a.generation)?, password: a.password, description: a.description, duration_s: a.duration_s, channel_id: a.channel_id, channel_password: a.channel_password }
|
||||
C::TempPasswordAdd { generation: a.generation, password: a.password, description: a.description, duration_s: a.duration_s, channel_id: a.channel_id, channel_password: a.channel_password }
|
||||
}
|
||||
"temp_password_delete" => {
|
||||
let a: TempDeleteArgs = args(raw)?;
|
||||
check_str("password", &a.password, 255, false)?;
|
||||
C::TempPasswordDelete { generation: generation(a.generation)?, password: a.password, confirm: a.confirm }
|
||||
C::TempPasswordDelete { generation: a.generation, password: a.password, confirm: a.confirm }
|
||||
}
|
||||
"server_info" => { args::<Empty>(raw)?; C::ServerInfo }
|
||||
"server_edit" => {
|
||||
let a: ServerEditArgs = args(raw)?;
|
||||
let properties = properties(a.properties, SERVER_EDIT)?;
|
||||
if properties.is_empty() { return Err(bad("properties must not be empty")); }
|
||||
C::ServerEdit { generation: generation(a.generation)?, confirm: a.confirm, properties }
|
||||
let properties = Properties::server_edit(a.properties)?;
|
||||
C::ServerEdit { generation: a.generation, confirm: a.confirm, properties }
|
||||
}
|
||||
"server_group_perm_list" => C::ServerGroupPermList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
|
||||
"channel_group_perm_list" => C::ChannelGroupPermList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
|
||||
"channel_perm_list" => C::ChannelPermList { channel_id: positive("channel_id", args::<ChannelArgs>(raw)?.channel_id)? },
|
||||
"server_group_client_list" => C::ServerGroupClientList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
|
||||
"server_group_perm_list" => C::ServerGroupPermList { group_id: args::<GroupArgs>(raw)?.group_id },
|
||||
"channel_group_perm_list" => C::ChannelGroupPermList { group_id: args::<GroupArgs>(raw)?.group_id },
|
||||
"channel_perm_list" => C::ChannelPermList { channel_id: args::<ChannelArgs>(raw)?.channel_id },
|
||||
"server_group_client_list" => C::ServerGroupClientList { group_id: args::<GroupArgs>(raw)?.group_id },
|
||||
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
|
||||
})
|
||||
};
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
/// Checks fields that native callers can construct directly. Property values are
|
||||
/// already unforgeably validated by their scope-specific constructors.
|
||||
pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
|
||||
use AdminCommand as C;
|
||||
if let C::Extra(c) = command { return c.validate(); }
|
||||
if let Some(g) = command.generation() { generation(g)?; }
|
||||
match command {
|
||||
C::ChannelCreate { properties, .. } => properties.check_scope(PropertyScope::ChannelCreate)?,
|
||||
C::ChannelEdit { channel_id, properties, .. } => {
|
||||
properties.check_scope(PropertyScope::ChannelEdit)?;
|
||||
positive("channel_id", *channel_id)?;
|
||||
}
|
||||
C::ServerEdit { properties, .. } => properties.check_scope(PropertyScope::ServerEdit)?,
|
||||
C::ChannelMove { channel_id, parent_id, .. } => {
|
||||
if parent_id == channel_id { return Err(bad("a channel cannot be its own parent")); }
|
||||
positive("channel_id", *channel_id)?;
|
||||
}
|
||||
C::ChannelDelete { channel_id, .. } | C::ChannelSubscribe { channel_id, .. }
|
||||
| C::ChannelDescription { channel_id } | C::ChannelPermList { channel_id } => { positive("channel_id", *channel_id)?; }
|
||||
C::SetAway { away, message } => {
|
||||
if !away && message.is_some() { return Err(bad("message is only allowed with away: true")); }
|
||||
check_opt("message", message, 80)?;
|
||||
}
|
||||
C::TalkRequest { request, message } => {
|
||||
if !request && message.is_some() { return Err(bad("message is only allowed with request: true")); }
|
||||
check_opt("message", message, 50)?;
|
||||
}
|
||||
C::TalkPower { target, .. } => menu::validate_target(target)?,
|
||||
C::BanAdd { ip, name, uid, duration_s, reason, .. } => {
|
||||
for (field, value) in [("ip", ip), ("name", name), ("uid", uid)] { check_opt(field, value, 255)?; }
|
||||
check_opt("reason", reason, 512)?;
|
||||
if ![ip, name, uid].iter().any(|v| v.as_deref().is_some_and(|s| !s.is_empty())) {
|
||||
return Err(bad("at least one of ip, name or uid is required"));
|
||||
}
|
||||
if *duration_s > u32::MAX as u64 { return Err(bad("duration_s is too large")); }
|
||||
}
|
||||
C::BanDelete { ban_id, .. } => { positive("ban_id", *ban_id)?; }
|
||||
C::PrivilegeKeyAdd { kind, group_id, channel_id, description, .. } => {
|
||||
check_str("description", description, 255, true)?;
|
||||
match kind {
|
||||
PrivilegeKeyKind::ServerGroup if *channel_id != 0 => return Err(bad("channel_id is only allowed for kind channel_group")),
|
||||
PrivilegeKeyKind::ChannelGroup => { positive("channel_id", *channel_id)?; }
|
||||
PrivilegeKeyKind::ServerGroup => {}
|
||||
}
|
||||
positive("group_id", *group_id)?;
|
||||
}
|
||||
C::PrivilegeKeyDelete { token, .. } | C::PrivilegeKeyUse { token, .. } => check_str("token", token, 255, false)?,
|
||||
C::TempPasswordAdd { password, description, duration_s, channel_id, channel_password, .. } => {
|
||||
check_str("password", password, 255, false)?;
|
||||
check_str("description", description, 255, true)?;
|
||||
check_str("channel_password", channel_password, 255, true)?;
|
||||
if *duration_s == 0 || *duration_s > u32::MAX as u64 { return Err(bad("duration_s must be 1..=4294967295")); }
|
||||
if *channel_id == 0 && !channel_password.is_empty() { return Err(bad("channel_password needs channel_id")); }
|
||||
}
|
||||
C::TempPasswordDelete { password, .. } => check_str("password", password, 255, false)?,
|
||||
C::ServerGroupPermList { group_id } | C::ChannelGroupPermList { group_id } | C::ServerGroupClientList { group_id } => { positive("group_id", *group_id)?; }
|
||||
C::Extra(_) | C::Context | C::ChannelSubscribeAll { .. } | C::BanList | C::BanDeleteAll { .. }
|
||||
| C::PrivilegeKeyList | C::TempPasswordList | C::ServerInfo => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ replies
|
||||
@@ -855,6 +930,60 @@ pub fn talk_power(client_id: u16, grant: bool) -> OutCommand {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(name: &str, raw: Option<&serde_json::value::RawValue>) -> Result<AdminCommand, ErrorObj> {
|
||||
let command = super::parse(name, raw)?;
|
||||
validate(&command)?;
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_properties_hash_once_and_cannot_cross_scopes() {
|
||||
let properties = Properties::channel_create(Map::from_iter([
|
||||
("channel_name".into(), Value::String("Lobby".into())),
|
||||
("channel_password".into(), Value::String("secret".into())),
|
||||
])).unwrap();
|
||||
let expected = encode_password(b"secret");
|
||||
assert!(properties.contains(&("channel_password", expected.clone())));
|
||||
assert!(properties.contains(&("channel_flag_password", "1".into())));
|
||||
let command = AdminCommand::ChannelCreate { generation: 1, parent_id: 0, properties: properties.clone() };
|
||||
let checked = crate::protocol::validate_command(crate::protocol::Command::Admin(command.clone())).unwrap();
|
||||
assert_eq!(checked.into_inner(), crate::protocol::Command::Admin(command));
|
||||
let wrong_scope = AdminCommand::ChannelEdit { generation: 1, channel_id: 7, properties };
|
||||
assert_eq!(validate(&wrong_scope).unwrap_err().code, ErrorCode::BadRequest);
|
||||
for value in [
|
||||
json!({"channel_flag_password":true}), json!({"channel_codec_quality":11}),
|
||||
json!({"channel_password":42}), json!({"channel_flag_permanent":true,"channel_flag_semi_permanent":true}),
|
||||
] {
|
||||
assert_eq!(Properties::channel_edit(value.as_object().unwrap().clone()).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
assert!(Properties::channel_create(Map::new()).is_err());
|
||||
assert!(Properties::channel_edit(Map::new()).is_err());
|
||||
assert!(Properties::server_edit(Map::new()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_admin_and_permission_arguments_reject_invalid_values() {
|
||||
use extra::{Command as E, GroupKind, Permission};
|
||||
let invalid = [
|
||||
AdminCommand::BanDelete { generation: 0, ban_id: 1, confirm: "1".into() },
|
||||
AdminCommand::SetAway { away: false, message: Some("reason".into()) },
|
||||
AdminCommand::TalkRequest { request: true, message: Some("x".repeat(51)) },
|
||||
AdminCommand::TalkPower { generation: 1, target: menu::Target { client_id: 7, uid: String::new() }, grant: true },
|
||||
AdminCommand::PrivilegeKeyUse { generation: 1, token: "bad\n".into() },
|
||||
AdminCommand::PrivilegeKeyAdd { generation: 1, kind: PrivilegeKeyKind::ServerGroup, group_id: 1, channel_id: 7, description: String::new() },
|
||||
AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 1, channel_id: 0, channel_password: "pw".into() },
|
||||
AdminCommand::ServerGroupPermList { group_id: 0 },
|
||||
AdminCommand::Extra(E::GroupSetPermissions { generation: 1, kind: GroupKind::Server, group_id: 7, permissions: vec![] }),
|
||||
AdminCommand::Extra(E::ChannelSetPermissions { generation: 1, channel_id: 7, permissions: vec![Permission { id: "b_test".into(), value: 1, negate: true, skip: false }] }),
|
||||
AdminCommand::Extra(E::GroupDeletePermissions { generation: 1, kind: GroupKind::Server, group_id: 7, permissions: vec!["0".into()] }),
|
||||
AdminCommand::Extra(E::GroupDelete { generation: 1, kind: GroupKind::Server, group_id: 7, force: true, confirm: "8".into() }),
|
||||
AdminCommand::Extra(E::ClientDatabaseDelete { generation: 1, client_database_id: 7, confirm: "8".into() }),
|
||||
];
|
||||
for command in invalid {
|
||||
assert_eq!(crate::protocol::validate_command(crate::protocol::Command::Admin(command)).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json(cmd: &str, v: Value) -> Result<AdminCommand, ErrorObj> {
|
||||
let raw = serde_json::value::RawValue::from_string(v.to_string()).unwrap();
|
||||
parse(cmd, Some(&raw))
|
||||
|
||||
@@ -55,7 +55,7 @@ impl Command {
|
||||
|Self::GroupSetPermissions{generation,..}|Self::ChannelSetPermissions{generation,..}|Self::ServerGroupAddClient{generation,..}
|
||||
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
|
||||
}}
|
||||
fn validate(&self) -> Result<(),ErrorObj> {
|
||||
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
|
||||
let positive=|id:u64| if id==0 {Err(menu::bad("target ID must be positive"))}else{Ok(())};
|
||||
let text=|s:&str,max:usize| if s.is_empty()||s.len()>max||s.chars().any(char::is_control){Err(menu::bad("invalid text argument"))}else{Ok(())};
|
||||
if let Some(g)=self.generation(){positive(g)?;}
|
||||
@@ -168,5 +168,5 @@ pub fn parse(name:&str,raw:Option<&serde_json::value::RawValue>)->Result<Command
|
||||
let obj=v.as_object_mut().ok_or_else(||menu::bad("args must be an object"))?;
|
||||
if obj.contains_key("command"){return Err(menu::bad("unexpected command argument"));}
|
||||
obj.insert("command".into(),Value::String(name.into()));
|
||||
let cmd:Command=serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))?;cmd.validate()?;Ok(cmd)
|
||||
serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))
|
||||
}
|
||||
+222
-24
@@ -1,7 +1,13 @@
|
||||
//! Profileless selected-application audio helper. Never substitutes endpoint/system loopback.
|
||||
//! Profileless selected-application audio. Never substitutes endpoint/system loopback.
|
||||
//! Native consumers receive bounded PCM directly; only `run` uses the CLI transport.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::process::ExitCode;
|
||||
use serde_json::json;
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "app_audio_windows.rs"]
|
||||
@@ -14,9 +20,116 @@ mod platform;
|
||||
#[allow(dead_code)]
|
||||
mod linux_contract_tests;
|
||||
|
||||
pub const PCM_BYTES: usize = 960 * 2 * 2;
|
||||
const EVENT_CAPACITY: usize = 4;
|
||||
|
||||
/// Explicit, clonable cancellation shared by enumeration and capture operations.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Cancellation(Arc<AtomicBool>);
|
||||
impl Cancellation {
|
||||
pub fn cancel(&self) { self.0.store(true, Ordering::Release); }
|
||||
pub fn is_cancelled(&self) -> bool { self.0.load(Ordering::Acquire) }
|
||||
pub(super) fn check(&self) -> Result<(), String> {
|
||||
if self.is_cancelled() { Err("Application audio cancelled".into()) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed 20 ms, 48 kHz stereo signed little-endian PCM. Sequence gaps denote drops.
|
||||
#[derive(Debug)]
|
||||
pub enum CaptureEvent {
|
||||
Format,
|
||||
Pcm { sequence: u64, bytes: [u8; PCM_BYTES] },
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Sink(mpsc::SyncSender<CaptureEvent>);
|
||||
impl Sink {
|
||||
pub(super) fn format(&self) -> Result<(), String> {
|
||||
self.0.try_send(CaptureEvent::Format).map_err(|_| "Application audio consumer stopped".into())
|
||||
}
|
||||
pub(super) fn pcm(&self, sequence: u64, bytes: [u8; PCM_BYTES]) -> Result<(), String> {
|
||||
match self.0.try_send(CaptureEvent::Pcm { sequence, bytes }) {
|
||||
Ok(()) | Err(mpsc::TrySendError::Full(_)) => Ok(()),
|
||||
Err(mpsc::TrySendError::Disconnected(_)) => Err("Application audio consumer stopped".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the capture worker and its bounded output. Drop cancels and joins it.
|
||||
/// Host callbacks run on the caller, never on a capture or helper-reader thread.
|
||||
/// Drain continuously; a slow consumer drops new PCM, never blocks capture.
|
||||
/// The terminal success/error is returned by `join`/`stop`, not a droppable event.
|
||||
/// `stop`, `join`, and Drop block: use an owner/shutdown worker, never the UI thread.
|
||||
pub struct Capture {
|
||||
cancel: Cancellation,
|
||||
events: mpsc::Receiver<CaptureEvent>,
|
||||
worker: Option<JoinHandle<Result<(), String>>>,
|
||||
}
|
||||
impl Capture {
|
||||
pub fn cancel(&self) { self.cancel.cancel(); }
|
||||
pub fn is_finished(&self) -> bool { self.worker.as_ref().is_none_or(JoinHandle::is_finished) }
|
||||
pub fn recv_timeout(&self, timeout: Duration) -> Result<CaptureEvent, mpsc::RecvTimeoutError> {
|
||||
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
|
||||
let event = self.events.recv_timeout(timeout)?;
|
||||
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
|
||||
Ok(event)
|
||||
}
|
||||
/// Dispatch no more than the queue capacity, even while capture produces more.
|
||||
pub fn dispatch_pending(&self, mut callback: impl FnMut(CaptureEvent)) -> usize {
|
||||
let mut count = 0;
|
||||
while count < EVENT_CAPACITY && !self.cancel.is_cancelled() {
|
||||
let Ok(event) = self.events.try_recv() else { break };
|
||||
callback(event);
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
pub fn join(mut self) -> Result<(), String> { self.join_worker() }
|
||||
pub fn stop(mut self) -> Result<(), String> { self.cancel(); self.join_worker() }
|
||||
fn join_worker(&mut self) -> Result<(), String> {
|
||||
self.worker.take().map_or(Ok(()), |worker| worker.join().unwrap_or_else(|_| Err("Application audio worker panicked".into())))
|
||||
}
|
||||
}
|
||||
impl Drop for Capture {
|
||||
fn drop(&mut self) { self.cancel(); let _ = self.join_worker(); }
|
||||
}
|
||||
|
||||
/// Enumerate without recording. Retains platform capability and isolation metadata.
|
||||
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
|
||||
cancel.check()?;
|
||||
#[cfg(any(windows, target_os = "linux"))]
|
||||
{ platform::list(cancel) }
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
{ Ok(json!({"supported":false,"platform":std::env::consts::OS,"reason":unsupported_reason(),"applications":[]})) }
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
fn unsupported_reason() -> &'static str {
|
||||
if cfg!(target_os = "macos") {
|
||||
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
|
||||
} else { "This platform has no selected-application audio capture backend." }
|
||||
}
|
||||
|
||||
/// Start only an exact identity returned by `list`; initialization failures are joined.
|
||||
pub fn capture(id: &str, cancel: Cancellation) -> Result<Capture, String> {
|
||||
cancel.check()?;
|
||||
#[cfg(any(windows, target_os = "linux"))]
|
||||
{
|
||||
let id = id.to_owned();
|
||||
spawn_capture(cancel, move |cancel, sink| platform::capture(&id, cancel, sink))
|
||||
}
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
{ let _ = id; Err(unsupported_reason().into()) }
|
||||
}
|
||||
|
||||
fn spawn_capture(cancel: Cancellation, run: impl FnOnce(&Cancellation, &Sink) -> Result<(), String> + Send + 'static) -> Result<Capture, String> {
|
||||
let (tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
|
||||
let requested = cancel.clone();
|
||||
let worker = std::thread::Builder::new().name("app-audio-capture".into()).spawn(move || run(&requested, &Sink(tx))).map_err(|e| e.to_string())?;
|
||||
Ok(Capture { cancel, events, worker: Some(worker) })
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> ExitCode {
|
||||
let result = dispatch(args);
|
||||
match result {
|
||||
match dispatch(args) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => {
|
||||
eprintln!("{}", json!({"event":"error","code":"application_audio","message":message}));
|
||||
@@ -26,26 +139,111 @@ pub fn run(args: &[String]) -> ExitCode {
|
||||
}
|
||||
|
||||
fn dispatch(args: &[String]) -> Result<(), String> {
|
||||
#[cfg(any(windows, target_os = "linux"))]
|
||||
{
|
||||
match args {
|
||||
[command] if command == "list" => platform::list(),
|
||||
[command, id] if command == "capture" => platform::capture(id),
|
||||
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
{
|
||||
let reason = if cfg!(target_os = "macos") {
|
||||
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
|
||||
} else {
|
||||
"This platform has no selected-application audio capture backend."
|
||||
};
|
||||
if matches!(args, [command] if command == "list") {
|
||||
println!("{}", json!({"supported":false,"platform":std::env::consts::OS,"reason":reason,"applications":[]}));
|
||||
let cancel = Cancellation::default();
|
||||
match args {
|
||||
[command] if command == "list" => {
|
||||
println!("{}", list(&cancel)?);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(reason.into())
|
||||
}
|
||||
},
|
||||
[command, id] if command == "capture" => {
|
||||
let capture = capture(id, cancel.clone())?;
|
||||
// Only the standalone CLI owns this blocking stdin thread; library workers do not.
|
||||
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
|
||||
let _ = std::io::stdin().read(&mut [0u8; 1]);
|
||||
cancel.cancel();
|
||||
}).map_err(|e| e.to_string())?;
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
let mut encoded = String::with_capacity(PCM_BYTES * 4 / 3);
|
||||
loop {
|
||||
match capture.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(CaptureEvent::Format) => writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}"),
|
||||
Ok(CaptureEvent::Pcm { sequence, bytes }) => {
|
||||
encoded.clear(); STANDARD.encode_string(bytes, &mut encoded);
|
||||
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}.and_then(|_| stdout.flush()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
capture.join()
|
||||
},
|
||||
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn bounded_consumer_preserves_format_and_drops_without_blocking() {
|
||||
let capture = spawn_capture(Cancellation::default(), |_, sink| {
|
||||
sink.format()?;
|
||||
for sequence in 0..100 { sink.pcm(sequence, [7; PCM_BYTES])?; }
|
||||
Ok(())
|
||||
}).unwrap();
|
||||
while !capture.is_finished() { std::thread::yield_now(); }
|
||||
let mut events = Vec::new();
|
||||
assert_eq!(capture.dispatch_pending(|event| events.push(event)), EVENT_CAPACITY);
|
||||
assert!(matches!(events[0], CaptureEvent::Format));
|
||||
assert!(matches!(events[1], CaptureEvent::Pcm { sequence: 0, .. }));
|
||||
assert_eq!(capture.dispatch_pending(|_| panic!("queue should be empty")), 0);
|
||||
capture.join().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_discards_queued_pcm_before_host_callback() {
|
||||
let capture = spawn_capture(Cancellation::default(), |_, sink| {
|
||||
sink.format()?;
|
||||
sink.pcm(0, [9; PCM_BYTES])
|
||||
}).unwrap();
|
||||
while !capture.is_finished() { std::thread::yield_now(); }
|
||||
capture.cancel();
|
||||
assert_eq!(capture.dispatch_pending(|_| panic!("cancelled capture forwarded data")), 0);
|
||||
assert!(matches!(capture.recv_timeout(Duration::ZERO), Err(mpsc::RecvTimeoutError::Disconnected)));
|
||||
capture.stop().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn callback_cancellation_stops_current_dispatch_batch() {
|
||||
let cancel = Cancellation::default();
|
||||
let capture = spawn_capture(cancel.clone(), |_, sink| {
|
||||
sink.format()?;
|
||||
sink.pcm(0, [9; PCM_BYTES])
|
||||
}).unwrap();
|
||||
while !capture.is_finished() { std::thread::yield_now(); }
|
||||
assert_eq!(capture.dispatch_pending(|_| cancel.cancel()), 1);
|
||||
capture.join().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn missing_consumer_fails_without_blocking() {
|
||||
let (tx, rx) = mpsc::sync_channel(EVENT_CAPACITY);
|
||||
drop(rx);
|
||||
let sink = Sink(tx);
|
||||
assert!(sink.format().is_err());
|
||||
assert!(sink.pcm(0, [0; PCM_BYTES]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn drop_cancels_and_joins_worker() {
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
let completed = finished.clone();
|
||||
let capture = spawn_capture(Cancellation::default(), move |cancel, _| {
|
||||
while !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(1)); }
|
||||
completed.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}).unwrap();
|
||||
drop(capture);
|
||||
assert!(finished.load(Ordering::Acquire));
|
||||
}
|
||||
#[test]
|
||||
fn worker_errors_and_panics_are_joined() {
|
||||
let capture = spawn_capture(Cancellation::default(), |_, _| Err("source ended".into())).unwrap();
|
||||
assert_eq!(capture.join().unwrap_err(), "source ended");
|
||||
let capture = spawn_capture(Cancellation::default(), |_, _| panic!("fixture")).unwrap();
|
||||
assert_eq!(capture.join().unwrap_err(), "Application audio worker panicked");
|
||||
}
|
||||
#[test]
|
||||
fn cancelled_enumeration_does_not_access_platform() {
|
||||
let cancel = Cancellation::default();
|
||||
cancel.cancel();
|
||||
assert!(list(&cancel).is_err());
|
||||
assert!(capture("not-observed", cancel).is_err());
|
||||
}
|
||||
}
|
||||
+150
-80
@@ -2,11 +2,11 @@
|
||||
//! Runtime prerequisites: pactl with JSON output and parec with --monitor-stream.
|
||||
//! No sink moves, volume changes, defaults, modules or persistent graph edits.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use super::{Cancellation, Sink};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -15,9 +15,26 @@ const MAX_JSON: u64 = 4 * 1024 * 1024;
|
||||
const TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const PREREQUISITE: &str = "Linux application audio requires pactl JSON support, parec --monitor-stream, and an accessible PulseAudio or PipeWire-Pulse user audio server with recording permission; native PipeWire without pipewire-pulse is not supported by this backend";
|
||||
|
||||
struct OwnedChild(Child);
|
||||
struct OwnedChild {
|
||||
child: Child,
|
||||
readers: Vec<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
impl OwnedChild {
|
||||
fn new(child: Child) -> Self { Self { child, readers: Vec::new() } }
|
||||
}
|
||||
impl Drop for OwnedChild {
|
||||
fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); }
|
||||
fn drop(&mut self) {
|
||||
// Only these exact helper children are terminated. Killing before joining
|
||||
// releases blocking pipe reads, including early-return and panic paths.
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
for reader in self.readers.drain(..) { let _ = reader.join(); }
|
||||
}
|
||||
}
|
||||
|
||||
struct EndForwarding(Arc<AtomicBool>);
|
||||
impl Drop for EndForwarding {
|
||||
fn drop(&mut self) { self.0.store(true, Ordering::Release); }
|
||||
}
|
||||
|
||||
fn command(program: &str) -> Command {
|
||||
@@ -29,7 +46,7 @@ fn command(program: &str) -> Command {
|
||||
unsafe extern "C" { fn prctl(option: i32, ...) -> i32; fn getppid() -> i32; }
|
||||
let parent = std::process::id() as i32;
|
||||
unsafe { command.pre_exec(move || {
|
||||
// Kill our subprocess if the helper is forcibly terminated by Electron.
|
||||
// Kill this owned subprocess if its native/CLI host is forcibly terminated.
|
||||
if prctl(1, 15, 0, 0, 0) != 0 || getppid() != parent { return Err(std::io::Error::last_os_error()); }
|
||||
Ok(())
|
||||
}); }
|
||||
@@ -37,30 +54,46 @@ fn command(program: &str) -> Command {
|
||||
command
|
||||
}
|
||||
|
||||
fn output(program: &str, args: &[&str]) -> Result<Vec<u8>, String> {
|
||||
let mut child = OwnedChild(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
|
||||
let stdout = child.0.stdout.take().ok_or("Missing command stdout")?;
|
||||
fn output(program: &str, args: &[&str], cancel: &Cancellation) -> Result<Vec<u8>, String> {
|
||||
cancel.check()?;
|
||||
let child = OwnedChild::new(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
|
||||
collect_output(child, program, cancel)
|
||||
}
|
||||
|
||||
fn collect_output(mut child: OwnedChild, program: &str, cancel: &Cancellation) -> Result<Vec<u8>, String> {
|
||||
let stdout = child.child.stdout.take().ok_or("Missing command stdout")?;
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
std::thread::spawn(move || {
|
||||
child.readers.push(std::thread::Builder::new().name("app-audio-query".into()).spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
let result = stdout.take(MAX_JSON + 1).read_to_end(&mut bytes).map(|_| bytes);
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
}).map_err(|e| e.to_string())?);
|
||||
let start = Instant::now();
|
||||
let mut result = None;
|
||||
loop {
|
||||
if let Some(status) = child.0.try_wait().map_err(|e| e.to_string())? {
|
||||
cancel.check()?;
|
||||
if result.is_none() {
|
||||
match rx.try_recv() {
|
||||
Ok(bytes) => {
|
||||
let bytes = bytes.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
|
||||
result = Some(bytes);
|
||||
},
|
||||
Err(mpsc::TryRecvError::Empty) => {},
|
||||
Err(mpsc::TryRecvError::Disconnected) => return Err("Audio server output reader stopped".into()),
|
||||
}
|
||||
}
|
||||
if let Some(status) = child.child.try_wait().map_err(|e| e.to_string())? {
|
||||
if !status.success() { return Err(format!("{PREREQUISITE}: {program} exited with {status}")); }
|
||||
let bytes = rx.recv_timeout(TIMEOUT).map_err(|_| "Audio server output timed out")?.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
|
||||
return Ok(bytes);
|
||||
if let Some(bytes) = result { return Ok(bytes); }
|
||||
}
|
||||
if start.elapsed() >= TIMEOUT { return Err(format!("{program}: audio server timeout")); }
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(kind: &str) -> Result<Vec<Value>, String> {
|
||||
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind])?).map_err(|e| format!("pactl JSON: {e}"))
|
||||
fn rows(kind: &str, cancel: &Cancellation) -> Result<Vec<Value>, String> {
|
||||
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind], cancel)?).map_err(|e| format!("pactl JSON: {e}"))
|
||||
}
|
||||
fn number(value: &Value) -> Option<u64> { value.as_u64().or_else(|| value.as_str()?.parse().ok()) }
|
||||
fn process_stat(text: &str) -> Option<(u32, u64)> {
|
||||
@@ -101,9 +134,9 @@ fn application(row: &Value, sinks: &[Value], start_time: u64, ancestors: Vec<u32
|
||||
})
|
||||
}
|
||||
|
||||
fn applications() -> Result<Vec<Application>, String> {
|
||||
let sinks = rows("sinks")?;
|
||||
let streams = rows("sink-inputs")?;
|
||||
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
|
||||
let sinks = rows("sinks", cancel)?;
|
||||
let streams = rows("sink-inputs", cancel)?;
|
||||
let mut result = Vec::new();
|
||||
for row in streams {
|
||||
let Some(pid) = number(&row["properties"]["application.process.id"]).and_then(|p| u32::try_from(p).ok()) else { continue };
|
||||
@@ -119,114 +152,151 @@ fn applications() -> Result<Vec<Application>, String> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn prerequisites() -> Result<(), String> {
|
||||
let help = output("parec", &["--help"])?;
|
||||
fn prerequisites(cancel: &Cancellation) -> Result<(), String> {
|
||||
let help = output("parec", &["--help"], cancel)?;
|
||||
if !String::from_utf8_lossy(&help).contains("--monitor-stream") { return Err(PREREQUISITE.into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn list() -> Result<(), String> {
|
||||
let result = prerequisites().and_then(|_| applications());
|
||||
match result {
|
||||
Ok(apps) => println!("{}", json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps})),
|
||||
Err(reason) => println!("{}", json!({"supported":false,"platform":"linux","reason":reason,"applications":[]})),
|
||||
}
|
||||
Ok(())
|
||||
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
|
||||
let result = prerequisites(cancel).and_then(|_| applications(cancel));
|
||||
cancel.check()?;
|
||||
Ok(match result {
|
||||
Ok(apps) => json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps}),
|
||||
Err(reason) => json!({"supported":false,"platform":"linux","reason":reason,"applications":[]}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn capture(id: &str) -> Result<(), String> {
|
||||
prerequisites()?;
|
||||
let app = applications()?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let requested = Arc::new(AtomicBool::new(false));
|
||||
let request = requested.clone();
|
||||
let cancel = stop.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = std::io::stdin().read(&mut [0; 1]);
|
||||
request.store(true, Ordering::Release);
|
||||
cancel.store(true, Ordering::Release);
|
||||
});
|
||||
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
|
||||
match capture_inner(id, cancel, sink) {
|
||||
Err(_) if cancel.is_cancelled() => Ok(()),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
|
||||
prerequisites(cancel)?;
|
||||
let app = applications(cancel)?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
|
||||
// Monitor removal/change before starting capture. Any selected-stream change fails closed.
|
||||
let mut subscription = OwnedChild(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
|
||||
let subscription_out = subscription.0.stdout.take().ok_or("Missing subscription stdout")?;
|
||||
let mut subscription = OwnedChild::new(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
|
||||
let subscription_out = subscription.child.stdout.take().ok_or("Missing subscription stdout")?;
|
||||
let changed = Arc::new(AtomicBool::new(false));
|
||||
let changed_reader = changed.clone();
|
||||
let target = format!("on sink-input #{}", app.index);
|
||||
std::thread::spawn(move || {
|
||||
subscription.readers.push(std::thread::Builder::new().name("app-audio-subscribe".into()).spawn(move || {
|
||||
use std::io::BufRead;
|
||||
let mut reader = std::io::BufReader::new(subscription_out);
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
match reader.by_ref().take(4097).read_line(&mut line) {
|
||||
Ok(n) if n > 0 && n <= 4096 => {
|
||||
if line.trim_end().ends_with(&target) { changed_reader.store(true, Ordering::Release); break; }
|
||||
if line.trim_end().ends_with(&target) { break; }
|
||||
},
|
||||
_ => { changed_reader.store(true, Ordering::Release); break; }
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
changed_reader.store(true, Ordering::Release);
|
||||
}).map_err(|e| e.to_string())?);
|
||||
let monitor_arg = format!("--device={}", app.monitor);
|
||||
let index_arg = format!("--monitor-stream={}", app.index);
|
||||
let mut recorder = OwnedChild(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
|
||||
cancel.check()?;
|
||||
let mut recorder = OwnedChild::new(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
|
||||
// Re-enumerate before forwarding anything: never use a recycled or moved stream index.
|
||||
if !applications()?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
|
||||
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
|
||||
return Err("Selected audio stream changed during activation".into());
|
||||
}
|
||||
let mut pcm = recorder.0.stdout.take().ok_or("Missing recorder stdout")?;
|
||||
let (tx, rx) = mpsc::sync_channel::<(u64, [u8; BYTES])>(4);
|
||||
let cancel = stop.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut pcm = recorder.child.stdout.take().ok_or("Missing recorder stdout")?;
|
||||
sink.format()?;
|
||||
let pcm_sink = sink.clone();
|
||||
let pcm_changed = changed.clone();
|
||||
let requested = cancel.clone();
|
||||
recorder.readers.push(std::thread::Builder::new().name("app-audio-read".into()).spawn(move || {
|
||||
let mut sequence = 0;
|
||||
while !cancel.load(Ordering::Acquire) {
|
||||
while !requested.is_cancelled() && !pcm_changed.load(Ordering::Acquire) {
|
||||
let mut block = [0; BYTES];
|
||||
if pcm.read_exact(&mut block).is_err() { break; }
|
||||
let _ = tx.try_send((sequence, block));
|
||||
if requested.is_cancelled() || pcm_changed.load(Ordering::Acquire) { break; }
|
||||
if pcm_sink.pcm(sequence, block).is_err() { break; }
|
||||
sequence += 1;
|
||||
}
|
||||
cancel.store(true, Ordering::Release);
|
||||
});
|
||||
let writer_stop = stop.clone();
|
||||
let writer_changed = changed.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
let mut encoded = String::with_capacity(BYTES * 4 / 3);
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}")?;
|
||||
stdout.flush()?;
|
||||
while let Ok((sequence, block)) = rx.recv() {
|
||||
if writer_stop.load(Ordering::Acquire) || writer_changed.load(Ordering::Acquire) { break; }
|
||||
encoded.clear(); STANDARD.encode_string(block, &mut encoded);
|
||||
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")?;
|
||||
stdout.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() { writer_stop.store(true, Ordering::Release); }
|
||||
});
|
||||
}).map_err(|e| e.to_string())?);
|
||||
let _end_forwarding = EndForwarding(changed.clone());
|
||||
let mut checked = Instant::now();
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
if changed.load(Ordering::Acquire) { return Err("Selected audio stream changed or disappeared".into()); }
|
||||
if recorder.0.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
|
||||
while !cancel.is_cancelled() {
|
||||
if changed.load(Ordering::Acquire) || subscription.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected audio stream changed or disappeared".into()); }
|
||||
if recorder.child.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
|
||||
if checked.elapsed() >= Duration::from_millis(250) {
|
||||
if !applications()?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
|
||||
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
|
||||
checked = Instant::now();
|
||||
}
|
||||
if recorder.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected application PCM transport stopped".into()); }
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
if !requested.load(Ordering::Acquire) { return Err("Selected application PCM transport stopped".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn blocking_child() -> OwnedChild {
|
||||
let (program, prefix) = crate::test_exec::self_invocation();
|
||||
OwnedChild::new(command(&program).args(prefix)
|
||||
.args(["app_audio_blocking_child_fixture", "--nocapture", "--test-threads=1"])
|
||||
.env("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE", "1").spawn().unwrap())
|
||||
}
|
||||
#[test]
|
||||
fn app_audio_blocking_child_fixture() {
|
||||
if std::env::var_os("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE").is_none() { return; }
|
||||
use std::io::Write;
|
||||
println!("APP_AUDIO_CHILD_READY");
|
||||
std::io::stdout().flush().unwrap();
|
||||
std::thread::sleep(Duration::from_secs(30));
|
||||
}
|
||||
#[test]
|
||||
fn dropping_child_unblocks_and_joins_pipe_reader() {
|
||||
use std::io::BufRead;
|
||||
let mut child = blocking_child();
|
||||
let stdout = child.child.stdout.take().unwrap();
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
let completed = finished.clone();
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
||||
child.readers.push(std::thread::spawn(move || {
|
||||
let mut reader = std::io::BufReader::new(stdout);
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).unwrap_or(0) != 0 {
|
||||
if line.contains("APP_AUDIO_CHILD_READY") { let _ = ready_tx.try_send(()); }
|
||||
line.clear();
|
||||
}
|
||||
completed.store(true, Ordering::Release);
|
||||
}));
|
||||
ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
let start = Instant::now();
|
||||
drop(child);
|
||||
assert!(finished.load(Ordering::Acquire));
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_interrupts_blocked_helper_output() {
|
||||
let child = blocking_child();
|
||||
let cancel = Cancellation::default();
|
||||
let requested = cancel.clone();
|
||||
let canceller = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
requested.cancel();
|
||||
});
|
||||
let start = Instant::now();
|
||||
let result = collect_output(child, "fixture", &cancel);
|
||||
canceller.join().unwrap();
|
||||
assert_eq!(result.unwrap_err(), "Application audio cancelled");
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn controlled_executable_output_and_failure() {
|
||||
let (program, prefix) = crate::test_exec::self_invocation();
|
||||
let run = |option: &'static str| {
|
||||
let mut args: Vec<&str> = prefix.iter().map(String::as_str).collect();
|
||||
args.push(option);
|
||||
output(&program, &args)
|
||||
output(&program, &args, &Cancellation::default())
|
||||
};
|
||||
let data = run("--list").unwrap();
|
||||
assert!(String::from_utf8(data).unwrap().contains("identity_uses_start_time_serial_and_exact_monitor"));
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
//! Activation follows Microsoft's ApplicationLoopback sample; COM bindings are windows-rs.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
|
||||
use std::time::Duration;
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use std::sync::mpsc;
|
||||
use super::{Cancellation, Sink};
|
||||
use std::time::{Duration, Instant};
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use windows::core::{implement, Interface, HRESULT, PCWSTR, PWSTR};
|
||||
@@ -20,7 +19,6 @@ use windows::Win32::System::Variant::VT_BLOB;
|
||||
|
||||
const FRAMES: usize = 960;
|
||||
const BYTES: usize = FRAMES * 2 * 2;
|
||||
const QUEUE: usize = 4;
|
||||
|
||||
#[link(name = "ntdll")]
|
||||
extern "system" { fn RtlGetVersion(version: *mut OSVERSIONINFOW) -> i32; }
|
||||
@@ -69,13 +67,14 @@ fn process(pid: u32) -> Result<(Handle, String, String), String> {
|
||||
Ok((h, format!("{pid}:{time:016x}"), label))
|
||||
}
|
||||
|
||||
fn parents() -> Result<BTreeMap<u32, u32>, String> {
|
||||
fn parents(cancel: &Cancellation) -> Result<BTreeMap<u32, u32>, String> {
|
||||
let snapshot = Handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.map_err(error)?);
|
||||
let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
|
||||
let mut result = BTreeMap::new();
|
||||
unsafe {
|
||||
Process32FirstW(snapshot.0, &mut entry).map_err(error)?;
|
||||
loop {
|
||||
cancel.check()?;
|
||||
result.insert(entry.th32ProcessID, entry.th32ParentProcessID);
|
||||
if Process32NextW(snapshot.0, &mut entry).is_err() { break; }
|
||||
}
|
||||
@@ -83,18 +82,20 @@ fn parents() -> Result<BTreeMap<u32, u32>, String> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn applications() -> Result<Vec<Application>, String> {
|
||||
let tree = parents()?;
|
||||
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
|
||||
let tree = parents(cancel)?;
|
||||
let mut ids = BTreeSet::new();
|
||||
unsafe {
|
||||
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(error)?;
|
||||
let devices = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(error)?;
|
||||
for index in 0..devices.GetCount().map_err(error)? {
|
||||
cancel.check()?;
|
||||
let device = devices.Item(index).map_err(error)?;
|
||||
// A disappearing endpoint must not silently turn enumeration into an all-system selection.
|
||||
let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None).map_err(error)?;
|
||||
let sessions = manager.GetSessionEnumerator().map_err(error)?;
|
||||
for index in 0..sessions.GetCount().map_err(error)? {
|
||||
cancel.check()?;
|
||||
let session = sessions.GetSession(index).map_err(error)?;
|
||||
if session.GetState().map_err(error)? == AudioSessionStateExpired { continue; }
|
||||
let session: IAudioSessionControl2 = session.cast().map_err(error)?;
|
||||
@@ -105,6 +106,7 @@ fn applications() -> Result<Vec<Application>, String> {
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
for pid in ids {
|
||||
cancel.check()?;
|
||||
// Inaccessible/protected/exited processes are not selectable.
|
||||
let Ok((_handle, id, label)) = process(pid) else { continue };
|
||||
let mut ancestors = Vec::new();
|
||||
@@ -119,13 +121,13 @@ fn applications() -> Result<Vec<Application>, String> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn list() -> Result<(), String> {
|
||||
pub fn list(cancel: &Cancellation) -> Result<serde_json::Value, String> {
|
||||
cancel.check()?;
|
||||
if !supported() {
|
||||
println!("{}", json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
|
||||
return Ok(());
|
||||
return Ok(json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
|
||||
}
|
||||
let _com = Com::new()?;
|
||||
let tree = parents()?;
|
||||
let tree = parents(cancel)?;
|
||||
let mut host_ancestors = Vec::new();
|
||||
let mut current = std::process::id();
|
||||
while let Some(&parent) = tree.get(¤t) {
|
||||
@@ -133,8 +135,9 @@ pub fn list() -> Result<(), String> {
|
||||
host_ancestors.push(parent);
|
||||
current = parent;
|
||||
}
|
||||
println!("{}", json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":applications()?}));
|
||||
Ok(())
|
||||
let apps = applications(cancel)?;
|
||||
cancel.check()?;
|
||||
Ok(json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":apps}))
|
||||
}
|
||||
|
||||
#[implement(IActivateAudioInterfaceCompletionHandler)]
|
||||
@@ -150,7 +153,7 @@ impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(pid: u32) -> Result<IAudioClient, String> {
|
||||
fn activate(pid: u32, cancel: &Cancellation) -> Result<IAudioClient, String> {
|
||||
let mut params = Box::new(AUDIOCLIENT_ACTIVATION_PARAMS {
|
||||
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
|
||||
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
|
||||
@@ -168,7 +171,15 @@ fn activate(pid: u32) -> Result<IAudioClient, String> {
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
let completion: IActivateAudioInterfaceCompletionHandler = Completion { tx, _params: params }.into();
|
||||
let operation = unsafe { ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&*variant), &completion) }.map_err(error)?;
|
||||
rx.recv_timeout(Duration::from_secs(10)).map_err(|_| "Application audio activation timed out".to_owned())?;
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
cancel.check()?;
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(()) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) if start.elapsed() < Duration::from_secs(10) => {},
|
||||
_ => return Err("Application audio activation timed out".into()),
|
||||
}
|
||||
}
|
||||
let mut status = HRESULT(0);
|
||||
let mut object = None;
|
||||
unsafe { operation.GetActivateResult(&mut status, &mut object) }.map_err(error)?;
|
||||
@@ -176,15 +187,24 @@ fn activate(pid: u32) -> Result<IAudioClient, String> {
|
||||
object.ok_or("Application audio activation returned no interface")?.cast().map_err(error)
|
||||
}
|
||||
|
||||
struct Packet { sequence: u64, bytes: Box<[u8; BYTES]> }
|
||||
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
|
||||
match capture_inner(id, cancel, sink) {
|
||||
Err(_) if cancel.is_cancelled() => Ok(()),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capture(id: &str) -> Result<(), String> {
|
||||
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
|
||||
if cancel.is_cancelled() { return Ok(()); }
|
||||
if !supported() { return Err("WASAPI process-loopback requires Windows build 20348 or later".into()); }
|
||||
let _com = Com::new()?;
|
||||
let app = applications()?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
|
||||
let app = applications(cancel)?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
|
||||
let (target, current_id, _) = process(app.pid)?;
|
||||
if current_id != id { return Err("Selected application identity changed before capture".into()); }
|
||||
let client = activate(app.pid)?;
|
||||
let client = match activate(app.pid, cancel) {
|
||||
Err(_) if cancel.is_cancelled() => return Ok(()),
|
||||
result => result?,
|
||||
};
|
||||
// Recheck after asynchronous activation; never start an audio client for a recycled PID.
|
||||
let (_recheck, current_id, _) = process(app.pid)?;
|
||||
if current_id != id || unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT {
|
||||
@@ -195,45 +215,19 @@ pub fn capture(id: &str) -> Result<(), String> {
|
||||
let event = Handle(unsafe { CreateEventW(None, false, false, PCWSTR::null()) }.map_err(error)?);
|
||||
unsafe { client.SetEventHandle(event.0) }.map_err(error)?;
|
||||
let reader: IAudioCaptureClient = unsafe { client.GetService() }.map_err(error)?;
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let stop = stopped.clone();
|
||||
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
|
||||
let _ = std::io::stdin().read(&mut [0u8; 1]);
|
||||
stop.store(true, Ordering::Release);
|
||||
}).map_err(|e| e.to_string())?;
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel::<Packet>(QUEUE);
|
||||
let (free_tx, free_rx) = mpsc::sync_channel::<Box<[u8; BYTES]>>(QUEUE + 2);
|
||||
for _ in 0..QUEUE + 2 { free_tx.send(Box::new([0; BYTES])).map_err(|e| e.to_string())?; }
|
||||
let free_return = free_tx.clone();
|
||||
if cancel.is_cancelled() { return Ok(()); }
|
||||
unsafe { client.Start() }.map_err(error)?;
|
||||
let _started = Started(client);
|
||||
let stop = stopped.clone();
|
||||
std::thread::Builder::new().name("app-audio-pcm".into()).spawn(move || {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
let mut encoded = String::with_capacity(BYTES * 4 / 3);
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}")?;
|
||||
stdout.flush()?;
|
||||
while let Ok(packet) = ready_rx.recv() {
|
||||
encoded.clear();
|
||||
STANDARD.encode_string(packet.bytes.as_ref(), &mut encoded);
|
||||
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{},\"pcm\":\"{}\"}}", packet.sequence, encoded)?;
|
||||
stdout.flush()?;
|
||||
let _ = free_tx.try_send(packet.bytes);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() { stop.store(true, Ordering::Release); }
|
||||
}).map_err(|e| e.to_string())?;
|
||||
let mut block = free_rx.recv().map_err(|e| e.to_string())?;
|
||||
sink.format()?;
|
||||
let mut block = [0u8; BYTES];
|
||||
let mut used = 0;
|
||||
let mut sequence = 0;
|
||||
while !stopped.load(Ordering::Acquire) {
|
||||
while !cancel.is_cancelled() {
|
||||
if unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT { return Err("Selected application exited".into()); }
|
||||
let wait = unsafe { WaitForSingleObject(event.0, 50) };
|
||||
if wait == WAIT_TIMEOUT { continue; }
|
||||
if wait != WAIT_OBJECT_0 { return Err("Application audio capture event failed".into()); }
|
||||
while unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
|
||||
while !cancel.is_cancelled() && unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
|
||||
let mut data = std::ptr::null_mut();
|
||||
let mut frames = 0;
|
||||
let mut flags = 0;
|
||||
@@ -253,12 +247,10 @@ pub fn capture(id: &str) -> Result<(), String> {
|
||||
used += count;
|
||||
offset += count;
|
||||
if used == BYTES {
|
||||
if let Ok(next) = free_rx.try_recv() {
|
||||
let packet = Packet { sequence, bytes: std::mem::replace(&mut block, next) };
|
||||
if let Err(e) = ready_tx.try_send(packet) {
|
||||
// Recover the unsent buffer without allocation; a full queue drops this interval.
|
||||
let packet = match e { mpsc::TrySendError::Full(p) | mpsc::TrySendError::Disconnected(p) => p };
|
||||
let _ = free_return.try_send(packet.bytes);
|
||||
if !cancel.is_cancelled() {
|
||||
if let Err(message) = sink.pcm(sequence, block) {
|
||||
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
|
||||
return Err(message);
|
||||
}
|
||||
}
|
||||
used = 0;
|
||||
|
||||
+250
-44
@@ -4,6 +4,7 @@
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use audiopus::coder::Encoder;
|
||||
use audiopus::{Application, Bitrate, Channels, SampleRate};
|
||||
@@ -23,25 +24,38 @@ const MAX_OPUS_PACKET: usize = 1275;
|
||||
|
||||
// ---------------------------------------------------------------- input queue
|
||||
|
||||
/// A capture-clock-stamped frame. Producers retain these tags through DSP and VAD;
|
||||
/// a device callback must hand PCM to a worker rather than lock this queue itself.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CapturedFrame {
|
||||
pub pcm: Frame,
|
||||
pub captured_at: Instant,
|
||||
pub connection_generation: u64,
|
||||
pub capture_epoch: u64,
|
||||
/// A whisper frame may only use this registered whisper route, never normal voice.
|
||||
pub whisper: Option<u32>,
|
||||
}
|
||||
|
||||
pub enum AudioIn {
|
||||
/// Captured for ordinary voice to the own channel.
|
||||
Frame(Box<Frame>),
|
||||
/// Captured while a whisper key was held: may only be sent to the whisper target registered under
|
||||
/// exactly this epoch (`whisper_start`), never as ordinary voice.
|
||||
Whisper(Box<Frame>, u32),
|
||||
Frame(CapturedFrame),
|
||||
End,
|
||||
}
|
||||
|
||||
impl AudioIn {
|
||||
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_) | AudioIn::Whisper(..)) }
|
||||
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_)) }
|
||||
}
|
||||
|
||||
/// Bounded single-consumer queue between the stdin reader and the session; drops the oldest
|
||||
/// frame when full.
|
||||
/// Capture age is checked both on ingress and immediately before encoding/sending.
|
||||
pub const MAX_CAPTURE_AGE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Bounded single-consumer queue between capture/DSP workers and the session.
|
||||
/// The mutex also serializes synchronous network enqueue against invalidation.
|
||||
pub struct AudioInQueue {
|
||||
items: Mutex<VecDeque<AudioIn>>,
|
||||
notify: Notify,
|
||||
dropped: AtomicU64,
|
||||
capture_epoch: AtomicU64,
|
||||
connection_generation: AtomicU64,
|
||||
}
|
||||
|
||||
/// Upper bound of queued entries: at most [`TX_QUEUE_FRAMES`] frames, and End markers are never
|
||||
@@ -54,37 +68,103 @@ impl AudioInQueue {
|
||||
items: Mutex::new(VecDeque::with_capacity(TX_QUEUE_ENTRIES)),
|
||||
notify: Notify::new(),
|
||||
dropped: AtomicU64::new(0),
|
||||
capture_epoch: AtomicU64::new(1),
|
||||
connection_generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&self, item: AudioIn) {
|
||||
pub fn epoch(&self) -> u64 { self.capture_epoch.load(Ordering::Acquire) }
|
||||
|
||||
pub fn generation(&self) -> u64 { self.connection_generation.load(Ordering::Acquire) }
|
||||
|
||||
/// A preliminary check, not a send permit. Use `with_valid_frame` for network enqueue.
|
||||
pub fn validate(&self, frame: &CapturedFrame) -> bool {
|
||||
self.validate_at(frame, Instant::now())
|
||||
}
|
||||
|
||||
fn validate_at(&self, frame: &CapturedFrame, now: Instant) -> bool {
|
||||
frame.capture_epoch == self.epoch()
|
||||
&& frame.connection_generation == self.generation()
|
||||
&& now.checked_duration_since(frame.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
|
||||
}
|
||||
|
||||
/// Execute encoding and synchronous network enqueue while invalidation is excluded.
|
||||
/// Never await, block on network, or call queue-mutating methods in `send`.
|
||||
/// Recheck `validate(frame)` after encoding, immediately before network enqueue:
|
||||
/// encoding can itself exhaust the capture-age limit. Release this guard before
|
||||
/// asynchronous error reporting. Once invalidation returns no old send can start.
|
||||
pub fn with_valid_frame<R>(&self, frame: &CapturedFrame, send: impl FnOnce() -> R) -> Option<R> {
|
||||
let _guard = self.items.lock().expect("audio queue poisoned");
|
||||
self.validate(frame).then(send)
|
||||
}
|
||||
|
||||
fn invalidate_locked(&self, q: &mut VecDeque<AudioIn>) -> u64 {
|
||||
let epoch = self.epoch().checked_add(1).expect("capture epoch exhausted");
|
||||
self.capture_epoch.store(epoch, Ordering::Release);
|
||||
q.clear();
|
||||
// The consumer must also stop its encoder/VAD burst, even if no PCM remains.
|
||||
q.push_back(AudioIn::End);
|
||||
epoch
|
||||
}
|
||||
|
||||
/// Revoke queued, dequeued and VAD-held frames and ask the consumer to end its burst.
|
||||
pub fn invalidate(&self) -> u64 {
|
||||
let epoch = {
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
self.invalidate_locked(&mut q)
|
||||
};
|
||||
self.notify.notify_one();
|
||||
epoch
|
||||
}
|
||||
|
||||
/// Every connection boundary revokes capture, including reapplying a generation.
|
||||
pub fn set_generation(&self, generation: u64) {
|
||||
{
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
match item {
|
||||
// Consecutive ends carry no extra information.
|
||||
AudioIn::End if matches!(q.back(), Some(AudioIn::End)) => {}
|
||||
AudioIn::End => q.push_back(item),
|
||||
AudioIn::Frame(_) | AudioIn::Whisper(..) => {
|
||||
let frames = q.iter().filter(|i| i.is_frame()).count();
|
||||
if frames >= TX_QUEUE_FRAMES {
|
||||
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
|
||||
q.remove(pos);
|
||||
self.dropped.fetch_add(1, Ordering::Relaxed);
|
||||
// Dropping a burst's only frame can leave two ends side by side.
|
||||
if pos > 0
|
||||
&& matches!(q.get(pos - 1), Some(AudioIn::End))
|
||||
&& matches!(q.get(pos), Some(AudioIn::End))
|
||||
{
|
||||
q.remove(pos);
|
||||
}
|
||||
}
|
||||
self.connection_generation.store(generation, Ordering::Release);
|
||||
self.invalidate_locked(&mut q);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
}
|
||||
|
||||
/// Reject expired or wrong-boundary frames without ever allocating per frame.
|
||||
pub fn try_push(&self, frame: CapturedFrame) -> bool {
|
||||
{
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
if !self.validate(&frame) { return false; }
|
||||
let frames = q.iter().filter(|i| i.is_frame()).count();
|
||||
if frames >= TX_QUEUE_FRAMES {
|
||||
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
|
||||
q.remove(pos);
|
||||
self.dropped.fetch_add(1, Ordering::Relaxed);
|
||||
// Removing a burst's only frame can leave adjacent ends.
|
||||
if pos > 0
|
||||
&& matches!(q.get(pos - 1), Some(AudioIn::End))
|
||||
&& matches!(q.get(pos), Some(AudioIn::End))
|
||||
{
|
||||
q.remove(pos);
|
||||
}
|
||||
q.push_back(item);
|
||||
}
|
||||
}
|
||||
q.push_back(AudioIn::Frame(frame));
|
||||
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn push(&self, item: AudioIn) {
|
||||
match item {
|
||||
AudioIn::Frame(frame) => { self.try_push(frame); }
|
||||
AudioIn::End => {
|
||||
{
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
if !matches!(q.back(), Some(AudioIn::End)) { q.push_back(AudioIn::End); }
|
||||
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -92,8 +172,8 @@ impl AudioInQueue {
|
||||
|
||||
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
|
||||
|
||||
/// Discards everything queued, e.g. frames captured under a previous transmit mode. Returns the number
|
||||
/// of discarded frames (not counted as overflow drops).
|
||||
/// Discard queued entries without revoking dequeued frames. Privacy/routing
|
||||
/// boundaries must use `invalidate` instead. Overflow statistics are unchanged.
|
||||
pub fn clear(&self) -> usize {
|
||||
let mut q = self.items.lock().expect("audio queue poisoned");
|
||||
let frames = q.iter().filter(|i| i.is_frame()).count();
|
||||
@@ -107,6 +187,18 @@ impl AudioInQueue {
|
||||
pub fn take_dropped(&self) -> u64 { self.dropped.swap(0, Ordering::Relaxed) }
|
||||
}
|
||||
|
||||
impl tsclientlib::AudioSendGuard for AudioInQueue {
|
||||
fn with_valid_audio(&self, metadata: &tsclientlib::AudioSendMetadata, send: &mut dyn FnMut()) {
|
||||
let _guard = self.items.lock().expect("audio queue poisoned");
|
||||
if metadata.capture_epoch == self.epoch()
|
||||
&& metadata.connection_generation == self.generation()
|
||||
&& Instant::now().checked_duration_since(metadata.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
|
||||
{
|
||||
send();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- transmit
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -544,7 +636,7 @@ mod tests {
|
||||
fn clear_discards_queued_frames_without_counting_drops() {
|
||||
let q = AudioInQueue::new();
|
||||
for _ in 0..3 {
|
||||
q.push(AudioIn::Frame(Box::new([1; FRAME_SAMPLES])));
|
||||
q.push(AudioIn::Frame(captured(&q, 1)));
|
||||
}
|
||||
q.push(AudioIn::End);
|
||||
assert_eq!(q.clear(), 3);
|
||||
@@ -710,10 +802,16 @@ mod tests {
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
fn frame(tag: i16) -> AudioIn {
|
||||
let mut f = Box::new([0i16; FRAME_SAMPLES]);
|
||||
f[0] = tag;
|
||||
AudioIn::Frame(f)
|
||||
fn captured(q: &AudioInQueue, tag: i16) -> CapturedFrame {
|
||||
let mut pcm = [0i16; FRAME_SAMPLES];
|
||||
pcm[0] = tag;
|
||||
CapturedFrame {
|
||||
pcm,
|
||||
captured_at: Instant::now(),
|
||||
connection_generation: q.generation(),
|
||||
capture_epoch: q.epoch(),
|
||||
whisper: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -723,13 +821,13 @@ mod tests {
|
||||
q.push(AudioIn::End);
|
||||
}
|
||||
assert_eq!(q.len(), 1);
|
||||
q.push(frame(1));
|
||||
q.push(AudioIn::Frame(captured(&q, 1)));
|
||||
for _ in 0..1000 {
|
||||
q.push(AudioIn::End);
|
||||
}
|
||||
assert_eq!(q.len(), 3);
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f[0] == 1));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f.pcm[0] == 1));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(q.pop().is_none());
|
||||
}
|
||||
@@ -738,7 +836,7 @@ mod tests {
|
||||
fn alternating_bursts_overflow_stays_bounded_and_terminated() {
|
||||
let q = AudioInQueue::new();
|
||||
for i in 0..500i16 {
|
||||
q.push(frame(i));
|
||||
q.push(AudioIn::Frame(captured(&q, i)));
|
||||
q.push(AudioIn::End);
|
||||
q.push(AudioIn::End);
|
||||
assert!(q.len() <= TX_QUEUE_ENTRIES, "len {}", q.len());
|
||||
@@ -751,7 +849,7 @@ mod tests {
|
||||
while let Some(item) = q.pop() {
|
||||
match item {
|
||||
AudioIn::Frame(f) => {
|
||||
frames.push(f[0]);
|
||||
frames.push(f.pcm[0]);
|
||||
prev_end = false;
|
||||
last_is_end = false;
|
||||
}
|
||||
@@ -760,13 +858,121 @@ mod tests {
|
||||
prev_end = true;
|
||||
last_is_end = true;
|
||||
}
|
||||
AudioIn::Whisper(_, _) => panic!("ordinary queue test received whisper"),
|
||||
}
|
||||
}
|
||||
assert!(last_is_end);
|
||||
assert_eq!(frames, (490..500).collect::<Vec<i16>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_age_is_inclusive_and_never_accepts_future_frames() {
|
||||
let q = AudioInQueue::new();
|
||||
let mut frame = captured(&q, 1);
|
||||
let now = frame.captured_at;
|
||||
assert!(q.validate_at(&frame, now));
|
||||
assert!(q.validate_at(&frame, now + MAX_CAPTURE_AGE));
|
||||
// Windows Instant arithmetic rounds to the performance-counter resolution, not nanoseconds.
|
||||
assert!(!q.validate_at(&frame, now + MAX_CAPTURE_AGE + Duration::from_millis(1)));
|
||||
assert!(!q.validate_at(&frame, now - Duration::from_millis(1)));
|
||||
frame.captured_at = Instant::now() - Duration::from_millis(600);
|
||||
assert!(!q.try_push(frame));
|
||||
let mut future = captured(&q, 2);
|
||||
future.captured_at += Duration::from_secs(60);
|
||||
assert!(!q.try_push(future));
|
||||
assert!(q.pop().is_none());
|
||||
assert_eq!(q.take_dropped(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidation_revokes_dequeued_frames_and_preserves_one_end() {
|
||||
let q = AudioInQueue::new();
|
||||
let frame = captured(&q, 7);
|
||||
assert!(q.try_push(frame.clone()));
|
||||
let Some(AudioIn::Frame(dequeued)) = q.pop() else { panic!("missing frame") };
|
||||
assert!(q.try_push(captured(&q, 8)));
|
||||
q.push(AudioIn::End);
|
||||
let epoch = q.invalidate();
|
||||
assert_eq!(epoch, frame.capture_epoch + 1);
|
||||
assert!(!q.validate(&dequeued));
|
||||
assert!(!q.try_push(frame));
|
||||
assert!(q.with_valid_frame(&dequeued, || panic!("revoked frame sent")).is_none());
|
||||
q.invalidate();
|
||||
q.push(AudioIn::End);
|
||||
assert_eq!(q.len(), 1);
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(q.try_push(captured(&q, 9)));
|
||||
assert!(matches!(q.pop(), Some(AudioIn::Frame(frame)) if frame.pcm[0] == 9));
|
||||
assert_eq!(q.take_dropped(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_boundary_revokes_epoch_and_rejects_wrong_tags() {
|
||||
let q = AudioInQueue::new();
|
||||
let old = captured(&q, 1);
|
||||
q.set_generation(7);
|
||||
assert_eq!(q.generation(), 7);
|
||||
assert_eq!(q.epoch(), old.capture_epoch + 1);
|
||||
assert!(!q.validate(&old));
|
||||
let mut wrong_generation = captured(&q, 2);
|
||||
wrong_generation.connection_generation = 6;
|
||||
assert!(!q.try_push(wrong_generation));
|
||||
let mut wrong_epoch = captured(&q, 3);
|
||||
wrong_epoch.capture_epoch += 1;
|
||||
assert!(!q.try_push(wrong_epoch));
|
||||
let epoch = q.epoch();
|
||||
q.set_generation(7);
|
||||
assert_eq!(q.epoch(), epoch + 1);
|
||||
assert!(matches!(q.pop(), Some(AudioIn::End)));
|
||||
assert!(q.pop().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whisper_envelope_survives_queue_without_normal_voice_fallback() {
|
||||
let q = AudioInQueue::new();
|
||||
let mut frame = captured(&q, 4);
|
||||
frame.whisper = Some(42);
|
||||
let captured_at = frame.captured_at;
|
||||
assert!(q.try_push(frame));
|
||||
let Some(AudioIn::Frame(frame)) = q.pop() else { panic!("missing whisper frame") };
|
||||
assert_eq!(frame.whisper, Some(42));
|
||||
assert_eq!(frame.captured_at, captured_at);
|
||||
assert_eq!(frame.pcm[0], 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_guard_serializes_invalidation_and_rechecks_capture_age() {
|
||||
let q = AudioInQueue::new();
|
||||
let frame = captured(&q, 1);
|
||||
let order = AtomicU64::new(0);
|
||||
std::thread::scope(|scope| {
|
||||
let q = &q;
|
||||
let frame = &frame;
|
||||
let order = ℴ
|
||||
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel();
|
||||
let sender = scope.spawn(move || {
|
||||
q.with_valid_frame(frame, || {
|
||||
assert!(q.items.try_lock().is_err(), "send must exclude invalidation");
|
||||
entered_tx.send(()).unwrap();
|
||||
release_rx.recv().unwrap();
|
||||
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 0);
|
||||
})
|
||||
});
|
||||
entered_rx.recv().unwrap();
|
||||
let invalidator = scope.spawn(move || {
|
||||
q.invalidate();
|
||||
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 1);
|
||||
});
|
||||
release_tx.send(()).unwrap();
|
||||
assert!(sender.join().unwrap().is_some());
|
||||
invalidator.join().unwrap();
|
||||
});
|
||||
assert!(q.with_valid_frame(&frame, || panic!("old send after invalidation")).is_none());
|
||||
let mut expired = captured(&q, 2);
|
||||
expired.captured_at -= Duration::from_millis(600);
|
||||
assert!(q.with_valid_frame(&expired, || panic!("expired frame encoded")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_rearms_unsupported_codec_report() {
|
||||
let mut rx = Receiver::new();
|
||||
@@ -784,14 +990,14 @@ mod tests {
|
||||
fn queue_drops_oldest_frames() {
|
||||
let q = AudioInQueue::new();
|
||||
for i in 0..(TX_QUEUE_FRAMES + 3) {
|
||||
let mut f = Box::new([0i16; FRAME_SAMPLES]);
|
||||
f[0] = i as i16;
|
||||
q.push(AudioIn::Frame(f));
|
||||
let mut pcm = [0i16; FRAME_SAMPLES];
|
||||
pcm[0] = i as i16;
|
||||
q.try_push(CapturedFrame { pcm, captured_at: Instant::now(), connection_generation: q.generation(), capture_epoch: q.epoch(), whisper: None });
|
||||
}
|
||||
q.push(AudioIn::End);
|
||||
assert_eq!(q.take_dropped(), 3);
|
||||
match q.pop() {
|
||||
Some(AudioIn::Frame(f)) => assert_eq!(f[0], 3),
|
||||
Some(AudioIn::Frame(f)) => assert_eq!(f.pcm[0], 3),
|
||||
_ => panic!(),
|
||||
}
|
||||
let mut n = 1;
|
||||
|
||||
+112
-74
@@ -238,23 +238,18 @@ fn channel(id: u64) -> Result<u64, ErrorObj> {
|
||||
if id == 0 { Err(bad("channel_id must be a channel (not 0)")) } else { Ok(id) }
|
||||
}
|
||||
|
||||
fn password(p: Option<String>) -> Result<String, ErrorObj> {
|
||||
let p = p.unwrap_or_default();
|
||||
fn check_password(p: &str) -> Result<(), ErrorObj> {
|
||||
if p.chars().count() > MAX_PASSWORD_CHARS || p.chars().any(char::is_control) {
|
||||
return Err(bad("channel_password is invalid"));
|
||||
}
|
||||
Ok(p)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn host_path(field: &str, p: &str) -> Result<PathBuf, ErrorObj> {
|
||||
if p.is_empty() || p.len() > 4096 || p.contains('\0') {
|
||||
return Err(bad(format!("{field} is invalid")));
|
||||
}
|
||||
let path = PathBuf::from(p);
|
||||
if !path.is_absolute() {
|
||||
return Err(bad(format!("{field} must be absolute")));
|
||||
}
|
||||
Ok(path)
|
||||
fn check_host_path(field: &str, path: &Path) -> Result<(), ErrorObj> {
|
||||
let p = path.to_str().ok_or_else(|| bad(format!("{field} is invalid")))?;
|
||||
if p.is_empty() || p.len() > 4096 || p.contains('\0') { return Err(bad(format!("{field} is invalid"))); }
|
||||
if !path.is_absolute() { return Err(bad(format!("{field} must be absolute"))); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Channel zero is reserved for the virtual server's icons (main-owned snapshots and icon manager),
|
||||
@@ -278,94 +273,90 @@ pub fn wire_name(channel_id: u64, path: &str) -> &str {
|
||||
|
||||
/// Parse a `file_*` bridge command.
|
||||
pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<Request, ErrorObj> {
|
||||
Ok(match name {
|
||||
let request = match name {
|
||||
"file_config" => {
|
||||
let a: ConfigArgs = args(raw)?;
|
||||
if a.download_slots > 9 || a.upload_slots > 9 || a.download_slots + a.upload_slots > 10
|
||||
|| a.download_limit > 26_843_545_600 || a.upload_limit > 26_843_545_600 {
|
||||
return Err(bad("invalid transfer scheduler limits"));
|
||||
}
|
||||
Request::Config { download_slots: a.download_slots, upload_slots: a.upload_slots, download_limit: a.download_limit, upload_limit: a.upload_limit }
|
||||
}
|
||||
"file_list" => {
|
||||
"file_list" | "file_mkdir" => {
|
||||
let a: PathArgs = args(raw)?;
|
||||
let path = remote_dir(&a.path)?;
|
||||
let channel_id = if a.channel_id == 0 && path == "/icons/" { 0 } else { channel(a.channel_id)? };
|
||||
Request::List { channel_id, path, password: password(a.channel_password)? }
|
||||
}
|
||||
"file_mkdir" => {
|
||||
let a: PathArgs = args(raw)?;
|
||||
Request::Mkdir { channel_id: channel(a.channel_id)?, path: remote_item(&a.path)?, password: password(a.channel_password)? }
|
||||
if name == "file_list" { Request::List { channel_id: a.channel_id, path: a.path, password: a.channel_password.unwrap_or_default() } }
|
||||
else { Request::Mkdir { channel_id: a.channel_id, path: a.path, password: a.channel_password.unwrap_or_default() } }
|
||||
}
|
||||
"file_rename" => {
|
||||
let a: RenameArgs = args(raw)?;
|
||||
let target = match (a.target_channel_id, a.target_channel_password) {
|
||||
(Some(id), pw) => Some((channel(id)?, password(pw)?)),
|
||||
(Some(id), pw) => Some((id, pw.unwrap_or_default())),
|
||||
(None, Some(_)) => return Err(bad("target_channel_password requires target_channel_id")),
|
||||
(None, None) => None,
|
||||
};
|
||||
let (from, to) = (remote_item(&a.from)?, remote_item(&a.to)?);
|
||||
if from == to && target.as_ref().is_none_or(|t| t.0 == a.channel_id) {
|
||||
return Err(bad("from and to are the same path"));
|
||||
}
|
||||
Request::Rename { channel_id: channel(a.channel_id)?, password: password(a.channel_password)?, from, to, target }
|
||||
Request::Rename { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), from: a.from, to: a.to, target }
|
||||
}
|
||||
"file_delete" => {
|
||||
let a: DeleteArgs = args(raw)?;
|
||||
if a.paths.is_empty() || a.paths.len() > MAX_DELETE {
|
||||
return Err(bad(format!("paths must hold 1-{MAX_DELETE} entries")));
|
||||
}
|
||||
let paths = a.paths.iter().map(|p| remote_item(p)).collect::<Result<Vec<_>, _>>()?;
|
||||
// Channel 0 deletes only server icons; every path must name one.
|
||||
let channel_id = if a.channel_id == 0 {
|
||||
for p in &paths { transfer_channel(0, p)?; }
|
||||
0
|
||||
} else { a.channel_id };
|
||||
Request::Delete { channel_id, password: password(a.channel_password)?, paths }
|
||||
Request::Delete { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), paths: a.paths }
|
||||
}
|
||||
"file_download" => {
|
||||
let a: DownloadArgs = args(raw)?;
|
||||
if a.subdirs.len() > MAX_SUBDIRS {
|
||||
return Err(bad("too many subdirs"));
|
||||
}
|
||||
for s in &a.subdirs {
|
||||
local_component(s)?;
|
||||
}
|
||||
let path = remote_item(&a.path)?;
|
||||
local_component(file_name(&path))?;
|
||||
Request::Download {
|
||||
channel_id: transfer_channel(a.channel_id, &path)?,
|
||||
password: password(a.channel_password)?,
|
||||
path,
|
||||
dest_dir: host_path("dest_dir", &a.dest_dir)?,
|
||||
subdirs: a.subdirs,
|
||||
overwrite: a.overwrite,
|
||||
}
|
||||
Request::Download { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), path: a.path,
|
||||
dest_dir: PathBuf::from(a.dest_dir), subdirs: a.subdirs, overwrite: a.overwrite }
|
||||
}
|
||||
"file_upload" => {
|
||||
let a: UploadArgs = args(raw)?;
|
||||
let path = remote_item(&a.path)?;
|
||||
Request::Upload {
|
||||
channel_id: transfer_channel(a.channel_id, &path)?,
|
||||
password: password(a.channel_password)?,
|
||||
path,
|
||||
source: host_path("source", &a.source)?,
|
||||
overwrite: a.overwrite,
|
||||
}
|
||||
Request::Upload { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), path: a.path,
|
||||
source: PathBuf::from(a.source), overwrite: a.overwrite }
|
||||
}
|
||||
"file_cancel" => Request::Cancel { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
|
||||
"file_pause" => Request::Pause { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
|
||||
"file_resume" => Request::Resume { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
|
||||
"file_fetch_image" => {
|
||||
let a: ImageArgs = args(raw)?;
|
||||
Request::FetchImage { channel_id: channel(a.channel_id)?, path: remote_item(&a.path)? }
|
||||
}
|
||||
"file_transfers" => {
|
||||
args::<Empty>(raw)?;
|
||||
Request::Transfers
|
||||
Request::FetchImage { channel_id: a.channel_id, path: a.path }
|
||||
}
|
||||
"file_transfers" => { args::<Empty>(raw)?; Request::Transfers }
|
||||
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other}"))),
|
||||
})
|
||||
};
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
pub(crate) fn validate(request: &mut Request) -> Result<(), ErrorObj> {
|
||||
match request {
|
||||
Request::Config { download_slots, upload_slots, download_limit, upload_limit } => {
|
||||
if *download_slots > 9 || *upload_slots > 9 || *download_slots + *upload_slots > 10
|
||||
|| *download_limit > 26_843_545_600 || *upload_limit > 26_843_545_600 { return Err(bad("invalid transfer scheduler limits")); }
|
||||
}
|
||||
Request::List { channel_id, path, password } => {
|
||||
check_remote_dir(path)?;
|
||||
if !path.ends_with('/') { path.push('/'); }
|
||||
if *channel_id != 0 || path.as_str() != "/icons/" { channel(*channel_id)?; }
|
||||
check_password(password)?;
|
||||
}
|
||||
Request::Mkdir { channel_id, path, password } => { channel(*channel_id)?; check_remote_item(path)?; check_password(password)?; }
|
||||
Request::Rename { channel_id, password, from, to, target } => {
|
||||
if let Some((id, pw)) = target { channel(*id)?; check_password(pw)?; }
|
||||
check_remote_item(from)?; check_remote_item(to)?;
|
||||
if from == to && target.as_ref().is_none_or(|t| t.0 == *channel_id) { return Err(bad("from and to are the same path")); }
|
||||
channel(*channel_id)?; check_password(password)?;
|
||||
}
|
||||
Request::Delete { channel_id, password, paths } => {
|
||||
if paths.is_empty() || paths.len() > MAX_DELETE { return Err(bad(format!("paths must hold 1-{MAX_DELETE} entries"))); }
|
||||
for path in paths { check_remote_item(path)?; transfer_channel(*channel_id, path)?; }
|
||||
check_password(password)?;
|
||||
}
|
||||
Request::Download { channel_id, password, path, dest_dir, subdirs, .. } => {
|
||||
if subdirs.len() > MAX_SUBDIRS { return Err(bad("too many subdirs")); }
|
||||
for subdir in subdirs { local_component(subdir)?; }
|
||||
check_remote_item(path)?; local_component(file_name(path))?;
|
||||
transfer_channel(*channel_id, path)?; check_password(password)?; check_host_path("dest_dir", dest_dir)?;
|
||||
}
|
||||
Request::Upload { channel_id, password, path, source, .. } => {
|
||||
check_remote_item(path)?; transfer_channel(*channel_id, path)?;
|
||||
check_password(password)?; check_host_path("source", source)?;
|
||||
}
|
||||
Request::FetchImage { channel_id, path } => { channel(*channel_id)?; check_remote_item(path)?; }
|
||||
Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ paths
|
||||
@@ -396,11 +387,16 @@ fn check_path_text(p: &str) -> Result<(), ErrorObj> {
|
||||
|
||||
/// Remote folder path, normalized to `/` or `/a/b/`.
|
||||
pub fn remote_dir(p: &str) -> Result<String, ErrorObj> {
|
||||
check_remote_dir(p)?;
|
||||
if p.ends_with('/') { Ok(p.to_owned()) } else { Ok(format!("{p}/")) }
|
||||
}
|
||||
|
||||
fn check_remote_dir(p: &str) -> Result<(), ErrorObj> {
|
||||
check_path_text(p)?;
|
||||
let inner = p.trim_start_matches('/').trim_end_matches('/');
|
||||
if inner.is_empty() {
|
||||
if p.chars().all(|c| c == '/') && p.len() == 1 {
|
||||
return Ok("/".into());
|
||||
return Ok(());
|
||||
}
|
||||
return Err(bad("remote path contains an empty component"));
|
||||
}
|
||||
@@ -410,11 +406,16 @@ pub fn remote_dir(p: &str) -> Result<String, ErrorObj> {
|
||||
for c in inner.split('/') {
|
||||
remote_component(c)?;
|
||||
}
|
||||
Ok(format!("/{inner}/"))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remote file or folder path `/a/b` (no trailing slash; not the root).
|
||||
pub fn remote_item(p: &str) -> Result<String, ErrorObj> {
|
||||
check_remote_item(p)?;
|
||||
Ok(p.to_owned())
|
||||
}
|
||||
|
||||
fn check_remote_item(p: &str) -> Result<(), ErrorObj> {
|
||||
check_path_text(p)?;
|
||||
let inner = &p[1..];
|
||||
if inner.is_empty() || inner.ends_with('/') {
|
||||
@@ -423,7 +424,7 @@ pub fn remote_item(p: &str) -> Result<String, ErrorObj> {
|
||||
for c in inner.split('/') {
|
||||
remote_component(c)?;
|
||||
}
|
||||
Ok(p.to_owned())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Last component of a validated remote item path.
|
||||
@@ -1479,6 +1480,43 @@ pub async fn upload(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(name: &str, raw: Option<&RawValue>) -> Result<Request, ErrorObj> {
|
||||
let mut request = super::parse(name, raw)?;
|
||||
validate(&mut request)?;
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_list_normalization_preserves_the_wire_path_boundary() {
|
||||
let path = format!("/{}/{}", "a".repeat(MAX_NAME_CHARS), "b".repeat(MAX_NAME_CHARS));
|
||||
assert_eq!(path.len(), MAX_PATH_CHARS);
|
||||
let command = crate::protocol::Command::Files(Request::List { channel_id: 7, path: path.clone(), password: String::new() });
|
||||
let validated = crate::protocol::validate_command(command).unwrap();
|
||||
let expected = crate::protocol::Command::Files(Request::List { channel_id: 7, path: format!("{path}/"), password: String::new() });
|
||||
assert_eq!(validated.into_inner(), expected);
|
||||
let line = serde_json::json!({"id":"boundary","cmd":"file_list","args":{"channel_id":7,"path":path}}).to_string();
|
||||
let crate::protocol::Input::Request { cmd, .. } = crate::protocol::parse_line(&line) else { panic!("valid boundary path rejected") };
|
||||
assert_eq!(cmd.into_inner(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_file_requests_reject_paths_passwords_and_unsafe_destinations() {
|
||||
let invalid = [
|
||||
Request::List { channel_id: 7, path: "/a//b".into(), password: String::new() },
|
||||
Request::Mkdir { channel_id: 7, path: "/a".into(), password: "pw\n".into() },
|
||||
Request::Rename { channel_id: 7, password: String::new(), from: "/a".into(), to: "/a".into(), target: None },
|
||||
Request::Rename { channel_id: 7, password: String::new(), from: "/a".into(), to: "/b".into(), target: Some((0, String::new())) },
|
||||
Request::Delete { channel_id: 7, password: String::new(), paths: vec![] },
|
||||
Request::Delete { channel_id: 0, password: String::new(), paths: vec!["/private".into()] },
|
||||
Request::Download { channel_id: 7, password: String::new(), path: "/file".into(), dest_dir: std::env::temp_dir(), subdirs: vec!["..".into()], overwrite: false },
|
||||
Request::Download { channel_id: 7, password: String::new(), path: "/CON".into(), dest_dir: std::env::temp_dir(), subdirs: vec![], overwrite: false },
|
||||
Request::FetchImage { channel_id: 0, path: "/icons/icon_1".into() },
|
||||
];
|
||||
for command in invalid {
|
||||
assert_eq!(crate::protocol::validate_command(crate::protocol::Command::Files(command)).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
}
|
||||
|
||||
fn raw(name: &str, items: &[&[(&str, &str)]]) -> RawNotification {
|
||||
RawNotification {
|
||||
name: name.into(),
|
||||
|
||||
+238
-61
@@ -1,10 +1,11 @@
|
||||
//! Scoped global-shortcut helper. No keyboard hooks or unrestricted key-state scans.
|
||||
//! Wire contract: app/main/whisper-main.js (newline-delimited JSON on stdio).
|
||||
//! Native callback service and CLI adapter (newline-delimited JSON on stdio).
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, RecvTimeoutError}, Arc};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
mod keys;
|
||||
@@ -30,19 +31,19 @@ enum Command {
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Binding {
|
||||
id: String,
|
||||
code: String,
|
||||
pub struct Binding {
|
||||
pub id: String,
|
||||
pub code: String,
|
||||
#[serde(default)]
|
||||
ctrl: bool,
|
||||
pub ctrl: bool,
|
||||
#[serde(default)]
|
||||
alt: bool,
|
||||
pub alt: bool,
|
||||
#[serde(default)]
|
||||
shift: bool,
|
||||
pub shift: bool,
|
||||
#[serde(default)]
|
||||
meta: bool,
|
||||
pub meta: bool,
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
@@ -98,12 +99,12 @@ impl State {
|
||||
true
|
||||
}
|
||||
|
||||
fn release_all(&mut self, out: &mut impl Write) -> io::Result<()> {
|
||||
// Clear each flag even if stdout has gone away; cleanup must still unregister OS bindings.
|
||||
fn release_all(&mut self, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
|
||||
// Clear every flag even when the consumer fails; OS cleanup must still run.
|
||||
let mut failure = None;
|
||||
for (id, held) in &mut self.registered {
|
||||
if std::mem::replace(held, false) {
|
||||
if let Err(error) = emit(out, &serde_json::json!({ "event": "release", "id": id })) {
|
||||
if let Err(error) = out(serde_json::json!({ "event": "release", "id": id, "synthetic": true })) {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
@@ -112,22 +113,22 @@ impl State {
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
fn event(&mut self, event: Event, out: &mut impl Write) -> io::Result<()> {
|
||||
fn event(&mut self, event: Event, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
|
||||
match event {
|
||||
Event::Key { id, down } => {
|
||||
if self.transition(&id, down) {
|
||||
emit(out, &serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
|
||||
out(serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
|
||||
}
|
||||
}
|
||||
Event::Bound { seq, results } => {
|
||||
self.release_all(out)?;
|
||||
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
|
||||
emit(out, &serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
|
||||
out(serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
|
||||
}
|
||||
Event::Rebound { results } => {
|
||||
self.release_all(out)?;
|
||||
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
|
||||
emit(out, &serde_json::json!({ "event": "rebound", "results": results }))?;
|
||||
out(serde_json::json!({ "event": "rebound", "results": results }))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -140,25 +141,28 @@ fn emit(out: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
|
||||
out.flush()
|
||||
}
|
||||
|
||||
fn validate_bindings(bindings: &[Binding]) -> Result<()> {
|
||||
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
|
||||
let mut ids = HashSet::with_capacity(bindings.len());
|
||||
let mut chords = HashSet::with_capacity(bindings.len());
|
||||
for b in bindings {
|
||||
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|
||||
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|
||||
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
|
||||
{
|
||||
return Err("invalid hotkey id, code or description".into());
|
||||
}
|
||||
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
|
||||
return Err("duplicate hotkey id or chord".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse(line: &[u8]) -> Result<Command> {
|
||||
if line.len() > MAX_LINE { return Err("hotkey input line exceeds 64 KiB".into()); }
|
||||
let command: Command = serde_json::from_slice(line)?;
|
||||
if let Command::Bind { bindings, .. } = &command {
|
||||
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
|
||||
let mut ids = HashSet::with_capacity(bindings.len());
|
||||
let mut chords = HashSet::with_capacity(bindings.len());
|
||||
for b in bindings {
|
||||
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|
||||
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|
||||
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
|
||||
{
|
||||
return Err("invalid hotkey id, code or description".into());
|
||||
}
|
||||
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
|
||||
return Err("duplicate hotkey id or chord".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Command::Bind { bindings, .. } = &command { validate_bindings(bindings)?; }
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
@@ -196,8 +200,207 @@ fn open_backend() -> Result<Box<dyn Backend>> {
|
||||
{ Err("global shortcuts are unavailable on this platform".into()) }
|
||||
}
|
||||
|
||||
/// A startup, validation, queue or backend failure. No OS registrations survive stop.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HotkeyError(String);
|
||||
|
||||
impl std::fmt::Display for HotkeyError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) }
|
||||
}
|
||||
|
||||
impl Error for HotkeyError {}
|
||||
|
||||
/// Owns a backend thread and bounded ordered events. Drop requests cancellation;
|
||||
/// call `stop` off the UI thread to wait for OS cleanup, then dispatch final events.
|
||||
pub struct HotkeyHandle {
|
||||
commands: mpsc::SyncSender<Result<Command, String>>,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<Result<(), HotkeyError>>>,
|
||||
events: mpsc::Receiver<serde_json::Value>,
|
||||
held: std::collections::BTreeSet<String>,
|
||||
terminal: Option<Result<(), HotkeyError>>,
|
||||
terminal_delivered: bool,
|
||||
}
|
||||
|
||||
const EVENT_CAPACITY: usize = 256;
|
||||
|
||||
impl HotkeyHandle {
|
||||
/// Replace the complete binding profile. Success means queued; the callback's
|
||||
/// `bound` event with this sequence carries the actual registration results.
|
||||
/// A full queue returns an error without replacing any pending profile.
|
||||
pub fn update(&self, seq: u32, bindings: Vec<Binding>) -> Result<(), HotkeyError> {
|
||||
validate_bindings(&bindings).map_err(|e| HotkeyError(e.to_string()))?;
|
||||
if self.cancelled.load(Ordering::Acquire) { return Err(HotkeyError("hotkey service has stopped".into())); }
|
||||
self.commands.try_send(Ok(Command::Bind { seq, bindings })).map_err(|error| {
|
||||
HotkeyError(match error {
|
||||
mpsc::TrySendError::Full(_) => "hotkey command queue is full",
|
||||
mpsc::TrySendError::Disconnected(_) => "hotkey service has stopped",
|
||||
}.into())
|
||||
})
|
||||
}
|
||||
|
||||
/// Cancel pending updates, release held keys, unregister and join the worker.
|
||||
/// Call off the UI thread; callbacks are never run by the backend worker.
|
||||
/// Afterwards call `dispatch` to consume final releases/errors.
|
||||
pub fn stop(&mut self) -> Result<(), HotkeyError> {
|
||||
self.cancel();
|
||||
if let Some(worker) = self.worker.take() {
|
||||
self.terminal = Some(worker.join().unwrap_or_else(|_| Err(HotkeyError("hotkey worker panicked".into()))));
|
||||
}
|
||||
self.terminal.clone().unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
self.cancelled.store(true, Ordering::Release);
|
||||
// Wake an idle worker; cancellation remains effective with a full queue.
|
||||
let _ = self.commands.try_send(Ok(Command::Shutdown {}));
|
||||
}
|
||||
|
||||
/// Deliver a bounded batch on the calling thread, plus final releases/errors.
|
||||
/// No callback runs on the OS backend thread, so a stalled consumer cannot
|
||||
/// prevent unregister. Queue overflow terminates the backend; cancellation
|
||||
/// discards undelivered events. Every consumer-held key is released before the
|
||||
/// terminal error, even if the bounded queue had no room for its release.
|
||||
/// Callback failure cancels the backend; call again to receive final releases.
|
||||
pub fn dispatch(&mut self, mut callback: impl FnMut(serde_json::Value) -> io::Result<()>) -> Result<usize, HotkeyError> {
|
||||
let mut delivered = 0;
|
||||
let mut disconnected = false;
|
||||
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
|
||||
if matches!(&self.terminal, Some(Err(_))) {
|
||||
// Failed service events must not reactivate PTT when a stalled host
|
||||
// resumes. The joined worker cannot refill this bounded queue.
|
||||
while self.events.try_recv().is_ok() {}
|
||||
}
|
||||
for _ in 0..EVENT_CAPACITY {
|
||||
let value = match self.events.try_recv() {
|
||||
Ok(value) => value,
|
||||
Err(mpsc::TryRecvError::Empty) => break,
|
||||
Err(mpsc::TryRecvError::Disconnected) => { disconnected = true; break; }
|
||||
};
|
||||
if self.cancelled.load(Ordering::Acquire) { continue; }
|
||||
let release_id = if value["event"] == "release" { value["id"].as_str().map(str::to_owned) } else { None };
|
||||
if value["event"] == "press" {
|
||||
if let Some(id) = value["id"].as_str() { self.held.insert(id.to_owned()); }
|
||||
}
|
||||
if let Err(error) = callback(value) {
|
||||
self.cancel();
|
||||
return Err(HotkeyError(error.to_string()));
|
||||
}
|
||||
if let Some(id) = release_id { self.held.remove(&id); }
|
||||
delivered += 1;
|
||||
}
|
||||
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
|
||||
if disconnected && self.terminal.is_some() && !self.terminal_delivered {
|
||||
while let Some(id) = self.held.first().cloned() {
|
||||
callback(serde_json::json!({ "event": "release", "id": id, "synthetic": true })).map_err(|e| HotkeyError(e.to_string()))?;
|
||||
self.held.remove(&id);
|
||||
delivered += 1;
|
||||
}
|
||||
if let Some(Err(error)) = &self.terminal {
|
||||
callback(serde_json::json!({ "event": "error", "detail": error.to_string() })).map_err(|e| HotkeyError(e.to_string()))?;
|
||||
delivered += 1;
|
||||
}
|
||||
self.terminal_delivered = true;
|
||||
}
|
||||
Ok(delivered)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HotkeyHandle {
|
||||
fn drop(&mut self) { self.cancel(); }
|
||||
}
|
||||
|
||||
/// Explicitly open the platform backend, without registering any bindings.
|
||||
/// Call off the UI thread: startup waits for backend discovery. `update` is the
|
||||
/// only registration request. Call `dispatch` regularly to deliver callback
|
||||
/// events with the CLI JSON shape and no serialization round trip.
|
||||
pub fn start() -> Result<HotkeyHandle, HotkeyError> {
|
||||
start_with_backend(open_backend)
|
||||
}
|
||||
|
||||
fn start_with_backend(
|
||||
factory: impl FnOnce() -> Result<Box<dyn Backend>> + Send + 'static,
|
||||
) -> Result<HotkeyHandle, HotkeyError> {
|
||||
let (commands, rx) = mpsc::sync_channel(8);
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
||||
let (events_tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let stop = Arc::clone(&cancelled);
|
||||
let worker = std::thread::Builder::new().name("hotkeys".into()).spawn(move || {
|
||||
let mut out = |value: serde_json::Value| {
|
||||
// Native errors are delivered once after final held-key releases.
|
||||
if value["event"] == "error" { return Ok(()); }
|
||||
events_tx.try_send(value).map_err(|error| io::Error::other(match error {
|
||||
mpsc::TrySendError::Full(_) => "hotkey event queue overflow",
|
||||
mpsc::TrySendError::Disconnected(_) => "hotkey event consumer closed",
|
||||
}))
|
||||
};
|
||||
let mut backend = match factory() {
|
||||
Ok(backend) => backend,
|
||||
Err(error) => {
|
||||
let detail = error.to_string();
|
||||
let _ = out(serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": detail }));
|
||||
let _ = ready_tx.send(Err(detail.clone()));
|
||||
return Err(HotkeyError(detail));
|
||||
}
|
||||
};
|
||||
if let Err(error) = out(serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true })) {
|
||||
let _ = backend.clear();
|
||||
let _ = ready_tx.send(Err(error.to_string()));
|
||||
return Err(HotkeyError(error.to_string()));
|
||||
}
|
||||
let _ = ready_tx.send(Ok(()));
|
||||
serve(&mut *backend, rx, &stop, &mut out).map_err(|e| HotkeyError(e.to_string()))
|
||||
}).map_err(|e| HotkeyError(e.to_string()))?;
|
||||
let mut handle = HotkeyHandle { commands, cancelled, worker: Some(worker), events,
|
||||
held: Default::default(), terminal: None, terminal_delivered: false };
|
||||
match ready_rx.recv() {
|
||||
Ok(Ok(())) => Ok(handle),
|
||||
Ok(Err(error)) => { let _ = handle.stop(); Err(HotkeyError(error)) }
|
||||
Err(_) => { let _ = handle.stop(); Err(HotkeyError("hotkey worker stopped during startup".into())) }
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(
|
||||
backend: &mut dyn Backend,
|
||||
rx: mpsc::Receiver<Result<Command, String>>,
|
||||
cancelled: &AtomicBool,
|
||||
out: &mut impl FnMut(serde_json::Value) -> io::Result<()>,
|
||||
) -> Result<()> {
|
||||
let mut state = State::default();
|
||||
let mut events = Vec::with_capacity(MAX_BINDINGS);
|
||||
let result = (|| -> Result<()> {
|
||||
while !cancelled.load(Ordering::Acquire) {
|
||||
let command = rx.recv_timeout(Duration::from_millis(8));
|
||||
if cancelled.load(Ordering::Acquire) { break; }
|
||||
match command {
|
||||
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
|
||||
Ok(Err(error)) => return Err(error.into()),
|
||||
Ok(Ok(Command::Bind { seq, bindings })) => {
|
||||
state.release_all(out)?;
|
||||
backend.clear()?;
|
||||
backend.bind(seq, bindings, &mut events)?;
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
if cancelled.load(Ordering::Acquire) { break; }
|
||||
backend.poll(&mut events)?;
|
||||
for event in events.drain(..) { state.event(event, out)?; }
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let released = state.release_all(out);
|
||||
let cleared = backend.clear();
|
||||
if let Err(error) = &result {
|
||||
let _ = out(serde_json::json!({ "event": "error", "detail": error.to_string() }));
|
||||
}
|
||||
result?;
|
||||
released?;
|
||||
cleared
|
||||
}
|
||||
|
||||
/// Runs only when explicitly selected by the `hotkeys` CLI subcommand.
|
||||
/// Tests exercise parsing/state only and never construct a platform backend.
|
||||
/// Blocking input and stdout serialization belong exclusively to this adapter.
|
||||
pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let stdout = io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
@@ -226,31 +429,5 @@ pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
if tx.send(item).is_err() || terminal { break; }
|
||||
}
|
||||
})?;
|
||||
let mut state = State::default();
|
||||
let mut events = Vec::with_capacity(MAX_BINDINGS);
|
||||
let result = (|| -> Result<()> {
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_millis(8)) {
|
||||
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
|
||||
Ok(Err(error)) => return Err(error.into()),
|
||||
Ok(Ok(Command::Bind { seq, bindings })) => {
|
||||
state.release_all(&mut out)?;
|
||||
backend.clear()?;
|
||||
backend.bind(seq, bindings, &mut events)?;
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
backend.poll(&mut events)?;
|
||||
for event in events.drain(..) { state.event(event, &mut out)?; }
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let released = state.release_all(&mut out);
|
||||
let cleared = backend.clear();
|
||||
if let Err(error) = &result {
|
||||
let _ = emit(&mut out, &serde_json::json!({ "event": "error", "detail": error.to_string() }));
|
||||
}
|
||||
result?;
|
||||
released?;
|
||||
cleared
|
||||
serve(&mut *backend, rx, &AtomicBool::new(false), &mut |value| emit(&mut out, &value))
|
||||
}
|
||||
+163
-5
@@ -83,10 +83,13 @@ fn replacement_releases_held_ids_before_new_bound_event() {
|
||||
state.registered.insert("old".into(), true);
|
||||
let mut out = Vec::new();
|
||||
state.event(Event::Bound { seq: 2, results: vec![BindResult::success(&binding("new", "KeyN"), "n".into()),
|
||||
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut out).unwrap();
|
||||
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut |value| emit(&mut out, &value)).unwrap();
|
||||
let messages: Vec<serde_json::Value> = out.split(|b| *b == b'\n').filter(|b| !b.is_empty())
|
||||
.map(|b| serde_json::from_slice(b).unwrap()).collect();
|
||||
assert_eq!(messages[0], serde_json::json!({ "event": "release", "id": "old" }));
|
||||
assert_eq!(messages[0]["event"], "release");
|
||||
assert_eq!(messages[0]["id"], "old");
|
||||
// Replacement is cancellation, not a physical key-up that can trigger a command.
|
||||
assert_eq!(messages[0]["synthetic"], true);
|
||||
assert_eq!(messages[1]["event"], "bound");
|
||||
assert_eq!(messages[1]["seq"], 2);
|
||||
assert!(state.transition("new", true));
|
||||
@@ -99,9 +102,9 @@ fn shutdown_and_failure_release_all_once() {
|
||||
let mut state = State::default();
|
||||
state.registered.extend([("a".into(), true), ("b".into(), true), ("c".into(), false)]);
|
||||
let mut out = Vec::new();
|
||||
state.release_all(&mut out).unwrap();
|
||||
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
|
||||
let written = out.len();
|
||||
state.release_all(&mut out).unwrap();
|
||||
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
|
||||
assert_eq!(out.len(), written);
|
||||
assert_eq!(out.iter().filter(|&&b| b == b'\n').count(), 2);
|
||||
assert!(state.registered.is_empty());
|
||||
@@ -116,7 +119,7 @@ fn broken_stdout_still_clears_all_held_state() {
|
||||
}
|
||||
let mut state = State::default();
|
||||
state.registered.extend([("a".into(), true), ("b".into(), true)]);
|
||||
assert!(state.release_all(&mut Broken).is_err());
|
||||
assert!(state.release_all(&mut |value| emit(&mut Broken, &value)).is_err());
|
||||
assert!(state.registered.is_empty());
|
||||
}
|
||||
|
||||
@@ -134,3 +137,158 @@ fn key_allowlist_and_portal_trigger_are_explicit() {
|
||||
b.meta = true;
|
||||
assert_eq!(keys::trigger(&b, &keys::lookup(&b.code).unwrap()), "CTRL+SHIFT+LOGO+a");
|
||||
}
|
||||
|
||||
// The same service factory/loop used by native callers, with no platform access.
|
||||
struct FakeBackend {
|
||||
binds: Arc<std::sync::atomic::AtomicUsize>,
|
||||
clears: Arc<std::sync::atomic::AtomicUsize>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
bursts: mpsc::Receiver<usize>,
|
||||
active: Option<String>,
|
||||
}
|
||||
|
||||
impl Backend for FakeBackend {
|
||||
fn name(&self) -> &'static str { "test" }
|
||||
|
||||
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
|
||||
self.binds.fetch_add(1, Ordering::SeqCst);
|
||||
self.active = bindings.first().map(|b| b.id.clone());
|
||||
let results = bindings.iter().map(|b| BindResult::success(b, b.code.clone())).collect();
|
||||
events.push(Event::Bound { seq, results });
|
||||
if let Some(id) = &self.active { events.push(Event::Key { id: id.clone(), down: true }); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
|
||||
if let (Some(id), Ok(count)) = (&self.active, self.bursts.try_recv()) {
|
||||
for n in 0..count { events.push(Event::Key { id: id.clone(), down: n % 2 != 0 }); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear(&mut self) -> Result<()> {
|
||||
self.clears.fetch_add(1, Ordering::SeqCst);
|
||||
self.active = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FakeBackend {
|
||||
fn drop(&mut self) { self.dropped.store(true, Ordering::Release); }
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
handle: HotkeyHandle,
|
||||
binds: Arc<std::sync::atomic::AtomicUsize>,
|
||||
clears: Arc<std::sync::atomic::AtomicUsize>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
bursts: mpsc::SyncSender<usize>,
|
||||
}
|
||||
|
||||
fn fake_service() -> Fixture {
|
||||
let binds = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let clears = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let (bursts, rx) = mpsc::sync_channel(1);
|
||||
let backend = FakeBackend { binds: binds.clone(), clears: clears.clone(), dropped: dropped.clone(), bursts: rx, active: None };
|
||||
let handle = start_with_backend(move || Ok(Box::new(backend))).unwrap();
|
||||
Fixture { handle, binds, clears, dropped, bursts }
|
||||
}
|
||||
|
||||
fn eventually(mut condition: impl FnMut() -> bool) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(3);
|
||||
while !condition() {
|
||||
assert!(std::time::Instant::now() < deadline, "hotkey lifecycle did not complete");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_until(handle: &mut HotkeyHandle, messages: &mut Vec<serde_json::Value>, event: &str, id: &str) {
|
||||
let consumer_thread = std::thread::current().id();
|
||||
eventually(|| {
|
||||
handle.dispatch(|value| {
|
||||
assert_eq!(std::thread::current().id(), consumer_thread);
|
||||
messages.push(value);
|
||||
Ok(())
|
||||
}).unwrap();
|
||||
messages.iter().any(|v| v["event"] == event && v["id"] == id)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_profiles_release_before_replace_and_join_before_restart() {
|
||||
for _ in 0..100 {
|
||||
let mut fixture = fake_service();
|
||||
assert_eq!(fixture.binds.load(Ordering::SeqCst), 0, "startup must not register");
|
||||
let mut messages = Vec::new();
|
||||
fixture.handle.update(1, vec![binding("old", "KeyA")]).unwrap();
|
||||
dispatch_until(&mut fixture.handle, &mut messages, "press", "old");
|
||||
assert!(fixture.handle.update(2, vec![binding("x", "KeyA"), binding("x", "KeyB")]).is_err());
|
||||
assert_eq!(fixture.binds.load(Ordering::SeqCst), 1);
|
||||
fixture.handle.update(3, vec![binding("new", "KeyB")]).unwrap();
|
||||
dispatch_until(&mut fixture.handle, &mut messages, "press", "new");
|
||||
let released = messages.iter().position(|v| v["event"] == "release" && v["id"] == "old").unwrap();
|
||||
let rebound = messages.iter().position(|v| v["event"] == "bound" && v["seq"] == 3).unwrap();
|
||||
assert!(released < rebound);
|
||||
fixture.handle.stop().unwrap();
|
||||
assert!(fixture.dropped.load(Ordering::Acquire), "stop must join backend destruction");
|
||||
assert_eq!(fixture.clears.load(Ordering::SeqCst), 3);
|
||||
dispatch_until(&mut fixture.handle, &mut messages, "release", "new");
|
||||
assert!(fixture.handle.update(4, vec![]).is_err());
|
||||
let count = messages.len();
|
||||
fixture.handle.stop().unwrap();
|
||||
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
|
||||
assert_eq!(messages.len(), count, "stop/release must be idempotent");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stalled_event_consumer_unregisters_and_receives_final_release_on_overflow() {
|
||||
let mut fixture = fake_service();
|
||||
let mut messages = Vec::new();
|
||||
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
|
||||
dispatch_until(&mut fixture.handle, &mut messages, "press", "ptt");
|
||||
fixture.bursts.send(EVENT_CAPACITY + 1).unwrap();
|
||||
// Do not dispatch: a backend must terminate independently of the consumer.
|
||||
eventually(|| fixture.dropped.load(Ordering::Acquire));
|
||||
assert!(fixture.handle.stop().unwrap_err().to_string().contains("overflow"));
|
||||
eventually(|| {
|
||||
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
|
||||
messages.iter().any(|v| v["event"] == "error")
|
||||
});
|
||||
let mut held = false;
|
||||
for message in &messages {
|
||||
match message["event"].as_str().unwrap() {
|
||||
"press" => { assert!(!held); held = true; }
|
||||
"release" => { assert!(held); held = false; }
|
||||
"error" => assert!(!held, "overflow must release PTT before reporting failure"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(!held);
|
||||
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_failure_cancels_without_stranding_consumer_held_key() {
|
||||
let mut fixture = fake_service();
|
||||
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
|
||||
eventually(|| fixture.handle.dispatch(|value| {
|
||||
if value["event"] == "press" { Err(io::Error::other("consumer failed")) } else { Ok(()) }
|
||||
}).is_err());
|
||||
fixture.handle.stop().unwrap();
|
||||
let mut messages = Vec::new();
|
||||
dispatch_until(&mut fixture.handle, &mut messages, "release", "ptt");
|
||||
assert_eq!(messages.iter().filter(|v| v["event"] == "release").count(), 1);
|
||||
assert!(fixture.dropped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_service_requests_cleanup_without_dispatch() {
|
||||
let mut fixture = fake_service();
|
||||
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
|
||||
dispatch_until(&mut fixture.handle, &mut Vec::new(), "press", "ptt");
|
||||
drop(fixture.handle);
|
||||
eventually(|| fixture.dropped.load(Ordering::Acquire));
|
||||
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Disposable identity CLI. Keys never enter stdout or process arguments.
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::io::{BufRead, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
|
||||
use std::time::Duration;
|
||||
use serde_json::{json, Value};
|
||||
use crate::profile::{Store, store_error};
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
@@ -17,6 +19,19 @@ pub fn emit(value: &Value) {
|
||||
let _ = writeln!(out, "{value}");
|
||||
let _ = out.flush();
|
||||
}
|
||||
// Only the standalone CLI owns a blocking stdin cancellation reader. The
|
||||
// embeddable improvement entrypoint never starts or waits for this reader.
|
||||
fn improve(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let signal = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut line = String::new();
|
||||
// Cancel on explicit command, stdin closure or transport failure.
|
||||
let _ = std::io::stdin().lock().read_line(&mut line);
|
||||
signal.store(true, Ordering::Relaxed);
|
||||
});
|
||||
crate::identity_improve::improve(store, uid, target, Duration::from_secs(seconds), &cancel, |event| emit(&event))
|
||||
}
|
||||
fn execute(args: &[String]) -> Result<Value, ErrorObj> {
|
||||
let action = args.first().ok_or_else(|| bad("identity action required"))?;
|
||||
let allowed: &[&str] = match action.as_str() {
|
||||
@@ -39,7 +54,7 @@ fn execute(args: &[String]) -> Result<Value, ErrorObj> {
|
||||
// Atomic vault reads need no profile lock; exports remain available during standalone sessions.
|
||||
// Mutations share the core lock and Store serializes writers/protects connected identities.
|
||||
let _guard = if action == "list" || action == "export" { None } else {
|
||||
Some(crate::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
|
||||
Some(crate::locks::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
|
||||
};
|
||||
let store = Store::new(dir);
|
||||
let uid = || required(&values, "--uid");
|
||||
@@ -68,7 +83,7 @@ fn execute(args: &[String]) -> Result<Value, ErrorObj> {
|
||||
let target = required(&values,"--target")?.parse::<u8>().map_err(|_| bad("invalid target"))?;
|
||||
let seconds = values.get("--seconds").map(|v| v.parse::<u64>()).transpose().map_err(|_| bad("invalid duration"))?.unwrap_or(30);
|
||||
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target) || !(1..=60).contains(&seconds) { return Err(bad("target must be 1–100; duration 1–60 seconds")); }
|
||||
crate::identity_improve::run(&store, uid()?, target, seconds)
|
||||
improve(&store, uid()?, target, seconds)
|
||||
},
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Bounded, cancellable hash-cash work. One core at <=25% duty cycle for at most 60 seconds.
|
||||
use std::io::{self, BufRead};
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use sha1::{Digest, Sha1};
|
||||
use serde_json::{json, Value};
|
||||
use crate::profile::{Store, store_error};
|
||||
use crate::protocol::ErrorObj;
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
|
||||
// TeamSpeak counts trailing bits of each SHA1 byte, starting with the first byte.
|
||||
// Decimal conversion uses a stack buffer: no allocation per candidate.
|
||||
@@ -24,7 +23,22 @@ fn quality(prefix: &Sha1, mut offset: u64) -> u8 {
|
||||
}
|
||||
level
|
||||
}
|
||||
fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &AtomicBool) -> Result<Value, ErrorObj> {
|
||||
/// Improve an identity on the caller's worker, persisting progress before notifying it.
|
||||
/// Cancellation is caller-owned; this function creates no threads or transport readers.
|
||||
/// Returning (including cancellation) completes the final durable checkpoint.
|
||||
pub fn improve(
|
||||
store: &Store,
|
||||
uid: &str,
|
||||
target: u8,
|
||||
duration: Duration,
|
||||
cancel: &AtomicBool,
|
||||
mut progress: impl FnMut(Value),
|
||||
) -> Result<Value, ErrorObj> {
|
||||
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target)
|
||||
|| duration.is_zero() || duration > Duration::from_secs(60)
|
||||
{
|
||||
return Err(ErrorObj::new(ErrorCode::BadRequest, "target must be 1–100; duration greater than zero and at most 60 seconds"));
|
||||
}
|
||||
let start = store.improve_start(uid).map_err(store_error)?;
|
||||
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
|
||||
let begun = Instant::now();
|
||||
@@ -44,7 +58,7 @@ fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &Ato
|
||||
}
|
||||
if checkpoint.elapsed() >= Duration::from_millis(500) || level >= target || exhausted {
|
||||
level = store.record_improvement(uid, best.take(), next).map_err(store_error)?;
|
||||
crate::identity_cli::emit(&json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
|
||||
progress(json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
|
||||
checkpoint = Instant::now();
|
||||
}
|
||||
if exhausted { break; }
|
||||
@@ -53,17 +67,6 @@ fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &Ato
|
||||
level = store.record_improvement(uid, best, next).map_err(store_error)?;
|
||||
Ok(json!({"uid":uid,"level":level,"target":target,"reached":level>=target,"canceled":cancel.load(Ordering::Relaxed),"bounded":level<target,"exhausted":exhausted,"searched":next.to_string()}))
|
||||
}
|
||||
pub fn run(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let signal = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut line = String::new();
|
||||
// Cancel on explicit command, stdin closure or transport failure.
|
||||
let _ = io::stdin().lock().read_line(&mut line);
|
||||
signal.store(true, Ordering::Relaxed);
|
||||
});
|
||||
search(store, uid, target, Duration::from_secs(seconds), &cancel)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -86,11 +89,33 @@ mod tests {
|
||||
let store = Store::new(&dir.0);
|
||||
let identity = store.create_identity("Temporary", "Temporary").unwrap();
|
||||
let before = store.export_ini(&identity.uid).unwrap();
|
||||
let result = search(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true)).unwrap();
|
||||
let result = std::thread::scope(|scope| {
|
||||
scope.spawn(|| improve(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true), |_| panic!("pre-canceled work must not report progress")))
|
||||
.join().expect("native worker joins without a stdin reader").unwrap()
|
||||
});
|
||||
assert_eq!(result["canceled"], true);
|
||||
assert_eq!(before, store.export_ini(&identity.uid).unwrap());
|
||||
}
|
||||
#[test]
|
||||
fn native_bounds_reject_before_touching_identity() {
|
||||
let dir = crate::profile::tests::TempDir::new("improve-invalid");
|
||||
let store = Store::new(&dir.0);
|
||||
let info = store.create_identity("Temporary", "Temporary").unwrap();
|
||||
let before = store.export_ini(&info.uid).unwrap();
|
||||
let start = store.improve_start(&info.uid).unwrap().start;
|
||||
for (target, duration) in [
|
||||
(0, Duration::from_secs(1)),
|
||||
(101, Duration::from_secs(1)),
|
||||
(100, Duration::ZERO),
|
||||
(100, Duration::from_secs(61)),
|
||||
] {
|
||||
let error = improve(&store, &info.uid, target, duration, &AtomicBool::new(false), |_| panic!("invalid work must not report progress")).unwrap_err();
|
||||
assert_eq!(serde_json::to_value(error).unwrap()["code"], "bad_request");
|
||||
}
|
||||
assert_eq!(before, store.export_ini(&info.uid).unwrap());
|
||||
assert_eq!(start, store.improve_start(&info.uid).unwrap().start);
|
||||
}
|
||||
#[test]
|
||||
fn quality_matches_protocol_identity_and_deadline_resumes() {
|
||||
let dir = crate::profile::tests::TempDir::new("improve-bound");
|
||||
let store = Store::new(&dir.0);
|
||||
@@ -99,7 +124,7 @@ mod tests {
|
||||
let start = store.improve_start(&info.uid).unwrap();
|
||||
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
|
||||
assert_eq!(quality(&prefix, stored.identity.counter()), stored.identity.level());
|
||||
let result = search(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false)).unwrap();
|
||||
let result = improve(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false), |_| {}).unwrap();
|
||||
assert_eq!(result["bounded"], true);
|
||||
let resumed = store.improve_start(&info.uid).unwrap();
|
||||
assert!(resumed.start > start.start);
|
||||
@@ -108,19 +133,36 @@ mod tests {
|
||||
assert_eq!(resumed.start.to_string(), result["searched"].as_str().unwrap());
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_during_search_preserves_checkpoint() {
|
||||
fn cancellation_during_search_preserves_checkpoint_and_resumes() {
|
||||
let dir = crate::profile::tests::TempDir::new("improve-running-cancel");
|
||||
let store = Store::new(&dir.0);
|
||||
let info = store.create_identity("Temporary", "Temporary").unwrap();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let signal = cancel.clone();
|
||||
let canceller = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
signal.store(true, Ordering::Relaxed);
|
||||
});
|
||||
let result = search(&store, &info.uid, 100, Duration::from_secs(1), &cancel).unwrap();
|
||||
canceller.join().unwrap();
|
||||
assert_eq!(result["canceled"], true);
|
||||
assert_eq!(store.improve_start(&info.uid).unwrap().start.to_string(), result["searched"].as_str().unwrap());
|
||||
let original_key = store.load_identity().unwrap().unwrap().identity.key().to_ts();
|
||||
let mut previous = store.improve_start(&info.uid).unwrap().start;
|
||||
for _ in 0..2 {
|
||||
let cancel = AtomicBool::new(false);
|
||||
let mut checkpoint = None;
|
||||
// Cancel synchronously at a durable checkpoint, without a timing race
|
||||
// against a detached canceller or relying on thread scheduling.
|
||||
let result = improve(&store, &info.uid, 100, Duration::from_secs(60), &cancel, |event| {
|
||||
assert_eq!(event["uid"], info.uid);
|
||||
let persisted = store.improve_start(&info.uid).unwrap();
|
||||
assert_eq!(event["searched"], persisted.start.to_string());
|
||||
checkpoint = Some(persisted.start);
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
}).unwrap();
|
||||
assert_eq!(result["canceled"], true);
|
||||
let next = checkpoint.expect("search must report a durable checkpoint");
|
||||
assert!(next > previous);
|
||||
let persisted = store.improve_start(&info.uid).unwrap();
|
||||
assert_eq!(persisted.start, next);
|
||||
assert_eq!(result["searched"], next.to_string());
|
||||
let loaded = store.load_identity().unwrap().unwrap();
|
||||
assert_eq!(loaded.uid, info.uid);
|
||||
assert_eq!(loaded.identity.key().to_ts(), original_key);
|
||||
let mut prefix = Sha1::new(); prefix.update(persisted.omega.as_bytes());
|
||||
assert_eq!(quality(&prefix, loaded.identity.counter()), persisted.level);
|
||||
previous = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Embedded TeamSpeak domain services and the independent diagnostic CLI adapters.
|
||||
pub mod admin;
|
||||
pub mod app_audio;
|
||||
pub mod audio;
|
||||
mod events;
|
||||
pub mod file_transfer;
|
||||
pub mod hotkeys;
|
||||
mod keyfmt;
|
||||
pub mod identity_cli;
|
||||
pub mod identity_improve;
|
||||
pub mod locks;
|
||||
pub mod media;
|
||||
pub mod menu;
|
||||
pub mod output;
|
||||
pub mod profile;
|
||||
pub mod protocol;
|
||||
pub mod recording;
|
||||
mod rawcmd;
|
||||
pub mod runtime;
|
||||
pub mod secure_fs;
|
||||
pub mod session;
|
||||
mod snapshot;
|
||||
pub mod stdio;
|
||||
#[cfg(test)]
|
||||
mod test_exec;
|
||||
pub mod vad;
|
||||
pub mod voice_dsp;
|
||||
pub mod whisper;
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::path::Path;
|
||||
use crate::secure_fs;
|
||||
|
||||
/// Cooperates with diagnostic CLI and embedded sessions without copying private identity keys.
|
||||
pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
|
||||
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
|
||||
let path = dir.join("core.lock");
|
||||
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
match if shared { file.try_lock_shared() } else { file.try_lock() } {
|
||||
Ok(()) => Ok(file),
|
||||
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
|
||||
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
|
||||
match connection_dir {
|
||||
None => Ok(vec![lock_dir(data_dir, false)?]),
|
||||
Some(conn) => Ok(vec![lock_dir(data_dir, true)?, lock_dir(conn, false)?]),
|
||||
}
|
||||
}
|
||||
+8
-68
@@ -1,32 +1,7 @@
|
||||
//! TeamsPeach core: TeamSpeak protocol backend speaking newline-delimited JSON on stdio.
|
||||
//! Contract: `docs/bridge.md`.
|
||||
|
||||
mod admin;
|
||||
mod app_audio;
|
||||
mod audio;
|
||||
mod events;
|
||||
mod file_transfer;
|
||||
mod hotkeys;
|
||||
mod keyfmt;
|
||||
mod identity_cli;
|
||||
mod identity_improve;
|
||||
mod media;
|
||||
mod menu;
|
||||
mod profile;
|
||||
mod protocol;
|
||||
mod recording;
|
||||
mod rawcmd;
|
||||
mod secure_fs;
|
||||
mod session;
|
||||
mod snapshot;
|
||||
mod stdio;
|
||||
#[cfg(test)]
|
||||
mod test_exec;
|
||||
mod vad;
|
||||
mod voice_dsp;
|
||||
mod whisper;
|
||||
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use teamspeach_core::{app_audio, audio, hotkeys, identity_cli, locks, output, profile, protocol, session, stdio};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
@@ -36,10 +11,10 @@ use serde_json::json;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::audio::AudioInQueue;
|
||||
use crate::profile::Store;
|
||||
use crate::protocol::PROTOCOL_VERSION;
|
||||
use crate::stdio::Out;
|
||||
use audio::AudioInQueue;
|
||||
use profile::Store;
|
||||
use protocol::PROTOCOL_VERSION;
|
||||
use output::Out;
|
||||
|
||||
const EXIT_FATAL: u8 = 1;
|
||||
const EXIT_USAGE: u8 = 2;
|
||||
@@ -82,45 +57,10 @@ fn parse_args(args: &[String]) -> Result<Mode, String> {
|
||||
Ok(Mode::Run { data_dir, connection_dir })
|
||||
}
|
||||
|
||||
/// Lock on `<dir>/core.lock`, held for the process lifetime.
|
||||
///
|
||||
/// - exclusive (`shared == false`): a single-connection core.
|
||||
/// - shared: simultaneous connection cores and the identity CLI on the same profile.
|
||||
/// Store serializes identity writes separately with `profile.lock`.
|
||||
fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
|
||||
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
|
||||
let path = dir.join("core.lock");
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
let result = if shared { file.try_lock_shared() } else { file.try_lock() };
|
||||
match result {
|
||||
Ok(()) => Ok(file),
|
||||
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
|
||||
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_data_dir(dir: &Path) -> Result<File, String> { lock_dir(dir, false) }
|
||||
|
||||
/// Profile locks for `run`: exclusive on the profile alone, or shared on the profile plus exclusive
|
||||
/// on the connection's own directory (two cores never serve the same connection slot).
|
||||
fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
|
||||
match connection_dir {
|
||||
None => Ok(vec![lock_data_dir(data_dir)?]),
|
||||
Some(conn) => {
|
||||
let profile = lock_dir(data_dir, true)?;
|
||||
Ok(vec![profile, lock_dir(conn, false)?])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
|
||||
let _locks = match lock_run(&data_dir, connection_dir.as_deref()) {
|
||||
let _locks = match locks::lock_run(&data_dir, connection_dir.as_deref()) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
error!("{e}");
|
||||
@@ -135,8 +75,8 @@ fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
|
||||
}
|
||||
};
|
||||
rt.block_on(async move {
|
||||
let (out, out_rx) = Out::new();
|
||||
let writer = tokio::spawn(stdio::run_writer(out_rx));
|
||||
let (out, out_rx, playback_rx) = Out::new();
|
||||
let writer = tokio::spawn(stdio::run_writer(out_rx, playback_rx));
|
||||
let audio_in = Arc::new(AudioInQueue::new());
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel(64);
|
||||
{
|
||||
|
||||
+16
-5
@@ -41,7 +41,7 @@ pub enum Action {
|
||||
SetChannelPermission { channel_id: u64, permission_id: u32, value: Option<i32> },
|
||||
KickChannel { reason: String }, KickServer { reason: String }, Ban { reason: String, duration: u32 },
|
||||
Volume { db: f32, muted: bool }, Avatar { data: String },
|
||||
MoveToOwnChannel { #[serde(default)] password: Option<String> }, DeleteAvatar {},
|
||||
MoveToOwnChannel { #[serde(default)] password: Option<String>, expected_channel_id: u64 }, DeleteAvatar {},
|
||||
}
|
||||
impl Action {
|
||||
pub fn key(&self) -> &'static str { match self {
|
||||
@@ -66,22 +66,28 @@ pub fn validate_target(t: &Target) -> Result<(), ErrorObj> {
|
||||
pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
|
||||
let obj=value.as_object_mut().ok_or_else(||bad("args must be an object"))?;
|
||||
let target=serde_json::from_value::<Target>(json!({"client_id":obj.remove("client_id"),"uid":obj.remove("uid")})).map_err(|e|bad(e.to_string()))?;
|
||||
validate_target(&target)?;
|
||||
let generation=obj.remove("generation").and_then(|v|v.as_u64()).filter(|v|*v>0).ok_or_else(||bad("generation is required"))?;
|
||||
if matches!(obj.get("action").and_then(Value::as_str),Some("set_client_permission"|"set_channel_permission")) && !obj.contains_key("value") { return Err(bad("value is required; use null explicitly to remove a permission")); }
|
||||
let action:Action=serde_json::from_value(value).map_err(|e|bad(e.to_string()))?;
|
||||
match &action {
|
||||
Ok(ActionRequest { target, generation, action })
|
||||
}
|
||||
|
||||
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
|
||||
validate_target(&request.target)?;
|
||||
if request.generation == 0 { return Err(bad("generation is required")); }
|
||||
match &request.action {
|
||||
Action::Poke{message} if message.is_empty() || message.len()>1024 || message.chars().any(char::is_control) =>return Err(bad("poke message must be 1..1024 bytes without controls")),
|
||||
Action::KickChannel{reason}|Action::KickServer{reason}|Action::Ban{reason,..} if reason.len()>1024 || reason.chars().any(char::is_control)=>return Err(bad("reason must be at most 1024 bytes without controls")),
|
||||
Action::Volume{db,..} if !crate::voice_dsp::valid_modifier_db(*db)=>return Err(bad("volume must be -200..10 dB in 0.5 dB steps")),
|
||||
Action::ServerGroup{group_id,..}|Action::ChannelGroup{group_id,..} if *group_id==0=>return Err(bad("group_id must be positive")),
|
||||
Action::ChannelGroup{channel_id,..}|Action::ChannelPermissions{channel_id}|Action::SetChannelPermission{channel_id,..} if *channel_id==0=>return Err(bad("channel_id must be positive")),
|
||||
Action::SetClientPermission{permission_id,..}|Action::SetChannelPermission{permission_id,..} if *permission_id==0=>return Err(bad("permission_id must be positive")),
|
||||
Action::MoveToOwnChannel{password:Some(p)} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
|
||||
Action::MoveToOwnChannel{expected_channel_id:0,..}=>return Err(bad("expected_channel_id must be positive")),
|
||||
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
|
||||
Action::Avatar{data}=>{avatar_bytes(data)?;},
|
||||
_=>{},
|
||||
}
|
||||
Ok(ActionRequest{target,generation,action})
|
||||
Ok(())
|
||||
}
|
||||
pub fn avatar_bytes(data:&str)->Result<Vec<u8>,ErrorObj>{
|
||||
if data.len()>174_764 { return Err(bad("avatar exceeds 128 KiB")); }
|
||||
@@ -205,6 +211,11 @@ pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Op
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn parse_action(value: Value) -> Result<ActionRequest, ErrorObj> {
|
||||
let request = super::parse_action(value)?;
|
||||
validate_action(&request)?;
|
||||
Ok(request)
|
||||
}
|
||||
#[test] fn command_fixture_escapes_and_uses_real_protocol_fields(){
|
||||
let action=Action::KickChannel{reason:"a b|c".into()};
|
||||
let packet=action_command(&action,42,9).unwrap().into_packet();
|
||||
|
||||
@@ -21,8 +21,9 @@ impl Session {
|
||||
let client=&book.clients[&ClientId(request.target.client_id)];
|
||||
let dbid=client.database_id.0;
|
||||
match &request.action {
|
||||
MenuAction::MoveToOwnChannel{password}=>{
|
||||
MenuAction::MoveToOwnChannel{password,expected_channel_id}=>{
|
||||
let own_channel=book.clients.get(&book.own_client).ok_or_else(||menu::bad("own channel unavailable"))?.channel;
|
||||
if own_channel.0!=*expected_channel_id{return Err(ErrorObj::new(ErrorCode::TargetChanged,"own channel changed; reopen the move action"));}
|
||||
if own_channel==client.channel{return Err(menu::bad("client is already in your channel"));}
|
||||
let pw=password.as_ref().filter(|p|!p.is_empty()).map(|p|tsproto_types::crypto::encode_password(p.as_bytes())).unwrap_or_default();
|
||||
let command=menu::command("clientmove",&[("clid",client.id.0.to_string()),("cid",own_channel.0.to_string()),("cpw",pw)]);
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Transport-neutral control output and bounded native playback PCM.
|
||||
use std::{collections::VecDeque, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use tokio::sync::{mpsc, Notify};
|
||||
use crate::protocol::{ErrorObj, Frame};
|
||||
|
||||
const CONTROL_CAPACITY: usize = 1024;
|
||||
const PCM_CAPACITY: usize = 10;
|
||||
|
||||
pub struct PlaybackFrame {
|
||||
pub pcm: Frame,
|
||||
pub speakers: Vec<u16>,
|
||||
pub generation: u64,
|
||||
pub emitted_at: std::time::Instant,
|
||||
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
|
||||
}
|
||||
|
||||
impl Drop for PlaybackFrame {
|
||||
fn drop(&mut self) {
|
||||
let mut speakers = std::mem::take(&mut self.speakers);
|
||||
speakers.clear();
|
||||
self.recycled.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(speakers);
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaybackInner {
|
||||
frames: VecDeque<PlaybackFrame>,
|
||||
closed: bool,
|
||||
}
|
||||
struct PlaybackShared {
|
||||
inner: Mutex<PlaybackInner>,
|
||||
ready: Notify,
|
||||
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
|
||||
}
|
||||
|
||||
pub struct PlaybackReceiver { shared: Arc<PlaybackShared> }
|
||||
impl PlaybackReceiver {
|
||||
pub async fn recv(&mut self) -> Option<PlaybackFrame> {
|
||||
loop {
|
||||
let notified = self.shared.ready.notified();
|
||||
{
|
||||
let mut inner = self.shared.inner.lock().expect("playback queue poisoned");
|
||||
if let Some(frame) = inner.frames.pop_front() { return Some(frame); }
|
||||
if inner.closed { return None; }
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PlaybackReceiver {
|
||||
fn drop(&mut self) {
|
||||
let mut inner = self.shared.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
inner.closed = true;
|
||||
inner.frames.clear();
|
||||
}
|
||||
}
|
||||
|
||||
struct OutputInner {
|
||||
control: mpsc::Sender<Value>,
|
||||
playback: Arc<PlaybackShared>,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
impl Drop for OutputInner {
|
||||
fn drop(&mut self) {
|
||||
self.playback.inner.lock().expect("playback queue poisoned").closed = true;
|
||||
self.playback.ready.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Out { inner: Arc<OutputInner> }
|
||||
impl Out {
|
||||
pub fn new() -> (Self, mpsc::Receiver<Value>, PlaybackReceiver) {
|
||||
let (control, receiver) = mpsc::channel(CONTROL_CAPACITY);
|
||||
let playback = Arc::new(PlaybackShared {
|
||||
inner: Mutex::new(PlaybackInner { frames: VecDeque::with_capacity(PCM_CAPACITY), closed: false }),
|
||||
ready: Notify::new(),
|
||||
recycled: Arc::new(Mutex::new((0..PCM_CAPACITY + 2).map(|_| Vec::with_capacity(16)).collect())),
|
||||
});
|
||||
(Self { inner: Arc::new(OutputInner { control, playback: playback.clone(), generation: AtomicU64::new(0) }) }, receiver, PlaybackReceiver { shared: playback })
|
||||
}
|
||||
pub fn set_generation(&self, generation: u64) { self.inner.generation.store(generation, Ordering::Release); }
|
||||
pub async fn control(&self, mut value: Value) {
|
||||
if let Some(object) = value.as_object_mut().filter(|o| o.contains_key("event")) {
|
||||
object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
|
||||
}
|
||||
let _ = self.inner.control.send(value).await;
|
||||
}
|
||||
pub async fn json<T: Serialize>(&self, value: &T) {
|
||||
match serde_json::to_value(value) {
|
||||
Ok(value) => self.control(value).await,
|
||||
Err(error) => tracing::error!(%error, "could not construct core output"),
|
||||
}
|
||||
}
|
||||
/// Drops oldest playback under congestion; never waits for an audio device.
|
||||
pub fn playback(&self, pcm: &Frame, speakers: &[u16]) -> bool {
|
||||
let mut inner = self.inner.playback.inner.lock().expect("playback queue poisoned");
|
||||
if inner.closed { return false; }
|
||||
let retained = inner.frames.len() < PCM_CAPACITY;
|
||||
if !retained { inner.frames.pop_front(); }
|
||||
let Some(mut speaker_buffer) = self.inner.playback.recycled.lock().expect("playback pool poisoned").pop() else { return false; };
|
||||
speaker_buffer.extend_from_slice(speakers);
|
||||
inner.frames.push_back(PlaybackFrame { pcm: *pcm, speakers: speaker_buffer, generation: self.inner.generation.load(Ordering::Acquire), emitted_at: std::time::Instant::now(), recycled: self.inner.playback.recycled.clone() });
|
||||
drop(inner);
|
||||
self.inner.playback.ready.notify_one();
|
||||
retained
|
||||
}
|
||||
pub async fn ok(&self, id: &str, result: Value) {
|
||||
self.control(json!({"id":id,"ok":true,"result":result})).await;
|
||||
}
|
||||
pub async fn err(&self, id: &str, error: ErrorObj) {
|
||||
self.control(json!({"id":id,"ok":false,"error":error})).await;
|
||||
}
|
||||
pub async fn error_event(&self, error: ErrorObj) {
|
||||
self.control(json!({"event":"error","error":error})).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn playback_discards_oldest_without_relabeling_reconnected_frames() {
|
||||
let (out, _control, mut playback) = Out::new();
|
||||
out.set_generation(7);
|
||||
for value in 0..12 { out.playback(&[value; crate::protocol::FRAME_SAMPLES], &[4, 9]); }
|
||||
out.set_generation(8);
|
||||
for expected in 2..12 {
|
||||
let frame = playback.recv().await.unwrap();
|
||||
assert_eq!(frame.pcm[0], expected);
|
||||
assert_eq!(frame.generation, 7);
|
||||
assert_eq!(frame.speakers, [4, 9]);
|
||||
}
|
||||
assert!(out.playback(&[12; crate::protocol::FRAME_SAMPLES], &[2]));
|
||||
let frame = playback.recv().await.unwrap();
|
||||
assert_eq!(frame.generation, 8);
|
||||
assert_eq!(frame.speakers, [2]);
|
||||
drop(frame);
|
||||
drop(out);
|
||||
assert!(playback.recv().await.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_playback_consumer_refuses_new_audio() {
|
||||
let (out, _control, playback) = Out::new();
|
||||
drop(playback);
|
||||
assert!(!out.playback(&[1; crate::protocol::FRAME_SAMPLES], &[2]));
|
||||
}
|
||||
}
|
||||
+193
-77
@@ -1,4 +1,9 @@
|
||||
//! Bridge protocol v1 (see `docs/bridge.md`): request parsing and error objects.
|
||||
//! Bridge protocol v1 (see `docs/bridge.md`): transport shape parsing and shared typed validation.
|
||||
//!
|
||||
//! Both CLI parsing and embedded requests enter through `validate_command` before
|
||||
//! becoming `Input::Request`. Family parsers decode only transport shapes; their
|
||||
//! semantic validators are dispatched here. Live generation/identity/permission
|
||||
//! checks remain in the session because argument validation cannot replace them.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -27,7 +32,7 @@ const MAX_FIELD_CHARS: usize = 1024;
|
||||
|
||||
pub type Frame = [i16; FRAME_SAMPLES];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ErrorCode {
|
||||
BadRequest,
|
||||
@@ -63,7 +68,7 @@ pub enum ErrorCode {
|
||||
}
|
||||
|
||||
/// TeamSpeak server error attached to an [`ErrorObj`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TsErrorInfo {
|
||||
/// Numeric TeamSpeak error id (e.g. 513 = nickname in use).
|
||||
pub id: u32,
|
||||
@@ -73,7 +78,7 @@ pub struct TsErrorInfo {
|
||||
pub missing_permission: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ErrorObj {
|
||||
pub code: ErrorCode,
|
||||
pub message: String,
|
||||
@@ -125,7 +130,7 @@ pub enum Command {
|
||||
SetPlaybackDsp { agc: bool },
|
||||
StreamList { client_id: Option<u16> },
|
||||
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
|
||||
/// `json` is already compact-serialized and size checked.
|
||||
/// JSON text; `validate_command` requires an object, compacts it and checks its byte size.
|
||||
StreamSignal { stream_id: String, client_id: u16, json: String },
|
||||
StreamLeave { stream_id: String, client_id: u16 },
|
||||
StreamSetup(StreamPublishArgs),
|
||||
@@ -184,6 +189,16 @@ impl Command {
|
||||
}
|
||||
}
|
||||
|
||||
/// A command whose transport-independent arguments have been checked and normalized.
|
||||
/// Only the core can unwrap it; callers must use [`validate_command`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ValidatedCommand(Command);
|
||||
|
||||
impl ValidatedCommand {
|
||||
pub fn name(&self) -> &'static str { self.0.name() }
|
||||
pub(crate) fn into_inner(self) -> Command { self.0 }
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ConnectArgs {
|
||||
@@ -205,7 +220,7 @@ pub struct ConnectArgs {
|
||||
/// One parsed stdin line.
|
||||
#[derive(Debug)]
|
||||
pub enum Input {
|
||||
Request { id: String, cmd: Command },
|
||||
Request { id: String, cmd: ValidatedCommand },
|
||||
AudioFrame(TaggedFrame),
|
||||
AudioEnd,
|
||||
/// The line could not be turned into a command. `id` is set if it could be recovered.
|
||||
@@ -462,7 +477,7 @@ pub fn parse_line(line: &str) -> Input {
|
||||
}
|
||||
None => return Input::Invalid { id: None, error: bad("missing id") },
|
||||
};
|
||||
match parse_command(&env.cmd, env.args) {
|
||||
match parse_command(&env.cmd, env.args).and_then(validate_command) {
|
||||
Ok(cmd) => Input::Request { id, cmd },
|
||||
Err(error) => Input::Invalid { id: Some(id), error },
|
||||
}
|
||||
@@ -483,42 +498,18 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
"rename" => Command::Rename { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
|
||||
"connect" => {
|
||||
let a: ConnectArgs = args_owned(raw)?;
|
||||
check_text("address", &a.address, 255, false)?;
|
||||
check_opt("server_password", &a.server_password)?;
|
||||
check_opt("channel", &a.channel)?;
|
||||
check_opt("channel_password", &a.channel_password)?;
|
||||
check_opt("identity_id", &a.identity_id)?;
|
||||
Command::Connect(a)
|
||||
}
|
||||
"disconnect" => {
|
||||
let a: DisconnectArgs = args_owned(raw)?;
|
||||
check_opt("message", &a.message)?;
|
||||
Command::Disconnect { message: a.message }
|
||||
}
|
||||
"join_channel" => {
|
||||
let a: JoinChannelArgs = args_owned(raw)?;
|
||||
check_opt("password", &a.password)?;
|
||||
Command::JoinChannel { channel_id: a.channel_id, password: a.password }
|
||||
}
|
||||
"send_text" => {
|
||||
let a: SendTextArgs = args_owned(raw)?;
|
||||
if a.message.is_empty() || a.message.len() > MAX_TEXT_BYTES {
|
||||
return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes")));
|
||||
}
|
||||
match (a.target, a.client_id) {
|
||||
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
|
||||
(TextTarget::Channel | TextTarget::Server, Some(_)) => {
|
||||
return Err(bad("client_id is only allowed for target client"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if a.target == TextTarget::Client {
|
||||
if a.client_id == Some(0) { return Err(bad("client_id must be positive")); }
|
||||
let uid = a.expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
|
||||
check_text("expected_client_uid", uid, 128, false)?;
|
||||
} else if a.expected_client_uid.is_some() {
|
||||
return Err(bad("expected_client_uid is only allowed for target client"));
|
||||
}
|
||||
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
|
||||
}
|
||||
"set_audio" => {
|
||||
@@ -531,69 +522,34 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
|
||||
"stream_join" => {
|
||||
let a: StreamJoinArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
check_opt("message", &a.message)?;
|
||||
Command::StreamJoin { stream_id: a.stream_id, client_id: a.client_id, message: a.message }
|
||||
}
|
||||
"stream_signal" => {
|
||||
let a: StreamSignalArgs = args(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
let value: Value = serde_json::from_str(a.json.get())
|
||||
.map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
|
||||
if !value.is_object() {
|
||||
return Err(bad("json must be an object"));
|
||||
}
|
||||
let json = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
|
||||
if json.len() > MAX_SIGNAL_JSON_BYTES {
|
||||
return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes")));
|
||||
}
|
||||
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json }
|
||||
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json: a.json.get().to_owned() }
|
||||
}
|
||||
"stream_leave" => {
|
||||
let a: StreamLeaveArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
Command::StreamLeave { stream_id: a.stream_id, client_id: a.client_id }
|
||||
}
|
||||
"stream_setup" | "stream_update" => {
|
||||
let a: StreamPublishArgs = args_owned(raw)?;
|
||||
if (cmd == "stream_update") != a.stream_id.is_some() {
|
||||
return Err(bad("stream_id is required only for stream_update"));
|
||||
}
|
||||
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
|
||||
check_text("name", &a.name, 200, false)?;
|
||||
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|
||||
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
|
||||
return Err(bad("invalid stream metadata (only P2P is supported)"));
|
||||
}
|
||||
if cmd == "stream_setup" { Command::StreamSetup(a) } else { Command::StreamUpdate(a) }
|
||||
}
|
||||
"stream_stop" => {
|
||||
let a: StreamStopArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
Command::StreamStop { stream_id: a.stream_id }
|
||||
}
|
||||
"stream_respond" => {
|
||||
let a: StreamRespondArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
check_text("message", &a.message, 200, true)?;
|
||||
if a.client_id == 0 || a.decision == a.offer.is_empty() || a.offer.len() > 60000
|
||||
|| a.offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t'))
|
||||
|| a.message.chars().any(char::is_control) {
|
||||
return Err(bad("invalid stream join response"));
|
||||
}
|
||||
Command::StreamRespond { stream_id: a.stream_id, client_id: a.client_id, decision: a.decision, offer: a.offer, message: a.message }
|
||||
}
|
||||
"stream_remove" => {
|
||||
let a: StreamLeaveArgs = args_owned(raw)?;
|
||||
check_stream_id(&a.stream_id)?;
|
||||
if a.client_id == 0 { return Err(bad("client_id must be nonzero")); }
|
||||
Command::StreamRemove { stream_id: a.stream_id, client_id: a.client_id }
|
||||
}
|
||||
"fetch_icon" => {
|
||||
let a: FetchIconArgs = args_owned(raw)?;
|
||||
if a.icon_id == 0 {
|
||||
return Err(bad("icon_id 0 means no icon"));
|
||||
}
|
||||
Command::FetchIcon { icon_id: a.icon_id }
|
||||
}
|
||||
"fetch_avatar" => Command::FetchAvatar { client_id: args_owned::<FetchAvatarArgs>(raw)?.client_id },
|
||||
@@ -604,7 +560,6 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
}
|
||||
"client_context" => {
|
||||
let target = args_owned(raw)?;
|
||||
crate::menu::validate_target(&target)?;
|
||||
Command::ClientContext(target)
|
||||
},
|
||||
"client_action" => Command::ClientAction(crate::menu::parse_action(args_owned(raw)?)?),
|
||||
@@ -622,6 +577,81 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate and normalize typed requests, without serializing commands to JSON.
|
||||
/// Signaling JSON is itself a protocol payload and is compacted for both transports.
|
||||
pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorObj> {
|
||||
let update = matches!(&command, Command::StreamUpdate(_));
|
||||
match &mut command {
|
||||
Command::Connect(a) => {
|
||||
check_text("address", &a.address, 255, false)?;
|
||||
check_opt("server_password", &a.server_password)?;
|
||||
check_opt("channel", &a.channel)?;
|
||||
check_opt("channel_password", &a.channel_password)?;
|
||||
check_opt("identity_id", &a.identity_id)?;
|
||||
}
|
||||
Command::Disconnect { message } => check_opt("message", message)?,
|
||||
Command::JoinChannel { password, .. } => check_opt("password", password)?,
|
||||
Command::SendText { target, client_id, expected_client_uid, message } => {
|
||||
if message.is_empty() || message.len() > MAX_TEXT_BYTES { return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes"))); }
|
||||
match (*target, *client_id) {
|
||||
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
|
||||
(TextTarget::Channel | TextTarget::Server, Some(_)) => return Err(bad("client_id is only allowed for target client")),
|
||||
_ => {}
|
||||
}
|
||||
if *target == TextTarget::Client {
|
||||
if *client_id == Some(0) { return Err(bad("client_id must be positive")); }
|
||||
let uid = expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
|
||||
check_text("expected_client_uid", uid, 128, false)?;
|
||||
} else if expected_client_uid.is_some() { return Err(bad("expected_client_uid is only allowed for target client")); }
|
||||
}
|
||||
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
|
||||
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
|
||||
Command::StreamJoin { stream_id, message, .. } => { check_stream_id(stream_id)?; check_opt("message", message)?; }
|
||||
Command::StreamSignal { stream_id, json, .. } => {
|
||||
check_stream_id(stream_id)?;
|
||||
let value: Value = serde_json::from_str(json).map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
|
||||
if !value.is_object() { return Err(bad("json must be an object")); }
|
||||
let compact = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
|
||||
if compact.len() > MAX_SIGNAL_JSON_BYTES { return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes"))); }
|
||||
*json = compact;
|
||||
}
|
||||
Command::StreamLeave { stream_id, .. } | Command::StreamStop { stream_id } => check_stream_id(stream_id)?,
|
||||
Command::StreamSetup(a) | Command::StreamUpdate(a) => {
|
||||
if update != a.stream_id.is_some() { return Err(bad("stream_id is required only for stream_update")); }
|
||||
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
|
||||
check_text("name", &a.name, 200, false)?;
|
||||
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|
||||
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
|
||||
return Err(bad("invalid stream metadata (only P2P is supported)"));
|
||||
}
|
||||
}
|
||||
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
|
||||
check_stream_id(stream_id)?;
|
||||
check_text("message", message, 200, true)?;
|
||||
if *client_id == 0 || *decision == offer.is_empty() || offer.len() > 60000
|
||||
|| offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) || message.chars().any(char::is_control) {
|
||||
return Err(bad("invalid stream join response"));
|
||||
}
|
||||
}
|
||||
Command::StreamRemove { stream_id, client_id } => {
|
||||
check_stream_id(stream_id)?;
|
||||
if *client_id == 0 { return Err(bad("client_id must be nonzero")); }
|
||||
}
|
||||
Command::FetchIcon { icon_id: 0 } => return Err(bad("icon_id 0 means no icon")),
|
||||
Command::ClientContext(a) => crate::menu::validate_target(a)?,
|
||||
Command::ClientAction(a) => crate::menu::validate_action(a)?,
|
||||
Command::Admin(a) => crate::admin::validate(a)?,
|
||||
Command::Files(a) => crate::file_transfer::validate(a)?,
|
||||
Command::Recording(a) => crate::recording::validate(a)?,
|
||||
Command::Whisper(a) => crate::whisper::validate(a)?,
|
||||
Command::ProfileGet | Command::ProfileCreate { .. } | Command::Rename { .. }
|
||||
| Command::SetAudio { .. } | Command::SetPlaybackDsp { .. } | Command::StreamList { .. }
|
||||
| Command::FetchIcon { .. } | Command::FetchAvatar { .. } | Command::FetchBanner { .. }
|
||||
| Command::FetchServerBanner | Command::Shutdown => {}
|
||||
}
|
||||
Ok(ValidatedCommand(command))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -678,11 +708,11 @@ mod tests {
|
||||
#[test]
|
||||
fn set_transmit_modes_and_sensitivities() {
|
||||
let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
|
||||
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: Command::SetTransmit { vad: None }, .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: None }), .. }));
|
||||
use crate::vad::Sensitivity;
|
||||
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }, .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }, .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }, .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }), .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }), .. }));
|
||||
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }), .. }));
|
||||
for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
|
||||
match parse(bad) {
|
||||
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
|
||||
@@ -695,7 +725,7 @@ mod tests {
|
||||
fn requests_need_valid_id_and_known_args() {
|
||||
assert!(matches!(
|
||||
parse_line(r#"{"id":"a","cmd":"profile_get"}"#),
|
||||
Input::Request { cmd: Command::ProfileGet, .. }
|
||||
Input::Request { cmd: ValidatedCommand(Command::ProfileGet), .. }
|
||||
));
|
||||
match parse_line(r#"{"cmd":"profile_get"}"#) {
|
||||
Input::Invalid { id: None, error } => assert_eq!(error.code, ErrorCode::BadRequest),
|
||||
@@ -733,17 +763,17 @@ mod tests {
|
||||
fn publisher_metadata_and_responses_are_strict() {
|
||||
let metadata = serde_json::json!({"name":"QA | stream", "type":3,"accessibility":3,"mode":1,"bitrate":4500,"viewer_limit":0,"audio":false});
|
||||
let parse = |cmd: &str, args: Value| parse_line(&serde_json::json!({"id":"p","cmd":cmd,"args":args}).to_string());
|
||||
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: Command::StreamSetup(_), .. }));
|
||||
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamSetup(_)), .. }));
|
||||
assert!(matches!(parse("stream_update", metadata.clone()), Input::Invalid { .. }));
|
||||
let mut updated = metadata.clone(); updated["stream_id"] = serde_json::json!("s1");
|
||||
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: Command::StreamUpdate(_), .. }));
|
||||
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamUpdate(_)), .. }));
|
||||
assert!(matches!(parse("stream_setup", updated), Input::Invalid { .. }));
|
||||
for (key, value) in [("type", 4), ("accessibility", 0), ("mode", 2), ("bitrate", 99), ("viewer_limit", -1)] {
|
||||
let mut invalid = metadata.clone(); invalid[key] = serde_json::json!(value);
|
||||
assert!(matches!(parse("stream_setup", invalid), Input::Invalid { .. }), "{key}");
|
||||
}
|
||||
let response = serde_json::json!({"stream_id":"s1","client_id":5,"decision":true,"offer":"v=0\r\n","message":""});
|
||||
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: Command::StreamRespond { decision:true, .. }, .. }));
|
||||
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamRespond { decision:true, .. }), .. }));
|
||||
let mut invalid = response; invalid["offer"] = serde_json::json!("");
|
||||
assert!(matches!(parse("stream_respond", invalid), Input::Invalid { .. }));
|
||||
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":0})), Input::Invalid { .. }));
|
||||
@@ -754,7 +784,7 @@ mod tests {
|
||||
fn stream_signal_json_is_compacted_object() {
|
||||
let line = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":{ "cmd" : "answer", "args": {"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"} }}}"#;
|
||||
match parse_line(line) {
|
||||
Input::Request { cmd: Command::StreamSignal { json, client_id, .. }, .. } => {
|
||||
Input::Request { cmd: ValidatedCommand(Command::StreamSignal { json, client_id, .. }), .. } => {
|
||||
assert_eq!(client_id, 5);
|
||||
assert_eq!(json, r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"}}"#);
|
||||
}
|
||||
@@ -763,4 +793,90 @@ mod tests {
|
||||
let arr = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":[1]}}"#;
|
||||
assert!(matches!(parse_line(arr), Input::Invalid { .. }));
|
||||
}
|
||||
|
||||
fn assert_bad(command: Command) {
|
||||
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_private_text_requires_exact_target_and_uid() {
|
||||
let private = |client_id, expected_client_uid| Command::SendText {
|
||||
target: TextTarget::Client, client_id, expected_client_uid, message: "hello".into(),
|
||||
};
|
||||
assert_bad(private(None, Some("uid".into())));
|
||||
assert_bad(private(Some(0), Some("uid".into())));
|
||||
assert_bad(private(Some(7), None));
|
||||
assert_bad(private(Some(7), Some(String::new())));
|
||||
assert_bad(private(Some(7), Some("x".repeat(129))));
|
||||
let valid = validate_command(private(Some(7), Some("uid".into()))).unwrap();
|
||||
assert_eq!(valid.name(), "send_text");
|
||||
assert_eq!(valid.into_inner(), private(Some(7), Some("uid".into())));
|
||||
for target in [TextTarget::Channel, TextTarget::Server] {
|
||||
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, message: "hello".into() });
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
|
||||
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
|
||||
}
|
||||
}
|
||||
let Input::Invalid { error, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"client","client_id":7,"message":"hello"}}"#) else { panic!() };
|
||||
assert_eq!(error, validate_command(private(Some(7), None)).unwrap_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_signaling_checks_objects_and_compact_byte_limit() {
|
||||
let signal = |json| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json };
|
||||
for json in ["[]", "null", "42", "\"string\"", "{"] { assert_bad(signal(json.into())); }
|
||||
let compact = format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 8));
|
||||
let padded = format!(" {compact}{}", " ".repeat(MAX_SIGNAL_JSON_BYTES));
|
||||
assert_eq!(validate_command(signal(padded)).unwrap().into_inner(), signal(compact));
|
||||
assert_bad(signal(format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 7))));
|
||||
assert_bad(Command::StreamSignal { stream_id: "bad\n".into(), client_id: 7, json: "{}".into() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_publisher_metadata_and_join_response_are_validated() {
|
||||
let args = StreamPublishArgs { stream_id: None, name: "Screen".into(), stream_type: 3,
|
||||
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
|
||||
assert!(validate_command(Command::StreamSetup(args.clone())).is_ok());
|
||||
assert_bad(Command::StreamUpdate(args.clone()));
|
||||
let mut update = args.clone(); update.stream_id = Some("s1".into());
|
||||
assert!(validate_command(Command::StreamUpdate(update.clone())).is_ok());
|
||||
assert_bad(Command::StreamSetup(update));
|
||||
for invalid in [
|
||||
StreamPublishArgs { mode: 2, ..args.clone() },
|
||||
StreamPublishArgs { accessibility: 0, ..args.clone() },
|
||||
StreamPublishArgs { stream_type: 4, ..args.clone() },
|
||||
StreamPublishArgs { bitrate: 99, ..args.clone() },
|
||||
StreamPublishArgs { bitrate: 100001, ..args.clone() },
|
||||
StreamPublishArgs { name: "Screen\n".into(), ..args.clone() },
|
||||
StreamPublishArgs { name: String::new(), ..args },
|
||||
] { assert_bad(Command::StreamSetup(invalid)); }
|
||||
for (client_id, decision, offer, message) in [(0, true, "v=0", ""), (7, true, "", ""),
|
||||
(7, false, "v=0", ""), (7, true, "v=0\0", ""), (7, true, "v=0", "bad\n")] {
|
||||
assert_bad(Command::StreamRespond { stream_id: "s1".into(), client_id, decision, offer: offer.into(), message: message.into() });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_family_commands_cannot_bypass_semantic_checks() {
|
||||
use crate::{admin, file_transfer as files, menu, recording, whisper};
|
||||
let invalid = [
|
||||
Command::Admin(admin::AdminCommand::ChannelMove { generation: 1, channel_id: 7, parent_id: 7, order: None }),
|
||||
Command::Admin(admin::AdminCommand::BanAdd { generation: 1, ip: None, name: None, uid: None, duration_s: 0, reason: None }),
|
||||
Command::Admin(admin::AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 0, channel_id: 0, channel_password: String::new() }),
|
||||
Command::Admin(admin::AdminCommand::Extra(admin::extra::Command::ServerLog { lines: 0, reverse: false, instance: false, begin_pos: 0 })),
|
||||
Command::ClientAction(menu::ActionRequest { target: menu::Target { client_id: 7, uid: "uid".into() }, generation: 1, action: menu::Action::Volume { db: f32::NAN, muted: false } }),
|
||||
Command::Files(files::Request::Config { download_slots: usize::MAX, upload_slots: usize::MAX, download_limit: 0, upload_limit: 0 }),
|
||||
Command::Files(files::Request::Mkdir { channel_id: 7, path: "/../bad".into(), password: String::new() }),
|
||||
Command::Files(files::Request::List { channel_id: 0, path: "/private".into(), password: String::new() }),
|
||||
Command::Files(files::Request::Upload { channel_id: 7, path: "/file".into(), password: String::new(), source: "relative".into(), overwrite: false }),
|
||||
Command::Recording(recording::RecCommand::Start { directory: "relative".into(), mode: recording::Mode::Master, label: None }),
|
||||
Command::Whisper(whisper::WhisperCommand::Stop { epoch: 0 }),
|
||||
Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: f32::NAN }) },
|
||||
Command::SetLocalVolumes(LocalVolumesUpdate { replace: false, volumes: vec![(vec![1], f32::INFINITY)] }),
|
||||
];
|
||||
for command in invalid { assert_bad(command); }
|
||||
let validated = validate_command(Command::Files(files::Request::List { channel_id: 7, path: "/folder".into(), password: String::new() })).unwrap();
|
||||
assert_eq!(validated.into_inner(), Command::Files(files::Request::List { channel_id: 7, path: "/folder/".into(), password: String::new() }));
|
||||
}
|
||||
}
|
||||
+16
-14
@@ -139,22 +139,11 @@ fn valid_label(label: &str) -> bool {
|
||||
}
|
||||
|
||||
pub fn parse(cmd: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj> {
|
||||
Ok(match cmd {
|
||||
let command = match cmd {
|
||||
"recording_start" => {
|
||||
let a: StartArgs = parse_args(raw)?;
|
||||
if a.directory.is_empty() || a.directory.len() > 1024 || a.directory.chars().any(char::is_control) {
|
||||
return Err(bad("directory must be 1-1024 characters without control characters"));
|
||||
}
|
||||
let directory = PathBuf::from(&a.directory);
|
||||
if !directory.is_absolute() {
|
||||
return Err(bad("directory must be an absolute path"));
|
||||
}
|
||||
let directory = PathBuf::from(a.directory);
|
||||
let mode = Mode::from_num(a.mode).ok_or_else(|| bad("mode must be 1 (multitrack), 2 (master) or 3 (both)"))?;
|
||||
if let Some(l) = &a.label {
|
||||
if !valid_label(l) {
|
||||
return Err(bad("label must be YYYY-MM-DD_HH-MM-SS"));
|
||||
}
|
||||
}
|
||||
RecCommand::Start { directory, mode, label: a.label }
|
||||
}
|
||||
"recording_waveform" => {
|
||||
@@ -172,7 +161,20 @@ pub fn parse(cmd: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj>
|
||||
}
|
||||
}
|
||||
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
|
||||
})
|
||||
};
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
pub(crate) fn validate(command: &RecCommand) -> Result<(), ErrorObj> {
|
||||
if let RecCommand::Start { directory, label, .. } = command {
|
||||
let text = directory.to_str().ok_or_else(|| bad("directory must be valid UTF-8"))?;
|
||||
if text.is_empty() || text.len() > 1024 || text.chars().any(char::is_control) {
|
||||
return Err(bad("directory must be 1-1024 characters without control characters"));
|
||||
}
|
||||
if !directory.is_absolute() { return Err(bad("directory must be an absolute path")); }
|
||||
if label.as_deref().is_some_and(|l| !valid_label(l)) { return Err(bad("label must be YYYY-MM-DD_HH-MM-SS")); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- identity
|
||||
|
||||
@@ -12,6 +12,12 @@ use super::*;
|
||||
use crate::audio::{Receiver as AudioReceiver, TxCodec, TxEncoder};
|
||||
use crate::vad::tests::speech_frames;
|
||||
|
||||
fn parse(name: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj> {
|
||||
let command = super::parse(name, raw)?;
|
||||
validate(&command)?;
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
const ALICE_UID: &[u8] = b"alice-uid-0123456789";
|
||||
const BOB_UID: &[u8] = b"bob-uid-0123456789ab";
|
||||
const CAROL_UID: &[u8] = b"carol-uid-0123456789";
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
//! Embedded session lifetime. The host owns one handle per server; no stdio or UI loop is required.
|
||||
use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input}, session::Session};
|
||||
|
||||
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("core startup or shutdown failed: {0}")]
|
||||
pub struct CoreStartError(pub String);
|
||||
|
||||
type Pending = Arc<Mutex<HashMap<String, oneshot::Sender<Result<Value, ErrorObj>>>>>;
|
||||
pub struct CoreEvents {
|
||||
pub control: mpsc::Receiver<Value>,
|
||||
pub playback: PlaybackReceiver,
|
||||
}
|
||||
|
||||
pub struct CoreHandle {
|
||||
commands: Option<mpsc::Sender<Input>>,
|
||||
pending: Pending,
|
||||
next_request: AtomicU64,
|
||||
audio: Arc<AudioInQueue>,
|
||||
cancel: Option<oneshot::Sender<()>>,
|
||||
finished: Option<oneshot::Receiver<()>>,
|
||||
worker: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn stopped() -> ErrorObj { ErrorObj::new(ErrorCode::NotConnected, "core session stopped") }
|
||||
fn fail_pending(pending: &Pending) {
|
||||
let mut requests = pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for (_, reply) in requests.drain() { let _ = reply.send(Err(stopped())); }
|
||||
}
|
||||
|
||||
struct WorkerCleanup(Pending);
|
||||
impl Drop for WorkerCleanup {
|
||||
fn drop(&mut self) { fail_pending(&self.0); }
|
||||
}
|
||||
|
||||
struct PendingRequest { id: String, pending: Pending }
|
||||
impl Drop for PendingRequest {
|
||||
fn drop(&mut self) { self.pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.id); }
|
||||
}
|
||||
|
||||
impl CoreHandle {
|
||||
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
|
||||
let command = validate_command(command)?;
|
||||
let commands = self.commands.as_ref().ok_or_else(stopped)?;
|
||||
let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string();
|
||||
let (reply, receiver) = oneshot::channel();
|
||||
self.pending.lock().expect("pending requests poisoned").insert(id.clone(), reply);
|
||||
let _guard = PendingRequest { id: id.clone(), pending: self.pending.clone() };
|
||||
commands.send(Input::Request { id, cmd: command }).await.map_err(|_| stopped())?;
|
||||
receiver.await.unwrap_or_else(|_| Err(stopped()))
|
||||
}
|
||||
pub fn push_audio(&self, frame: CapturedFrame) -> bool { self.audio.try_push(frame) }
|
||||
pub fn invalidate_audio(&self) -> u64 { self.audio.invalidate() }
|
||||
pub fn audio_epoch(&self) -> u64 { self.audio.epoch() }
|
||||
pub fn connection_generation(&self) -> u64 { self.audio.generation() }
|
||||
pub fn end_audio(&self) { self.audio.push(AudioIn::End); }
|
||||
pub async fn shutdown(mut self) -> Result<(), CoreStartError> {
|
||||
self.audio.invalidate();
|
||||
self.commands.take();
|
||||
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
|
||||
if let Some(finished) = self.finished.take() { let _ = finished.await; }
|
||||
if let Some(worker) = self.worker.take() {
|
||||
worker.join().map_err(|_| CoreStartError("core worker panicked".into()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for CoreHandle {
|
||||
fn drop(&mut self) {
|
||||
self.audio.invalidate();
|
||||
self.commands.take();
|
||||
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
|
||||
fail_pending(&self.pending);
|
||||
// Explicit shutdown awaits completion. Drop signals cancellation without blocking a UI thread.
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(config: CoreConfig) -> Result<(CoreHandle, CoreEvents), CoreStartError> {
|
||||
if !config.data_dir.is_absolute() || !config.connection_dir.is_absolute() || config.data_dir == config.connection_dir {
|
||||
return Err(CoreStartError("data and connection directories must be distinct absolute paths".into()));
|
||||
}
|
||||
let locks = locks::lock_run(&config.data_dir, Some(&config.connection_dir)).map_err(CoreStartError)?;
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| CoreStartError(e.to_string()))?;
|
||||
let (commands, command_rx) = mpsc::channel(64);
|
||||
let (cancel, cancel_rx) = oneshot::channel();
|
||||
let (finished_tx, finished) = oneshot::channel();
|
||||
let (events, control) = mpsc::channel(1024);
|
||||
let (out, mut out_rx, playback) = Out::new();
|
||||
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||
let worker_pending = pending.clone();
|
||||
let audio = Arc::new(AudioInQueue::new());
|
||||
let worker_audio = audio.clone();
|
||||
let worker = thread::Builder::new().name("teamspeach-core".into()).spawn(move || {
|
||||
let _locks = locks;
|
||||
let _cleanup = WorkerCleanup(worker_pending.clone());
|
||||
runtime.block_on(async move {
|
||||
let (failure_tx, failure_rx) = oneshot::channel::<()>();
|
||||
let mut failure_tx = Some(failure_tx);
|
||||
let cancel = async { tokio::select! { _ = cancel_rx => {}, _ = failure_rx => {} } };
|
||||
let mut session = Box::pin(Session::new(Store::new(&config.data_dir), out, worker_audio).run_with_cancel(command_rx, cancel));
|
||||
let mut session_finished = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = &mut session, if !session_finished => { session_finished = true; },
|
||||
value = out_rx.recv() => {
|
||||
let Some(value) = value else { break };
|
||||
if let Some(id) = value.get("id").and_then(Value::as_str) {
|
||||
let reply = worker_pending.lock().expect("pending requests poisoned").remove(id);
|
||||
if let Some(reply) = reply {
|
||||
let result = if value.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(value.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(serde_json::from_value(value.get("error").cloned().unwrap_or(Value::Null))
|
||||
.unwrap_or_else(|_| ErrorObj::new(ErrorCode::Internal, "invalid core error response")))
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
} else {
|
||||
// A stalled/dead host cannot stall network polling or command replies.
|
||||
if failure_tx.is_some() && events.try_send(value).is_err() {
|
||||
if let Some(cancel) = failure_tx.take() { let _ = cancel.send(()); }
|
||||
fail_pending(&worker_pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fail_pending(&worker_pending);
|
||||
});
|
||||
drop(runtime);
|
||||
drop(_locks);
|
||||
let _ = finished_tx.send(());
|
||||
}).map_err(|e| CoreStartError(e.to_string()))?;
|
||||
Ok((CoreHandle { commands: Some(commands), pending, next_request: AtomicU64::new(1), audio,
|
||||
cancel: Some(cancel), finished: Some(finished), worker: Some(worker) }, CoreEvents { control, playback }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn worker_unwind_completes_retained_requests_even_with_poisoned_map() {
|
||||
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||
let (reply, mut receiver) = oneshot::channel();
|
||||
pending.lock().unwrap().insert("pending".into(), reply);
|
||||
let captured = pending.clone();
|
||||
let result = std::panic::catch_unwind(move || {
|
||||
let _cleanup = WorkerCleanup(captured.clone());
|
||||
let _held = captured.lock().unwrap();
|
||||
panic!("controlled worker failure");
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(receiver.try_recv().unwrap().unwrap_err().code, ErrorCode::NotConnected);
|
||||
assert!(pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_waiter_releases_its_pending_sender() {
|
||||
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||
let (reply, mut receiver) = oneshot::channel();
|
||||
pending.lock().unwrap().insert("cancelled".into(), reply);
|
||||
drop(PendingRequest { id: "cancelled".into(), pending: pending.clone() });
|
||||
assert!(matches!(receiver.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
|
||||
assert!(pending.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
+67
-34
@@ -1,6 +1,7 @@
|
||||
//! The session: owns the tsclientlib connection and maps bridge commands/events onto it.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::future::Future;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -26,7 +27,7 @@ use crate::menu::{self, Action as MenuAction, ActionRequest, Target};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use md5::{Digest, Md5};
|
||||
use crate::profile::{store_error, validate_nickname, Store, StoreError, StoredIdentity};
|
||||
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
|
||||
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
|
||||
use crate::admin;
|
||||
#[path = "menu_session.rs"]
|
||||
mod menu_session;
|
||||
@@ -42,7 +43,8 @@ mod whisper_session;
|
||||
mod voice_dsp_session;
|
||||
use crate::rawcmd;
|
||||
use crate::snapshot::{self, RawExtras};
|
||||
use crate::stdio::Out;
|
||||
use crate::output::Out;
|
||||
use crate::audio::CapturedFrame;
|
||||
|
||||
const DEFAULT_PORT: u16 = 9987;
|
||||
const SNAPSHOT_MIN_INTERVAL: Duration = Duration::from_millis(50);
|
||||
@@ -242,7 +244,7 @@ pub struct Session {
|
||||
whisper: crate::whisper::Whisper,
|
||||
/// Persisted per-user volumes and playback DSP flags pushed by the app (outlive connections).
|
||||
voice: crate::voice_dsp::VoiceSettings,
|
||||
preroll_buf: Box<[Frame; MAX_PREROLL_FRAMES]>,
|
||||
preroll_buf: Box<[Option<CapturedFrame>; MAX_PREROLL_FRAMES]>,
|
||||
pcm: Box<[i16; FRAME_SAMPLES]>,
|
||||
rev: u64,
|
||||
exit: Exit,
|
||||
@@ -279,7 +281,7 @@ impl Session {
|
||||
vad: None,
|
||||
whisper: Default::default(),
|
||||
voice: Default::default(),
|
||||
preroll_buf: Box::new([[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES]),
|
||||
preroll_buf: Box::new(std::array::from_fn(|_| None)),
|
||||
pcm: Box::new([0; FRAME_SAMPLES]),
|
||||
rev: 0,
|
||||
exit: Exit::Running,
|
||||
@@ -295,14 +297,31 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(mut self, mut cmds: mpsc::Receiver<Input>) {
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
loop {
|
||||
pub async fn run(self, cmds: mpsc::Receiver<Input>) {
|
||||
self.run_with_cancel(cmds, std::future::pending()).await;
|
||||
}
|
||||
|
||||
pub async fn run_embedded(self, cmds: mpsc::Receiver<Input>, cancel: tokio::sync::oneshot::Receiver<()>) {
|
||||
self.run_with_cancel(cmds, async { let _ = cancel.await; }).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn run_with_cancel(mut self, mut cmds: mpsc::Receiver<Input>, cancel: impl Future<Output = ()>) {
|
||||
tokio::pin!(cancel);
|
||||
let mut cancelled = false;
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
loop {
|
||||
self.check_exit().await;
|
||||
if matches!(self.exit, Exit::Done) {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = &mut cancel, if !cancelled => {
|
||||
cancelled = true;
|
||||
self.audio_in.invalidate();
|
||||
self.stdin_closed = true;
|
||||
cmds.close();
|
||||
self.begin_exit(None).await;
|
||||
},
|
||||
ev = next_event(&mut self.conn) => self.on_conn_event(ev).await,
|
||||
input = cmds.recv(), if !self.stdin_closed => match input {
|
||||
Some(input) => self.on_input(input).await,
|
||||
@@ -386,7 +405,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
debug!(cmd = cmd.name(), "request");
|
||||
self.handle(id, cmd).await;
|
||||
self.handle(id, cmd.into_inner()).await;
|
||||
}
|
||||
Input::Invalid { id: Some(id), error } => self.out.err(&id, error).await,
|
||||
Input::Invalid { id: None, error } => self.out.error_event(error).await,
|
||||
@@ -528,6 +547,8 @@ impl Session {
|
||||
let con = options.connect().map_err(|e| lib_error(ErrorCode::ConnectFailed, &e))?;
|
||||
info!(uid = %identity.uid, address = %args.address, "connecting");
|
||||
self.generation += 1;
|
||||
self.audio_in.set_generation(self.generation);
|
||||
self.out.set_generation(self.generation);
|
||||
self.conn = Some(Conn {
|
||||
con,
|
||||
address: args.address.clone(),
|
||||
@@ -633,6 +654,7 @@ impl Session {
|
||||
}
|
||||
|
||||
async fn set_audio(&mut self, id: &str, input_muted: Option<bool>, output_muted: Option<bool>) -> Result<Option<Value>, ErrorObj> {
|
||||
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
|
||||
if let Some(m) = input_muted {
|
||||
self.flags.input_muted = m;
|
||||
}
|
||||
@@ -896,6 +918,7 @@ impl Session {
|
||||
// ------------------------------------------------------------ exit
|
||||
|
||||
async fn begin_exit(&mut self, req: Option<String>) {
|
||||
self.audio_in.invalidate();
|
||||
if !matches!(self.exit, Exit::Running) {
|
||||
if let Some(r) = req {
|
||||
self.out.err(&r, ErrorObj::new(ErrorCode::BadRequest, "already shutting down")).await;
|
||||
@@ -1041,6 +1064,8 @@ impl Session {
|
||||
self.rx_reset().await;
|
||||
if let Some(c) = &mut self.conn {
|
||||
self.generation += 1;
|
||||
self.audio_in.set_generation(self.generation);
|
||||
self.out.set_generation(self.generation);
|
||||
c.generation = self.generation;
|
||||
c.permissions = menu::Permissions::default();
|
||||
c.gains.clear();
|
||||
@@ -1285,6 +1310,7 @@ impl Session {
|
||||
|
||||
/// Drop the connection and emit `state: disconnected`. `respond` answers a disconnect request.
|
||||
async fn close_conn(&mut self, reason: Option<ErrorObj>, respond: Option<(String, Value)>) {
|
||||
self.audio_in.invalidate();
|
||||
self.recording_finish("disconnected", None).await;
|
||||
self.fail_pending("connection closed before the server answered").await;
|
||||
self.fail_media("connection closed before the download finished").await;
|
||||
@@ -1370,8 +1396,7 @@ impl Session {
|
||||
}
|
||||
while let Some(item) = self.audio_in.pop() {
|
||||
match item {
|
||||
AudioIn::Frame(f) => self.tx_frame(&f, None).await,
|
||||
AudioIn::Whisper(f, epoch) => self.tx_frame(&f, Some(epoch)).await,
|
||||
AudioIn::Frame(f) => self.tx_frame(&f).await,
|
||||
AudioIn::End => self.tx_end().await,
|
||||
}
|
||||
}
|
||||
@@ -1424,13 +1449,15 @@ impl Session {
|
||||
|
||||
/// One captured frame. `whisper` is the epoch the renderer tagged it with while a whisper key was held:
|
||||
/// such a frame goes only to that whisper route (or nowhere); an untagged frame is ordinary voice.
|
||||
async fn tx_frame(&mut self, frame: &Frame, whisper: Option<u32>) {
|
||||
async fn tx_frame(&mut self, frame: &CapturedFrame) {
|
||||
if !self.audio_in.validate(frame) { return; }
|
||||
let whisper = frame.whisper;
|
||||
// Capture queued before push-to-whisper must not escape to the ordinary channel.
|
||||
if whisper.is_none() && self.whisper.active_epoch().is_some() {
|
||||
return;
|
||||
}
|
||||
self.tx.burst_open = true;
|
||||
self.tx.last_frame = Some(Instant::now());
|
||||
self.tx.last_frame = Some(frame.captured_at);
|
||||
let Some(route) = self.tx_route().await else {
|
||||
// Nothing may be sent now; forget what voice activation heard so it is never sent later.
|
||||
self.vad_reset();
|
||||
@@ -1457,13 +1484,15 @@ impl Session {
|
||||
vad.gate.reset();
|
||||
vad.route = Some(route);
|
||||
}
|
||||
let decision = vad.gate.push(frame);
|
||||
let held = if decision == Decision::Start { vad.gate.take_preroll(&mut self.preroll_buf) } else { 0 };
|
||||
let decision = vad.gate.push_captured(frame);
|
||||
let held = if decision == Decision::Start { vad.gate.take_captured_preroll(&mut self.preroll_buf) } else { 0 };
|
||||
match decision {
|
||||
Decision::Hold => {}
|
||||
Decision::Start => {
|
||||
for i in 0..held {
|
||||
let earlier = self.preroll_buf[i];
|
||||
let Some(earlier) = self.preroll_buf[i].take() else { continue; };
|
||||
if earlier.capture_epoch != self.audio_in.epoch() || earlier.connection_generation != self.audio_in.generation() { return; }
|
||||
if !self.audio_in.validate(&earlier) { continue; }
|
||||
if !self.tx_send(&earlier, tx_codec, quality, None).await {
|
||||
return;
|
||||
}
|
||||
@@ -1483,7 +1512,8 @@ impl Session {
|
||||
|
||||
/// Encodes and sends one frame as ordinary voice (`whisper` = `None`) or to the whisper route of that
|
||||
/// epoch; returns false if it could not be sent (reported once per burst; whisper drops are silent).
|
||||
async fn tx_send(&mut self, frame: &Frame, tx_codec: TxCodec, quality: u8, whisper: Option<u32>) -> bool {
|
||||
async fn tx_send(&mut self, frame: &CapturedFrame, tx_codec: TxCodec, quality: u8, whisper: Option<u32>) -> bool {
|
||||
if !self.audio_in.validate(frame) { return false; }
|
||||
if self.tx.transmitting && self.whisper.spurt() != whisper {
|
||||
// The open transmission belongs to another route and ends there before this one starts.
|
||||
self.end_spurt().await;
|
||||
@@ -1524,19 +1554,22 @@ impl Session {
|
||||
}
|
||||
let encoder = self.tx.encoder.as_mut().expect("set above");
|
||||
let route = whisper.and_then(|epoch| self.whisper.route_mut(epoch, generation));
|
||||
let packet = match encoder.encode_to(frame, route) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if let Err(e) = c.con.send_audio(packet) {
|
||||
self.report_once(lib_error(ErrorCode::Io, &e)).await;
|
||||
return false;
|
||||
}
|
||||
let sent = self.audio_in.with_valid_frame(frame, || {
|
||||
let packet = encoder.encode_to(&frame.pcm, route)
|
||||
.map_err(|e| ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}")))?;
|
||||
if !self.audio_in.validate(frame) { return Ok(false); }
|
||||
let metadata = tsclientlib::AudioSendMetadata { captured_at: frame.captured_at,
|
||||
connection_generation: frame.connection_generation, capture_epoch: frame.capture_epoch };
|
||||
c.con.send_audio_guarded(packet, metadata, self.audio_in.clone()).map_err(|e| lib_error(ErrorCode::Io, &e))?;
|
||||
Ok(true)
|
||||
});
|
||||
match sent {
|
||||
Some(Ok(true)) => {},
|
||||
Some(Err(error)) => { self.report_once(error).await; return false; },
|
||||
_ => return false,
|
||||
}
|
||||
if let Some(r) = self.rec.as_mut() {
|
||||
r.capture(frame);
|
||||
r.capture(&frame.pcm);
|
||||
}
|
||||
if !self.tx.transmitting {
|
||||
self.tx.transmitting = true;
|
||||
@@ -1640,15 +1673,15 @@ impl Session {
|
||||
None => c.rx.mix(&mut self.pcm, gain),
|
||||
};
|
||||
let stopped = mixed.stopped;
|
||||
let line = (!mixed.speakers.is_empty() && !self.flags.output_muted)
|
||||
.then(|| audio::audio_event_line(&self.pcm, mixed.speakers));
|
||||
let playback = (!mixed.speakers.is_empty() && !self.flags.output_muted)
|
||||
.then(|| self.out.playback(&self.pcm, mixed.speakers));
|
||||
for cid in stopped {
|
||||
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
|
||||
}
|
||||
if let Some(line) = line {
|
||||
if !self.out.try_line(line) && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
|
||||
self.audio_drop_warned = Some(now);
|
||||
warn!("stdout is congested, dropping playback audio");
|
||||
if let Some(retained) = playback {
|
||||
if !retained && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
|
||||
self.audio_drop_warned = Some(now);
|
||||
warn!("playback consumer is congested, dropping oldest audio");
|
||||
}
|
||||
}
|
||||
self.recording_after_mix().await;
|
||||
|
||||
+38
-65
@@ -3,73 +3,41 @@
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncWriteExt, BufWriter};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::audio::{AudioIn, AudioInQueue};
|
||||
use crate::audio::{AudioIn, AudioInQueue, CapturedFrame};
|
||||
use crate::protocol::{self, ErrorCode, ErrorObj, Input, MAX_LINE_BYTES};
|
||||
use crate::output::PlaybackReceiver;
|
||||
|
||||
/// Control lines (responses/events) are awaited; audio lines are dropped when the pipe is full.
|
||||
const OUT_QUEUE: usize = 1024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Out {
|
||||
tx: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
pub fn new() -> (Self, mpsc::Receiver<String>) {
|
||||
let (tx, rx) = mpsc::channel(OUT_QUEUE);
|
||||
(Self { tx }, rx)
|
||||
}
|
||||
|
||||
pub async fn line(&self, line: String) {
|
||||
if self.tx.send(line).await.is_err() {
|
||||
error!("stdout writer is gone");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn json<T: Serialize>(&self, value: &T) {
|
||||
match serde_json::to_string(value) {
|
||||
Ok(s) => self.line(s).await,
|
||||
Err(e) => error!(%e, "failed to serialize output"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-blocking send for high-rate audio. Returns false if dropped.
|
||||
pub fn try_line(&self, line: String) -> bool { self.tx.try_send(line).is_ok() }
|
||||
|
||||
pub async fn ok(&self, id: &str, result: serde_json::Value) {
|
||||
self.json(&serde_json::json!({ "id": id, "ok": true, "result": result })).await
|
||||
}
|
||||
|
||||
pub async fn err(&self, id: &str, error: ErrorObj) {
|
||||
self.json(&serde_json::json!({ "id": id, "ok": false, "error": error })).await
|
||||
}
|
||||
|
||||
pub async fn error_event(&self, error: ErrorObj) {
|
||||
self.json(&serde_json::json!({ "event": "error", "error": error })).await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_writer(mut rx: mpsc::Receiver<String>) {
|
||||
let mut out = BufWriter::new(tokio::io::stdout());
|
||||
while let Some(first) = rx.recv().await {
|
||||
let mut line = Some(first);
|
||||
while let Some(l) = line {
|
||||
if out.write_all(l.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() {
|
||||
error!("stdout closed");
|
||||
return;
|
||||
}
|
||||
line = rx.try_recv().ok();
|
||||
}
|
||||
if out.flush().await.is_err() {
|
||||
error!("stdout closed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
/// The diagnostic CLI alone serializes native events and PCM onto stdout.
|
||||
pub async fn run_writer(mut rx: mpsc::Receiver<serde_json::Value>, mut playback: PlaybackReceiver) {
|
||||
let mut out = BufWriter::new(tokio::io::stdout());
|
||||
let mut control_open = true;
|
||||
let mut audio_open = true;
|
||||
while control_open || audio_open {
|
||||
let line = tokio::select! {
|
||||
biased;
|
||||
value = rx.recv(), if control_open => match value {
|
||||
Some(value) => match serde_json::to_string(&value) {
|
||||
Ok(line) => Some(line),
|
||||
Err(error) => { error!(%error, "cannot serialize CLI output"); None }
|
||||
},
|
||||
None => { control_open = false; None }
|
||||
},
|
||||
frame = playback.recv(), if audio_open => match frame {
|
||||
Some(frame) => Some(crate::audio::audio_event_line(&frame.pcm, &frame.speakers)),
|
||||
None => { audio_open = false; None }
|
||||
},
|
||||
};
|
||||
if let Some(line) = line {
|
||||
if out.write_all(line.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() || out.flush().await.is_err() {
|
||||
error!("stdout closed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking stdin reader (runs on its own thread). Lines longer than [`MAX_LINE_BYTES`] are
|
||||
@@ -131,10 +99,15 @@ pub fn run_reader(input: impl Read, cmds: mpsc::Sender<Input>, audio: Arc<AudioI
|
||||
input
|
||||
};
|
||||
match input {
|
||||
Input::AudioFrame(f) => audio.push(match f.whisper {
|
||||
None => AudioIn::Frame(f.pcm),
|
||||
Some(epoch) => AudioIn::Whisper(f.pcm, epoch),
|
||||
}),
|
||||
Input::AudioFrame(f) => {
|
||||
audio.try_push(CapturedFrame {
|
||||
pcm: *f.pcm,
|
||||
captured_at: std::time::Instant::now(),
|
||||
capture_epoch: audio.epoch(),
|
||||
connection_generation: audio.generation(),
|
||||
whisper: f.whisper,
|
||||
});
|
||||
},
|
||||
Input::AudioEnd => audio.push(AudioIn::End),
|
||||
other => {
|
||||
if cmds.blocking_send(other).is_err() {
|
||||
|
||||
+167
-4
@@ -18,6 +18,7 @@
|
||||
|
||||
use earshot::Detector;
|
||||
|
||||
use crate::audio::CapturedFrame;
|
||||
use crate::protocol::{Frame, FRAME_SAMPLES};
|
||||
|
||||
/// Frames kept from before the onset so the start of a word is not cut off (5 × 20 ms = 100 ms).
|
||||
@@ -36,11 +37,11 @@ pub const MAX_LEVEL_DB: f32 = 50.0;
|
||||
pub const DEFAULT_LEVEL_DB: f32 = -30.0;
|
||||
|
||||
/// Frames after a reset during which the gate cannot open: a freshly reset network scores the first
|
||||
/// ~150 ms of any input (noise, clicks) higher than it settles to. Nothing heard in that time is lost:
|
||||
/// every frame since the reset is kept (see [`MAX_PREROLL_FRAMES`]) and sent if speech opens the gate.
|
||||
/// ~150 ms of any input (noise, clicks) higher than it settles to. Startup audio is
|
||||
/// held, but the capture-age limit still applies before network transmission.
|
||||
pub const WARMUP_FRAMES: u32 = 10;
|
||||
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms). The first spurt after a
|
||||
/// reset sends everything since the reset; later spurts send the last [`PREROLL_FRAMES`].
|
||||
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms).
|
||||
/// The consumer must reject expired held frames, including this first spurt.
|
||||
pub const MAX_PREROLL_FRAMES: usize = WARMUP_FRAMES as usize + PREROLL_FRAMES;
|
||||
/// Detector input: 16 ms at 16 kHz.
|
||||
const WINDOW: usize = 256;
|
||||
@@ -187,6 +188,14 @@ impl Decimator {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct CaptureMetadata {
|
||||
captured_at: std::time::Instant,
|
||||
connection_generation: u64,
|
||||
capture_epoch: u64,
|
||||
whisper: Option<u32>,
|
||||
}
|
||||
|
||||
pub struct VoiceGate {
|
||||
detector: Box<Detector>,
|
||||
decimator: Decimator,
|
||||
@@ -200,6 +209,8 @@ pub struct VoiceGate {
|
||||
/// Frames left before the spurt ends; 0 = idle.
|
||||
hangover: u32,
|
||||
preroll: [Frame; MAX_PREROLL_FRAMES],
|
||||
preroll_metadata: [Option<CaptureMetadata>; MAX_PREROLL_FRAMES],
|
||||
capture_context: Option<(u64, u64, Option<u32>)>,
|
||||
preroll_start: usize,
|
||||
preroll_len: usize,
|
||||
/// Frames left in the post-reset warm-up.
|
||||
@@ -222,6 +233,8 @@ impl VoiceGate {
|
||||
voiced_run: 0,
|
||||
hangover: 0,
|
||||
preroll: [[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES],
|
||||
preroll_metadata: [None; MAX_PREROLL_FRAMES],
|
||||
capture_context: None,
|
||||
preroll_start: 0,
|
||||
preroll_len: 0,
|
||||
warmup: WARMUP_FRAMES,
|
||||
@@ -265,6 +278,8 @@ impl VoiceGate {
|
||||
self.hangover = 0;
|
||||
self.preroll_len = 0;
|
||||
self.preroll_start = 0;
|
||||
self.preroll_metadata.fill(None);
|
||||
self.capture_context = None;
|
||||
}
|
||||
|
||||
/// Runs the detector over one frame and returns whether any 16 ms window in it was voiced and
|
||||
@@ -313,6 +328,32 @@ impl VoiceGate {
|
||||
/// Classifies `frame`. On [`Decision::Start`], the caller sends [`VoiceGate::take_preroll`] and then
|
||||
/// `frame`; the current frame is never part of the preroll.
|
||||
pub fn push(&mut self, frame: &Frame) -> Decision {
|
||||
// Raw PCM is for detector analysis, never a replacement for capture tags.
|
||||
if self.capture_context.is_some() { self.reset(); }
|
||||
self.classify(frame)
|
||||
}
|
||||
|
||||
/// Classify captured PCM without losing its original timestamp or routing tags.
|
||||
/// A new boundary resets detector state as well as its held frames. Validation
|
||||
/// remains the consumer's responsibility, both here and before every actual send.
|
||||
pub fn push_captured(&mut self, frame: &CapturedFrame) -> Decision {
|
||||
let context = (frame.connection_generation, frame.capture_epoch, frame.whisper);
|
||||
if self.capture_context != Some(context) { self.reset(); }
|
||||
self.capture_context = Some(context);
|
||||
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
|
||||
let decision = self.classify(&frame.pcm);
|
||||
if decision == Decision::Hold {
|
||||
self.preroll_metadata[slot] = Some(CaptureMetadata {
|
||||
captured_at: frame.captured_at,
|
||||
connection_generation: frame.connection_generation,
|
||||
capture_epoch: frame.capture_epoch,
|
||||
whisper: frame.whisper,
|
||||
});
|
||||
}
|
||||
decision
|
||||
}
|
||||
|
||||
fn classify(&mut self, frame: &Frame) -> Decision {
|
||||
let (keep_level, open_level) = self.level(frame);
|
||||
let (voiced, onset) = match self.mode {
|
||||
GateMode::VolumeGate { .. } => (keep_level, open_level),
|
||||
@@ -343,6 +384,7 @@ impl VoiceGate {
|
||||
fn remember(&mut self, frame: &Frame) {
|
||||
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
|
||||
self.preroll[slot] = *frame;
|
||||
self.preroll_metadata[slot] = None;
|
||||
if self.preroll_len < MAX_PREROLL_FRAMES {
|
||||
self.preroll_len += 1;
|
||||
} else {
|
||||
@@ -361,15 +403,136 @@ impl VoiceGate {
|
||||
}
|
||||
self.preroll_start = 0;
|
||||
self.preroll_len = 0;
|
||||
self.preroll_metadata.fill(None);
|
||||
self.since_reset = false;
|
||||
keep
|
||||
}
|
||||
|
||||
/// Drain original capture envelopes, oldest first, without per-frame allocation.
|
||||
/// Output entries beyond the returned length are cleared. Even a valid current
|
||||
/// frame does not authorize these frames: check each one's age/epoch/generation
|
||||
/// with the input queue immediately before encoding and network enqueue.
|
||||
pub fn take_captured_preroll(&mut self, out: &mut [Option<CapturedFrame>; MAX_PREROLL_FRAMES]) -> usize {
|
||||
let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
|
||||
let skip = self.preroll_len - keep;
|
||||
out.fill(None);
|
||||
let mut written = 0;
|
||||
for i in 0..keep {
|
||||
let slot = (self.preroll_start + skip + i) % MAX_PREROLL_FRAMES;
|
||||
if let Some(metadata) = self.preroll_metadata[slot].take() {
|
||||
out[written] = Some(CapturedFrame {
|
||||
pcm: self.preroll[slot],
|
||||
captured_at: metadata.captured_at,
|
||||
connection_generation: metadata.connection_generation,
|
||||
capture_epoch: metadata.capture_epoch,
|
||||
whisper: metadata.whisper,
|
||||
});
|
||||
written += 1;
|
||||
}
|
||||
}
|
||||
self.preroll_start = 0;
|
||||
self.preroll_len = 0;
|
||||
self.preroll_metadata.fill(None);
|
||||
self.since_reset = false;
|
||||
written
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
|
||||
fn captured_frame(queue: &crate::audio::AudioInQueue, sample: i16) -> CapturedFrame {
|
||||
CapturedFrame {
|
||||
pcm: [sample; FRAME_SAMPLES],
|
||||
captured_at: std::time::Instant::now(),
|
||||
connection_generation: queue.generation(),
|
||||
capture_epoch: queue.epoch(),
|
||||
whisper: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_preroll_preserves_original_age_and_routing() {
|
||||
let queue = crate::audio::AudioInQueue::new();
|
||||
queue.set_generation(9);
|
||||
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
|
||||
let mut old = captured_frame(&queue, 1);
|
||||
old.captured_at -= std::time::Duration::from_millis(600);
|
||||
old.whisper = Some(7);
|
||||
assert_eq!(gate.push_captured(&old), Decision::Hold);
|
||||
let mut onset = captured_frame(&queue, 20_000);
|
||||
onset.whisper = Some(7);
|
||||
assert_eq!(gate.push_captured(&onset), Decision::Start);
|
||||
let mut held = std::array::from_fn(|_| None);
|
||||
assert_eq!(gate.take_captured_preroll(&mut held), 1);
|
||||
let earlier = held[0].as_ref().unwrap();
|
||||
assert_eq!(earlier.pcm, old.pcm);
|
||||
assert_eq!(earlier.captured_at, old.captured_at);
|
||||
assert_eq!(earlier.connection_generation, old.connection_generation);
|
||||
assert_eq!(earlier.capture_epoch, old.capture_epoch);
|
||||
assert_eq!(earlier.whisper, Some(7));
|
||||
assert!(!queue.validate(earlier), "opening VAD cannot renew an expired capture");
|
||||
assert!(held[1..].iter().all(Option::is_none));
|
||||
assert_eq!(gate.take_captured_preroll(&mut held), 0);
|
||||
assert!(held.iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_preroll_is_revoked_by_every_routing_boundary() {
|
||||
let queue = crate::audio::AudioInQueue::new();
|
||||
for boundary in 0..3 {
|
||||
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
|
||||
let old = captured_frame(&queue, 1);
|
||||
assert_eq!(gate.push_captured(&old), Decision::Hold);
|
||||
let mut next = captured_frame(&queue, 20_000);
|
||||
match boundary {
|
||||
0 => next.capture_epoch += 1,
|
||||
1 => next.connection_generation += 1,
|
||||
_ => next.whisper = Some(3),
|
||||
}
|
||||
assert_eq!(gate.push_captured(&next), Decision::Start);
|
||||
let mut held = std::array::from_fn(|_| None);
|
||||
assert_eq!(gate.take_captured_preroll(&mut held), 0);
|
||||
gate.reset();
|
||||
assert!(gate.capture_context.is_none());
|
||||
assert!(gate.preroll_metadata.iter().all(Option::is_none));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_preroll_ring_keeps_metadata_with_its_pcm() {
|
||||
let queue = crate::audio::AudioInQueue::new();
|
||||
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
|
||||
let start = std::time::Instant::now();
|
||||
for i in 0..MAX_PREROLL_FRAMES + 5 {
|
||||
let mut frame = captured_frame(&queue, i as i16);
|
||||
frame.captured_at = start + std::time::Duration::from_millis(i as u64 * 20);
|
||||
assert_eq!(gate.push_captured(&frame), Decision::Hold);
|
||||
}
|
||||
assert_eq!(gate.push_captured(&captured_frame(&queue, 20_000)), Decision::Start);
|
||||
let mut held = std::array::from_fn(|_| None);
|
||||
assert_eq!(gate.take_captured_preroll(&mut held), MAX_PREROLL_FRAMES);
|
||||
for (i, frame) in held.iter().enumerate() {
|
||||
let frame = frame.as_ref().unwrap();
|
||||
assert_eq!(frame.pcm[0], (i + 5) as i16);
|
||||
assert_eq!(frame.captured_at, start + std::time::Duration::from_millis((i + 5) as u64 * 20));
|
||||
}
|
||||
queue.invalidate();
|
||||
assert!(held.iter().all(|frame| !queue.validate(frame.as_ref().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_analysis_frames_cannot_inherit_capture_authorization() {
|
||||
let queue = crate::audio::AudioInQueue::new();
|
||||
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
|
||||
assert_eq!(gate.push_captured(&captured_frame(&queue, 1)), Decision::Hold);
|
||||
assert_eq!(gate.push(&[2; FRAME_SAMPLES]), Decision::Hold);
|
||||
assert_eq!(gate.push(&[20_000; FRAME_SAMPLES]), Decision::Start);
|
||||
let mut held = std::array::from_fn(|_| None);
|
||||
assert_eq!(gate.take_captured_preroll(&mut held), 0);
|
||||
}
|
||||
|
||||
/// Real speech: 4 s of a public-domain LibriVox reading (see tests/fixtures/README.md), 48 kHz mono s16le WAV.
|
||||
pub fn speech_frames() -> Vec<Frame> {
|
||||
let wav = include_bytes!("../tests/fixtures/speech-librivox-48k.wav");
|
||||
|
||||
+52
-6
@@ -94,8 +94,7 @@ pub fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorO
|
||||
Some(_) => return Err(bad("set_transmit: sensitivity must be 'high', 'normal' or 'low'")),
|
||||
};
|
||||
let level = || match a.level_db {
|
||||
Some(l) if l.is_finite() && (MIN_LEVEL_DB..=MAX_LEVEL_DB).contains(&l) => Ok(l),
|
||||
Some(_) => Err(bad("set_transmit: level_db must be between -50 and 50")),
|
||||
Some(l) => Ok(l),
|
||||
None => Err(bad("set_transmit: level_db is required for this detector")),
|
||||
};
|
||||
match a.detector.as_deref() {
|
||||
@@ -116,6 +115,15 @@ pub fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorO
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_transmit(mode: Option<GateMode>) -> Result<(), ErrorObj> {
|
||||
if let Some(GateMode::VolumeGate { level_db } | GateMode::Hybrid { level_db, .. }) = mode {
|
||||
if !level_db.is_finite() || !(MIN_LEVEL_DB..=MAX_LEVEL_DB).contains(&level_db) {
|
||||
return Err(bad("set_transmit: level_db must be between -50 and 50"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `set_transmit` answer for an applied mode.
|
||||
pub fn transmit_result(mode: Option<GateMode>) -> Value {
|
||||
match mode {
|
||||
@@ -162,12 +170,22 @@ pub fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate,
|
||||
return Err(bad("set_local_volumes: uid must be 1..128 characters"));
|
||||
}
|
||||
let uid = BASE64_STANDARD.decode(&e.uid).map_err(|_| bad("set_local_volumes: uid is not base64"))?;
|
||||
if !valid_modifier_db(e.db) {
|
||||
return Err(bad("set_local_volumes: db must be -200..10 in 0.5 steps"));
|
||||
}
|
||||
volumes.push((uid, e.db));
|
||||
}
|
||||
Ok(LocalVolumesUpdate { replace: a.replace, volumes })
|
||||
let update = LocalVolumesUpdate { replace: a.replace, volumes };
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_local_volumes(update: &LocalVolumesUpdate) -> Result<(), ErrorObj> {
|
||||
if update.volumes.len() > MAX_LOCAL_VOLUMES {
|
||||
return Err(bad(format!("set_local_volumes: at most {MAX_LOCAL_VOLUMES} entries")));
|
||||
}
|
||||
for (uid, db) in &update.volumes {
|
||||
// The wire representation is a nonempty base64 string of at most 128 bytes.
|
||||
if uid.is_empty() || uid.len() > 96 { return Err(bad("set_local_volumes: uid must be 1..128 characters")); }
|
||||
if !valid_modifier_db(*db) { return Err(bad("set_local_volumes: db must be -200..10 in 0.5 steps")); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl VoiceSettings {
|
||||
@@ -289,6 +307,34 @@ impl PlaybackDsp {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorObj> {
|
||||
let mode = super::parse_transmit(raw)?;
|
||||
validate_transmit(mode)?;
|
||||
Ok(mode)
|
||||
}
|
||||
|
||||
fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate, ErrorObj> {
|
||||
let update = super::parse_local_volumes(raw)?;
|
||||
validate_local_volumes(&update)?;
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_dsp_commands_enforce_finite_levels_and_decoded_uid_limits() {
|
||||
use crate::protocol::{validate_command, Command};
|
||||
for level_db in [f32::NAN, f32::INFINITY, -51.0, 51.0] {
|
||||
for mode in [GateMode::VolumeGate { level_db }, GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db }] {
|
||||
assert_eq!(validate_command(Command::SetTransmit { vad: Some(mode) }).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
}
|
||||
for volumes in [vec![(vec![], 0.0)], vec![(vec![1; 97], 0.0)], vec![(vec![1], -3.25)],
|
||||
vec![(vec![1], 0.0); MAX_LOCAL_VOLUMES + 1]] {
|
||||
assert_eq!(validate_command(Command::SetLocalVolumes(LocalVolumesUpdate { replace: true, volumes })).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
let valid = LocalVolumesUpdate { replace: true, volumes: vec![(vec![1; 96], -200.0), (vec![2], 10.0)] };
|
||||
assert_eq!(validate_command(Command::SetLocalVolumes(valid.clone())).unwrap().into_inner(), Command::SetLocalVolumes(valid));
|
||||
}
|
||||
|
||||
fn raw(s: &str) -> Box<RawValue> { RawValue::from_string(s.to_owned()).unwrap() }
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -16,14 +16,14 @@ impl Session {
|
||||
let state = self.vad.as_mut().expect("checked above");
|
||||
state.gate.set_mode(mode.expect("checked above"));
|
||||
} else {
|
||||
let discarded = self.audio_in.clear();
|
||||
let epoch = self.audio_in.invalidate();
|
||||
self.tx_end().await;
|
||||
match (mode, self.vad.as_mut()) {
|
||||
(None, _) => self.vad = None,
|
||||
(Some(m), Some(state)) => state.gate.set_mode(m),
|
||||
(Some(m), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(m), route: None })),
|
||||
}
|
||||
info!(discarded, "transmit queue discarded for a mode change");
|
||||
info!(epoch, "transmit queue invalidated for a mode change");
|
||||
}
|
||||
let result = voice_dsp::transmit_result(mode);
|
||||
info!(mode = %result["mode"], detector = %result["detector"], sensitivity = %result["sensitivity"], level_db = %result["level_db"], "transmit mode applied");
|
||||
|
||||
+59
-26
@@ -205,25 +205,10 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
|
||||
Ok(match kind.kind.as_str() {
|
||||
"list" => {
|
||||
let a: ListArgs = serde_json::from_str(text).map_err(invalid)?;
|
||||
if a.entries.len() > MAX_ENTRIES {
|
||||
return Err(bad(format!("at most {MAX_ENTRIES} whisper list entries")));
|
||||
}
|
||||
for e in &a.entries {
|
||||
check_text("uuid", &e.uuid)?;
|
||||
check_text("name", &e.name)?;
|
||||
}
|
||||
TargetSpec::List { entries: a.entries }
|
||||
}
|
||||
"group" => {
|
||||
let a: GroupArgs = serde_json::from_str(text).map_err(invalid)?;
|
||||
if a.group_type > GROUP_ALL_CLIENTS {
|
||||
return Err(invalid_list(&format!("unknown whisper group type: {}", a.group_type)));
|
||||
}
|
||||
if a.target_mode > MAX_GROUP_TARGET_MODE {
|
||||
return Err(invalid_list(&format!("unknown whisper group target mode: {}", a.target_mode)));
|
||||
}
|
||||
check_text("group_id", &a.group_id)?;
|
||||
check_text("server_uuid", &a.server_uuid)?;
|
||||
TargetSpec::Group {
|
||||
group_type: a.group_type,
|
||||
target_mode: a.target_mode,
|
||||
@@ -233,14 +218,6 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
|
||||
}
|
||||
"ids" => {
|
||||
let a: IdsArgs = serde_json::from_str(text).map_err(invalid)?;
|
||||
if a.clients.len() > MAX_TARGETS || a.channel_ids.len() > MAX_TARGETS {
|
||||
return Err(too_many_targets());
|
||||
}
|
||||
for c in &a.clients {
|
||||
if let Some(uid) = &c.uid {
|
||||
check_text("uid", uid)?;
|
||||
}
|
||||
}
|
||||
TargetSpec::Ids { clients: a.clients, channel_ids: a.channel_ids }
|
||||
}
|
||||
other => return Err(bad(format!("target kind must be 'list', 'group' or 'ids', not {other:?}"))),
|
||||
@@ -249,14 +226,14 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
|
||||
|
||||
/// Parses `whisper_start`, `whisper_stop` and `set_whisper_receive` arguments.
|
||||
pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, ErrorObj> {
|
||||
match name {
|
||||
let command = match name {
|
||||
"whisper_start" => {
|
||||
let a: StartArgs = args(raw)?;
|
||||
Ok(WhisperCommand::Start { epoch: check_epoch(a.epoch)?, target: parse_target(&a.target)? })
|
||||
Ok(WhisperCommand::Start { epoch: a.epoch, target: parse_target(&a.target)? })
|
||||
}
|
||||
"whisper_stop" => {
|
||||
let a: StopArgs = args(raw)?;
|
||||
Ok(WhisperCommand::Stop { epoch: check_epoch(a.epoch)? })
|
||||
Ok(WhisperCommand::Stop { epoch: a.epoch })
|
||||
}
|
||||
"set_whisper_receive" => {
|
||||
let a: ReceiveArgs = args(raw)?;
|
||||
@@ -269,7 +246,35 @@ pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, Error
|
||||
}
|
||||
}
|
||||
other => Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
|
||||
}?;
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
pub(crate) fn validate(command: &WhisperCommand) -> Result<(), ErrorObj> {
|
||||
match command {
|
||||
WhisperCommand::Start { epoch, target } => {
|
||||
check_epoch(*epoch)?;
|
||||
match target {
|
||||
TargetSpec::List { entries } => {
|
||||
if entries.len() > MAX_ENTRIES { return Err(bad(format!("at most {MAX_ENTRIES} whisper list entries"))); }
|
||||
for e in entries { check_text("uuid", &e.uuid)?; check_text("name", &e.name)?; }
|
||||
}
|
||||
TargetSpec::Group { group_type, target_mode, group_id, server_uuid } => {
|
||||
if *group_type > GROUP_ALL_CLIENTS { return Err(invalid_list(&format!("unknown whisper group type: {group_type}"))); }
|
||||
if *target_mode > MAX_GROUP_TARGET_MODE { return Err(invalid_list(&format!("unknown whisper group target mode: {target_mode}"))); }
|
||||
check_text("group_id", group_id)?;
|
||||
check_text("server_uuid", server_uuid)?;
|
||||
}
|
||||
TargetSpec::Ids { clients, channel_ids } => {
|
||||
if clients.len() > MAX_TARGETS || channel_ids.len() > MAX_TARGETS { return Err(too_many_targets()); }
|
||||
for c in clients { if let Some(uid) = &c.uid { check_text("uid", uid)?; } }
|
||||
}
|
||||
}
|
||||
}
|
||||
WhisperCommand::Stop { epoch } => { check_epoch(*epoch)?; }
|
||||
WhisperCommand::SetReceive { .. } => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ view
|
||||
@@ -616,6 +621,34 @@ impl Whisper {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, ErrorObj> {
|
||||
let command = super::parse(name, raw)?;
|
||||
validate(&command)?;
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_whisper_validation_preserves_limits_and_structured_errors() {
|
||||
use crate::protocol::{validate_command, Command};
|
||||
let oversized = WhisperCommand::Start { epoch: 1, target: TargetSpec::Ids {
|
||||
clients: vec![ClientRef { id: 7, uid: None }; MAX_TARGETS + 1], channel_ids: vec![],
|
||||
} };
|
||||
assert_eq!(validate_command(Command::Whisper(oversized)).unwrap_err(), too_many_targets());
|
||||
let group = WhisperCommand::Start { epoch: 1, target: TargetSpec::Group {
|
||||
group_type: u8::MAX, target_mode: 0, group_id: "1".into(), server_uuid: "server".into(),
|
||||
} };
|
||||
assert_eq!(validate_command(Command::Whisper(group)).unwrap_err(), invalid_list("unknown whisper group type: 255"));
|
||||
for entries in [
|
||||
vec![Entry { kind: ENTRY_CLIENT, uuid: "uid".into(), name: String::new() }; MAX_ENTRIES + 1],
|
||||
vec![Entry { kind: ENTRY_CLIENT, uuid: "x".repeat(MAX_TEXT_BYTES + 1), name: String::new() }],
|
||||
] {
|
||||
let command = WhisperCommand::Start { epoch: 1, target: TargetSpec::List { entries } };
|
||||
assert_eq!(validate_command(Command::Whisper(command)).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
let allowed = WhisperCommand::Start { epoch: 1, target: TargetSpec::Ids { clients: vec![], channel_ids: vec![7; MAX_TARGETS] } };
|
||||
assert_eq!(validate_command(Command::Whisper(allowed.clone())).unwrap().into_inner(), Command::Whisper(allowed));
|
||||
}
|
||||
use tsproto_packets::packets::{Direction, Flags, InPacket, PacketType};
|
||||
|
||||
fn raw(text: &str) -> Box<RawValue> { RawValue::from_string(text.to_owned()).unwrap() }
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
use std::{path::PathBuf, sync::atomic::{AtomicU64, Ordering}};
|
||||
use teamspeach_core::{protocol::Command, runtime::{spawn, CoreConfig}};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
struct Profile(PathBuf);
|
||||
impl Profile {
|
||||
fn new() -> Self {
|
||||
Self(std::env::temp_dir().join(format!("teamspeach-embedded-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))))
|
||||
}
|
||||
fn config(&self, slot: usize) -> CoreConfig {
|
||||
CoreConfig { data_dir: self.0.join("core"), connection_dir: self.0.join("core/connections").join(slot.to_string()) }
|
||||
}
|
||||
}
|
||||
impl Drop for Profile { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } }
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn embedded_identity_survives_repeated_worker_lifetimes() {
|
||||
let profile = Profile::new();
|
||||
let (first, _events) = spawn(profile.config(1)).unwrap();
|
||||
let created = first.request(Command::ProfileCreate { nickname: "Native owner".into() }).await.unwrap();
|
||||
let uid = created["uid"].clone();
|
||||
assert!(uid.as_str().is_some());
|
||||
for _ in 0..100 {
|
||||
let (other, _events) = spawn(profile.config(2)).unwrap();
|
||||
let state = other.request(Command::ProfileGet).await.unwrap();
|
||||
assert_eq!(state["uid"], uid);
|
||||
other.shutdown().await.unwrap();
|
||||
}
|
||||
assert_eq!(first.request(Command::ProfileGet).await.unwrap()["uid"], uid);
|
||||
first.shutdown().await.unwrap();
|
||||
let (again, _events) = spawn(profile.config(1)).unwrap();
|
||||
assert_eq!(again.request(Command::ProfileGet).await.unwrap()["uid"], uid);
|
||||
again.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn native_requests_validate_before_session_dispatch() {
|
||||
use teamspeach_core::protocol::{ErrorCode, TextTarget};
|
||||
let profile = Profile::new();
|
||||
let (core, _events) = spawn(profile.config(1)).unwrap();
|
||||
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
|
||||
expected_client_uid: None, message: "private".into() }).await.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::BadRequest);
|
||||
let error = core.request(Command::StreamSignal { stream_id: "s1".into(), client_id: 1, json: "[]".into() }).await.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::BadRequest);
|
||||
core.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn duplicate_connection_slot_is_refused_and_released_after_shutdown() {
|
||||
let profile = Profile::new();
|
||||
let (core, _events) = spawn(profile.config(1)).unwrap();
|
||||
assert!(spawn(profile.config(1)).is_err());
|
||||
core.shutdown().await.unwrap();
|
||||
let (next, _events) = spawn(profile.config(1)).unwrap();
|
||||
next.shutdown().await.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use std::{future::{poll_fn, Future}, path::PathBuf, sync::atomic::{AtomicU64, Ordering}, task::Poll, time::Duration};
|
||||
use teamspeach_core::{protocol::{Command, ErrorCode}, runtime::{spawn, CoreConfig, CoreEvents, CoreHandle}};
|
||||
use tokio::time::timeout;
|
||||
|
||||
const DEADLINE: Duration = Duration::from_secs(20);
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Profile(PathBuf);
|
||||
impl Profile {
|
||||
fn new() -> Self {
|
||||
Self(std::env::temp_dir().join(format!("teamspeach-runtime-failures-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))))
|
||||
}
|
||||
fn config(&self) -> CoreConfig {
|
||||
CoreConfig { data_dir: self.0.join("core"), connection_dir: self.0.join("core/connections/1") }
|
||||
}
|
||||
async fn start(&self) -> (CoreHandle, CoreEvents, serde_json::Value) {
|
||||
let (core, mut events) = spawn(self.config()).unwrap();
|
||||
let identity = core.request(Command::ProfileCreate { nickname: "Failure regression".into() }).await.unwrap();
|
||||
assert!(identity["uid"].as_str().is_some_and(|uid| !uid.is_empty()));
|
||||
// Consume the creation event before testing the exact host queue capacity.
|
||||
let event = events.control.recv().await.expect("profile event");
|
||||
assert_eq!(event["event"], "profile");
|
||||
(core, events, identity["uid"].clone())
|
||||
}
|
||||
async fn assert_reusable(&self, uid: &serde_json::Value) {
|
||||
let (core, _events) = spawn(self.config()).expect("terminated worker must release its slot");
|
||||
assert_eq!(&core.request(Command::ProfileGet).await.unwrap()["uid"], uid);
|
||||
core.shutdown().await.unwrap();
|
||||
}
|
||||
}
|
||||
impl Drop for Profile {
|
||||
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
|
||||
}
|
||||
|
||||
fn audio_state_request() -> Command {
|
||||
// Offline SetAudio still emits one audio_state event, without opening any device or socket.
|
||||
Command::SetAudio { input_muted: None, output_muted: None }
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn dropped_control_consumer_terminates_requests_and_releases_slot() {
|
||||
timeout(DEADLINE, async {
|
||||
let profile = Profile::new();
|
||||
let (core, events, uid) = profile.start().await;
|
||||
let CoreEvents { control, mut playback } = events;
|
||||
drop(control);
|
||||
let error = core.request(audio_state_request()).await.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::NotConnected);
|
||||
assert!(playback.recv().await.is_none(), "output owner must be dropped on host failure");
|
||||
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
|
||||
core.shutdown().await.unwrap();
|
||||
profile.assert_reusable(&uid).await;
|
||||
}).await.expect("dead host must not strand shutdown or pending requests");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn full_control_queue_ends_core_without_a_consumer_drain() {
|
||||
timeout(DEADLINE, async {
|
||||
let profile = Profile::new();
|
||||
let (core, mut events, uid) = profile.start().await;
|
||||
for _ in 0..1024 {
|
||||
core.request(audio_state_request()).await.unwrap();
|
||||
}
|
||||
assert_eq!(events.control.len(), 1024);
|
||||
let error = core.request(audio_state_request()).await.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::NotConnected);
|
||||
// Do not drain the congested receiver to help the worker finish.
|
||||
assert!(events.playback.recv().await.is_none());
|
||||
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
|
||||
core.shutdown().await.unwrap();
|
||||
assert_eq!(events.control.len(), 1024);
|
||||
assert!(events.control.is_closed());
|
||||
profile.assert_reusable(&uid).await;
|
||||
}).await.expect("control backpressure must terminate rather than deadlock the core");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn requests_queued_after_shutdown_complete_with_stopped_error() {
|
||||
timeout(DEADLINE, async {
|
||||
let profile = Profile::new();
|
||||
let (core, _events, uid) = profile.start().await;
|
||||
let mut shutdown = Box::pin(core.request(Command::Shutdown));
|
||||
// Poll once to enqueue Shutdown before ProfileGet. It may already finish on the
|
||||
// worker; retain that outcome instead of depending on a scheduling race.
|
||||
let completed = poll_fn(|cx| Poll::Ready(shutdown.as_mut().poll(cx))).await;
|
||||
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
|
||||
match completed {
|
||||
Poll::Ready(result) => { result.unwrap(); }
|
||||
Poll::Pending => { shutdown.as_mut().await.unwrap(); }
|
||||
}
|
||||
drop(shutdown);
|
||||
core.shutdown().await.unwrap();
|
||||
profile.assert_reusable(&uid).await;
|
||||
}).await.expect("shutdown must settle requests queued behind it");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn abandoning_a_request_preserves_subsequent_requests_and_shutdown() {
|
||||
timeout(DEADLINE, async {
|
||||
let profile = Profile::new();
|
||||
let (core, _events, uid) = profile.start().await;
|
||||
let mut abandoned = Box::pin(core.request(Command::ProfileGet));
|
||||
// This exercises caller cancellation if still pending, and the equally valid
|
||||
// already-completed race; deterministic pending-map cleanup needs an internal test.
|
||||
let _ = poll_fn(|cx| Poll::Ready(abandoned.as_mut().poll(cx))).await;
|
||||
drop(abandoned);
|
||||
assert_eq!(core.request(Command::ProfileGet).await.unwrap()["uid"], uid);
|
||||
core.shutdown().await.unwrap();
|
||||
profile.assert_reusable(&uid).await;
|
||||
}).await.expect("abandoning a caller must not strand the worker");
|
||||
}
|
||||
Vendored
+19
-6
@@ -7,14 +7,15 @@
|
||||
- Authors: Flakebi and the ReSpeak contributors.
|
||||
- License: dual MIT OR Apache-2.0 — see `tsclientlib/LICENSE-MIT` and
|
||||
`tsclientlib/LICENSE-APACHE` (copied verbatim from the upstream repository root).
|
||||
- Only the `tsclientlib` crate (`Cargo.toml`, `README.md`, `src/`) is vendored. Its sibling
|
||||
crates (`tsproto`, `ts-bookkeeping`, `tsproto-packets`, `tsproto-types`) are used unmodified
|
||||
as git dependencies pinned to the same revision.
|
||||
- `tsclientlib` and `tsproto` are vendored from that revision. `ts-bookkeeping`,
|
||||
`tsproto-packets` and `tsproto-types` remain pinned git dependencies. The root workspace
|
||||
patch selects the local `tsproto` for every consumer.
|
||||
|
||||
### Local modifications
|
||||
|
||||
The complete diff against upstream is `tsclientlib.patch` (apply with `git apply -p1` inside
|
||||
upstream's `tsclientlib/` crate directory at the revision above; it reproduces this tree):
|
||||
`tsclientlib.patch` records the original protocol-discovery modifications (items 1–5 below).
|
||||
The native capture-send extension in item 6 and `tsproto/` is maintained directly in the vendored tree;
|
||||
the historical patch alone no longer reproduces the complete tree.
|
||||
|
||||
1. `Cargo.toml`: the workspace `path` dependencies are replaced by git dependencies pinned to
|
||||
the same revision.
|
||||
@@ -37,4 +38,16 @@ upstream's `tsclientlib/` crate directory at the revision above; it reproduces t
|
||||
instead of spawning upstream's unbounded proof-of-work thread. The explicit identity CLI owns
|
||||
bounded, cancellable work and durable checkpoints.
|
||||
|
||||
No other behaviour changes.
|
||||
6. `src/lib.rs`: `AudioSendMetadata`, `AudioSendGuard` and `send_audio_guarded` forward
|
||||
original capture time, connection generation and privacy epoch to the transport. Ordinary
|
||||
`send_audio` remains for non-capture end markers and existing third-party callers.
|
||||
|
||||
## `tsproto/`
|
||||
|
||||
Same upstream revision and dual MIT OR Apache-2.0 license; license texts accompany the crate.
|
||||
Sibling workspace dependencies are pinned to the revision above. Guarded voice packets retain
|
||||
metadata plus a shared authorization guard through the deferred UDP queue. Before each actual
|
||||
socket send attempt, including a retry after backpressure, the guard synchronizes against capture
|
||||
invalidation and refuses expired or revoked packets. Guarded media is bounded separately from
|
||||
unmodified acknowledgement/control/end-marker traffic. This prevents muted or previous-session
|
||||
audio from escaping merely because it was encoded before a privacy boundary.
|
||||
Vendored
+24
@@ -58,6 +58,7 @@ mod tests;
|
||||
pub use ts_bookkeeping::messages::s2c::InMessage;
|
||||
// TODO This is bad because it re-exports ConnectOptions
|
||||
pub use ts_bookkeeping::*;
|
||||
pub use tsproto::connection::{AudioSendGuard, AudioSendMetadata};
|
||||
pub use tsproto::resend::{ConnectionStats, PacketStat};
|
||||
pub use tsproto::Identity;
|
||||
pub use tsproto_types::errors::Error as TsError;
|
||||
@@ -970,6 +971,29 @@ impl Connection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send captured audio only while its timestamp, generation and epoch remain valid.
|
||||
///
|
||||
/// Unlike `send_audio`, the reusable guard wraps every actual socket poll,
|
||||
/// including retries after backpressure. Keep empty End packets on `send_audio`
|
||||
/// so revoking capture cannot suppress the end of the preceding burst.
|
||||
pub fn send_audio_guarded(
|
||||
&mut self, packet: OutPacket, metadata: AudioSendMetadata, guard: Arc<dyn AudioSendGuard>,
|
||||
) -> Result<()> {
|
||||
assert!(
|
||||
matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper),
|
||||
"Can only send audio packets with send_audio_guarded"
|
||||
);
|
||||
if let ConnectionState::Connected { con, book } = &mut self.state {
|
||||
if !Self::intern_can_send_audio(book, &self.options) {
|
||||
let span = self.span.clone();
|
||||
warn!(parent: span, "Sending audio while muted");
|
||||
}
|
||||
con.client.send_audio_guarded(packet, metadata, guard).map_err(Error::SendPacket)
|
||||
} else {
|
||||
Err(Error::NotConnected)
|
||||
}
|
||||
}
|
||||
|
||||
/// Download a file from a channel of the connected TeamSpeak server.
|
||||
///
|
||||
/// Returns the size of the file and a tcp stream of the requested file.
|
||||
|
||||
+367
-1274
File diff suppressed because it is too large.
Load diff
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
[package]
|
||||
name = "tsproto"
|
||||
version = "0.2.0"
|
||||
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||
description = "An implementation of the TeamSpeak3 protocol as a library for use in clients and bots."
|
||||
repository = "https://github.com/ReSpeak/tsclientlib"
|
||||
readme = "README.md"
|
||||
keywords = ["teamspeak3", "ts3", "voip"]
|
||||
categories = ["multimedia"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2018"
|
||||
autobenches = false
|
||||
include = [
|
||||
"/Cargo.toml",
|
||||
"/README.md",
|
||||
"**/*.rs",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
aes = "0.8"
|
||||
base64 = "0.22"
|
||||
omnom = "3"
|
||||
curve25519-dalek-ng = "4"
|
||||
eax = "0.5"
|
||||
futures = "0.3"
|
||||
generic-array = "0.14"
|
||||
git-testament = "0.2"
|
||||
num-bigint = "0.4"
|
||||
num-derive = "0.4"
|
||||
num-traits = "0.2"
|
||||
pin-project-lite = "0.2"
|
||||
rand = "0.10"
|
||||
rug = { version = "1", optional = true, default-features = false, features = ["integer"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
sha-1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
time = { version = "0.3", features = ["formatting"] }
|
||||
tokio = { version = "1", features = ["macros", "net", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
quicklz = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
criterion = "0.8"
|
||||
once_cell = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "signal"] }
|
||||
tracing-subscriber = "0.3"
|
||||
|
||||
[[bench]]
|
||||
name = "modpow"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "connect"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "license"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "message"
|
||||
harness = false
|
||||
|
||||
# Keep standalone transport regression tests out of the application's package set.
|
||||
[workspace]
|
||||
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2020 tsclientlib contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
# TsProto   [](https://docs.rs/tsproto)
|
||||
This library implements the TeamSpeak3 protocol.
|
||||
|
||||
For a usable library to build clients and bots, you should take a look at
|
||||
[`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
|
||||
convenient interface to this library.
|
||||
|
||||
If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
|
||||
is a cross-platform TeamSpeak client, which is using this library (more
|
||||
correctly, it is using `tsclientlib`).
|
||||
|
||||
For more info on this project, take a look at the
|
||||
[tsclientlib README](https://github.com/ReSpeak/tsclientlib).
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||
* [MIT license](../LICENSE-MIT)
|
||||
|
||||
at your option.
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
# TsProto   [](https://docs.rs/tsproto)
|
||||
{{readme}}
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||
* [MIT license](../LICENSE-MIT)
|
||||
|
||||
at your option.
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
use anyhow::{Error, Result};
|
||||
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||
use once_cell::sync::Lazy;
|
||||
use tracing::{info, warn};
|
||||
use tsproto::client::Client;
|
||||
use tsproto::connection::StreamItem;
|
||||
use tsproto_packets::commands::CommandParser;
|
||||
|
||||
mod utils;
|
||||
use crate::utils::*;
|
||||
|
||||
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||
|
||||
async fn wait_channellistfinished(con: &mut Client) -> Result<()> {
|
||||
con.filter_items(|con, i| {
|
||||
Ok(match i {
|
||||
StreamItem::S2CInit(packet) => {
|
||||
con.hand_back_buffer(packet.into_buffer());
|
||||
None
|
||||
}
|
||||
StreamItem::C2SInit(packet) => {
|
||||
con.hand_back_buffer(packet.into_buffer());
|
||||
None
|
||||
}
|
||||
StreamItem::Command(packet) => {
|
||||
let (name, _) = CommandParser::new(packet.data().packet().content());
|
||||
if name == b"channellistfinished" { Some(()) } else { None }
|
||||
}
|
||||
StreamItem::Error(error) => {
|
||||
warn!(%error, "Got connection error");
|
||||
None
|
||||
}
|
||||
i => {
|
||||
warn!(got = ?i, "Unexpected packet, waiting for channellistfinished");
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn one_connect(b: &mut Bencher) {
|
||||
Lazy::force(&TRACING);
|
||||
|
||||
let local_address = "127.0.0.1:0".parse().unwrap();
|
||||
let address = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
|
||||
b.iter(|| {
|
||||
rt.block_on(async move {
|
||||
// The TS server does not accept the 3rd reconnect from the same port
|
||||
// so we create a new client for every connection.
|
||||
let mut con = create_client(local_address, address, 0).await?;
|
||||
|
||||
connect(&mut con).await?;
|
||||
info!("Connected");
|
||||
// Wait until channellistfinished
|
||||
wait_channellistfinished(&mut con).await?;
|
||||
|
||||
info!("Disconnecting");
|
||||
disconnect(&mut con).await?;
|
||||
Ok::<_, Error>(())
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
fn bench_connect(c: &mut Criterion) { c.bench_function("connect", one_connect); }
|
||||
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = Criterion::default().sample_size(20);
|
||||
targets = bench_connect
|
||||
}
|
||||
criterion_main!(benches);
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
use base64::prelude::*;
|
||||
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||
use tsproto::license::Licenses;
|
||||
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||
|
||||
fn license_parse(b: &mut Bencher, license: Vec<u8>) {
|
||||
b.iter(|| {
|
||||
Licenses::parse_ignore_expired(license.clone()).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
fn license_derive_key(b: &mut Bencher, license: Vec<u8>) {
|
||||
let licenses = Licenses::parse_ignore_expired(license).unwrap();
|
||||
|
||||
b.iter(|| {
|
||||
let derived_key =
|
||||
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(tsproto::ROOT_KEY)).unwrap();
|
||||
derived_key.compress().0
|
||||
});
|
||||
}
|
||||
|
||||
const STANDARD_LICENSE: &str = "AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==";
|
||||
|
||||
const AAL_LICENSE: &str = "AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
|
||||
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
|
||||
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
|
||||
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
|
||||
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
|
||||
3B78eHGeePIAm98vQJvpu0";
|
||||
|
||||
fn standard_license_parse(b: &mut Bencher) {
|
||||
license_parse(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
|
||||
}
|
||||
|
||||
fn aal_license_parse(b: &mut Bencher) {
|
||||
license_parse(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
|
||||
}
|
||||
|
||||
fn standard_license_derive_key(b: &mut Bencher) {
|
||||
license_derive_key(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
|
||||
}
|
||||
|
||||
fn aal_license_derive_key(b: &mut Bencher) {
|
||||
license_derive_key(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
|
||||
}
|
||||
|
||||
fn bench_license(c: &mut Criterion) {
|
||||
c.bench_function("parse standard license", standard_license_parse);
|
||||
c.bench_function("parse aal license", aal_license_parse);
|
||||
|
||||
c.bench_function("derive key standard license", standard_license_derive_key);
|
||||
c.bench_function("derive key aal license", aal_license_derive_key);
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench_license);
|
||||
criterion_main!(benches);
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
use anyhow::Error;
|
||||
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||
use tracing::info;
|
||||
use tsproto_packets::packets::*;
|
||||
|
||||
mod utils;
|
||||
use crate::utils::*;
|
||||
|
||||
fn send_messages(b: &mut Bencher) {
|
||||
create_logger(false);
|
||||
|
||||
let local_address = "127.0.0.1:0".parse().unwrap();
|
||||
let address = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let mut con = rt
|
||||
.block_on(async move {
|
||||
let mut con = create_client(local_address, address, 0).await?;
|
||||
|
||||
info!("Connecting");
|
||||
connect(&mut con).await?;
|
||||
Ok::<_, Error>(con)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let mut i = 0;
|
||||
|
||||
let mut last_id = None;
|
||||
b.iter(|| {
|
||||
let text = format!("Hello {}", i);
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
|
||||
packet.write_arg("targetmode", &"3");
|
||||
packet.write_arg("msg", &text);
|
||||
i += 1;
|
||||
|
||||
rt.block_on(async {
|
||||
con.wait_until_can_send().await.unwrap();
|
||||
last_id = Some(con.send_packet(packet.into_packet()).unwrap());
|
||||
});
|
||||
});
|
||||
|
||||
rt.block_on(async move {
|
||||
if let Some(id) = last_id {
|
||||
info!("Waiting for {:?}", id);
|
||||
con.wait_for_ack(id).await?;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {
|
||||
}
|
||||
_ = con.wait_disconnect() => {
|
||||
anyhow::bail!("Disconnected");
|
||||
}
|
||||
};
|
||||
|
||||
info!("Disconnecting");
|
||||
disconnect(&mut con).await
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn bench_message(c: &mut Criterion) { c.bench_function("message", send_messages); }
|
||||
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = Criterion::default().sample_size(200);
|
||||
targets = bench_message
|
||||
}
|
||||
criterion_main!(benches);
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||
use num_bigint::BigUint;
|
||||
use num_traits::One;
|
||||
#[cfg(feature = "rug")]
|
||||
use rug::Integer;
|
||||
|
||||
fn num_modpow(b: &mut Bencher) {
|
||||
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
|
||||
let level = 10_000;
|
||||
let n = n.parse().unwrap();
|
||||
let x: BigUint = x.parse().unwrap();
|
||||
let mut e = BigUint::one();
|
||||
e <<= level as usize;
|
||||
|
||||
b.iter(|| x.modpow(&e, &n));
|
||||
}
|
||||
|
||||
#[cfg(feature = "rug")]
|
||||
fn gmp_modpow(b: &mut Bencher) {
|
||||
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
|
||||
let level = 10_000;
|
||||
let n: Integer = n.parse().unwrap();
|
||||
let x: Integer = x.parse().unwrap();
|
||||
let mut e = Integer::new();
|
||||
e.set_bit(level, true);
|
||||
|
||||
b.iter(|| x.pow_mod_ref(&e, &n).unwrap());
|
||||
}
|
||||
|
||||
fn bench_modpow(c: &mut Criterion) {
|
||||
c.bench_function("num bigint", num_modpow);
|
||||
|
||||
#[cfg(feature = "rug")]
|
||||
{
|
||||
c.bench_function("gmp", gmp_modpow);
|
||||
}
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench_modpow);
|
||||
criterion_main!(benches);
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::net::UdpSocket;
|
||||
use tsproto::algorithms as algs;
|
||||
use tsproto::client::Client;
|
||||
use tsproto_packets::packets::*;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn create_logger(to_file: bool) {
|
||||
if to_file {
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(|| std::fs::OpenOptions::new().append(true).open("bench.log").unwrap())
|
||||
.init();
|
||||
} else {
|
||||
tracing_subscriber::fmt::init();
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_client(
|
||||
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
|
||||
) -> Result<Client> {
|
||||
// Get P-256 ECDH key
|
||||
let private_key = EccKeyPrivP256::import_str(
|
||||
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||
|
||||
let udp_socket = UdpSocket::bind(local_address).await?;
|
||||
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
|
||||
|
||||
if verbose >= 1 {
|
||||
tsproto::log::add_logger(true, verbose > 1, verbose > 2, &mut con)
|
||||
}
|
||||
|
||||
Ok(con)
|
||||
}
|
||||
|
||||
/// Returns the `initserver` command.
|
||||
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
|
||||
con.connect().await?;
|
||||
|
||||
// Send clientinit
|
||||
let private_key = EccKeyPrivP256::import_str(
|
||||
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||
|
||||
let private_key_as_pub = private_key.to_pub();
|
||||
let offset = algs::hash_cash(&private_key_as_pub, 8);
|
||||
|
||||
// Create clientinit packet
|
||||
let offset = offset.to_string();
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
|
||||
|
||||
for (arg, val) in [
|
||||
("client_nickname", "Bot"),
|
||||
("client_version", "3.?.? [Build: 5680278000]"),
|
||||
("client_platform", "Linux"),
|
||||
("client_input_hardware", "1"),
|
||||
("client_output_hardware", "1"),
|
||||
("client_default_channel", ""),
|
||||
("client_default_channel_password", ""),
|
||||
("client_server_password", ""),
|
||||
("client_meta_data", ""),
|
||||
(
|
||||
"client_version_sign",
|
||||
"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
|
||||
),
|
||||
("client_nickname_phonetic", ""),
|
||||
("client_key_offset", &offset),
|
||||
("client_default_token", ""),
|
||||
("client_badges", "Overwolf=0"),
|
||||
(
|
||||
"hwid",
|
||||
"923f136fb1e22ae6ce95e60255529c00,\
|
||||
d13231b1bc33edfecfb9169cc7a63bcc",
|
||||
),
|
||||
] {
|
||||
packet.write_arg(arg, &val);
|
||||
}
|
||||
|
||||
con.send_packet(packet.into_packet())?;
|
||||
Ok(con
|
||||
.filter_commands(|con, cmd| {
|
||||
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
|
||||
Some(cmd)
|
||||
} else {
|
||||
con.hand_back_buffer(cmd.into_buffer());
|
||||
None
|
||||
})
|
||||
})
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn disconnect(con: &mut Client) -> Result<()> {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
|
||||
for (arg, val) in [
|
||||
// Reason: Disconnect
|
||||
("reasonid", "8"),
|
||||
("reasonmsg", "Bye"),
|
||||
] {
|
||||
packet.write_arg(arg, &val);
|
||||
}
|
||||
|
||||
con.send_packet(packet.into_packet())?;
|
||||
con.wait_disconnect().await?;
|
||||
Ok(())
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use clap::Parser;
|
||||
use tokio::time::{self, Duration};
|
||||
use tracing::info;
|
||||
use tsproto_packets::packets::*;
|
||||
|
||||
mod utils;
|
||||
use crate::utils::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// The address of the server to connect to
|
||||
#[arg(short, long, default_value = "127.0.0.1:9987")]
|
||||
address: SocketAddr,
|
||||
/// The listening address of the client
|
||||
#[arg(long, default_value = "0.0.0.0:0")]
|
||||
local_address: SocketAddr,
|
||||
/// Print the content of all packets
|
||||
///
|
||||
/// 0. Print nothing
|
||||
/// 1. Print command string
|
||||
/// 2. Print packets
|
||||
/// 3. Print udp packets
|
||||
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||
verbose: u8,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> { real_main().await }
|
||||
|
||||
async fn real_main() -> Result<()> {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
create_logger();
|
||||
|
||||
let mut con = create_client(args.local_address, args.address, args.verbose).await?;
|
||||
|
||||
// Connect
|
||||
connect(&mut con).await?;
|
||||
info!("Connected");
|
||||
|
||||
// Wait some time
|
||||
tokio::select! {
|
||||
_ = time::sleep(Duration::from_secs(2)) => {}
|
||||
_ = con.wait_disconnect() => {
|
||||
bail!("Disconnected");
|
||||
}
|
||||
};
|
||||
info!("Waited");
|
||||
|
||||
// Send packet
|
||||
let mut cmd =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
|
||||
cmd.write_arg("targetmode", &3);
|
||||
cmd.write_arg("msg", &"Hello");
|
||||
let id = con.send_packet(cmd.into_packet())?;
|
||||
con.wait_for_ack(id).await?;
|
||||
|
||||
// Disconnect
|
||||
disconnect(&mut con).await?;
|
||||
info!("Disconnected");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
use clap::Parser;
|
||||
use tsproto::utils;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// Data (hex)
|
||||
#[arg()]
|
||||
data: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
|
||||
let data = utils::read_hex(&args.data).unwrap();
|
||||
let data = quicklz::decompress(&mut Cursor::new(data), std::u32::MAX).unwrap();
|
||||
std::io::stdout().write_all(&data).unwrap();
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use futures::prelude::*;
|
||||
use tokio::time::{self, Duration};
|
||||
use tracing::info;
|
||||
|
||||
mod utils;
|
||||
use crate::utils::*;
|
||||
|
||||
#[derive(Parser, Clone, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// The address of the server to connect to
|
||||
#[arg(short, long, default_value = "127.0.0.1:9987")]
|
||||
address: SocketAddr,
|
||||
/// The listening address of the client
|
||||
#[arg(long, default_value = "0.0.0.0:0")]
|
||||
local_address: SocketAddr,
|
||||
/// Print the content of all packets
|
||||
///
|
||||
/// 0. Print nothing
|
||||
/// 1. Print command string
|
||||
/// 2. Print packets
|
||||
/// 3. Print udp packets
|
||||
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||
verbose: u8,
|
||||
/// How many connections
|
||||
#[arg()]
|
||||
count: usize,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> { real_main().await }
|
||||
|
||||
async fn real_main() -> Result<()> {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
create_logger();
|
||||
|
||||
stream::iter(0..args.count)
|
||||
.for_each_concurrent(None, |_| {
|
||||
let args = args.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut con =
|
||||
create_client(args.local_address, args.address, args.verbose).await.unwrap();
|
||||
|
||||
// Connect
|
||||
connect(&mut con).await.unwrap();
|
||||
info!("Connected");
|
||||
|
||||
// Wait some time
|
||||
tokio::select! {
|
||||
_ = time::sleep(Duration::from_secs(2)) => {}
|
||||
_ = con.wait_disconnect() => {
|
||||
panic!("Disconnected");
|
||||
}
|
||||
};
|
||||
info!("Waited");
|
||||
|
||||
// Disconnect
|
||||
let _ = disconnect(&mut con).await;
|
||||
info!("Disconnected");
|
||||
})
|
||||
.map(|_| ())
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
use base64::prelude::*;
|
||||
use clap::Parser;
|
||||
use tsproto::license::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// The license data (base64)
|
||||
#[arg()]
|
||||
license: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
|
||||
let l = Licenses::parse(BASE64_STANDARD.decode(&args.license).unwrap()).unwrap();
|
||||
println!("{:#?}", l);
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
use std::io::Write;
|
||||
|
||||
use clap::Parser;
|
||||
use tsproto::algorithms as algs;
|
||||
use tsproto::utils;
|
||||
use tsproto_packets::packets::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// Print backtrace
|
||||
#[arg(short, long = "debug")]
|
||||
debug: bool,
|
||||
/// Server to client
|
||||
#[arg(short, long = "client")]
|
||||
c2s: bool,
|
||||
/// Data (hex)
|
||||
#[arg()]
|
||||
data: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
|
||||
let dir = if args.c2s { Direction::C2S } else { Direction::S2C };
|
||||
|
||||
let data = utils::read_hex(&args.data).unwrap();
|
||||
let packet = match InPacket::try_new(dir, &data) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
if args.debug {
|
||||
println!("Failed to decode: {:?}", e);
|
||||
} else {
|
||||
println!("Failed to decode: {}", e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let decrypted = match algs::decrypt_fake(&packet) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
if args.debug {
|
||||
println!("Failed to decrypt: {:?}", e);
|
||||
} else {
|
||||
println!("Failed to decrypt: {}", e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
std::io::stdout().write_all(&decrypted).unwrap();
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use base64::prelude::*;
|
||||
use clap::Parser;
|
||||
use curve25519_dalek_ng::edwards::CompressedEdwardsY;
|
||||
use curve25519_dalek_ng::scalar::Scalar;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// Public key
|
||||
#[arg(short, long = "pub")]
|
||||
pub_key: String,
|
||||
/// Private key
|
||||
#[arg(short, long = "priv")]
|
||||
priv_key: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
|
||||
let pub_key = BASE64_STANDARD.decode(&args.pub_key).unwrap();
|
||||
let priv_key = BASE64_STANDARD.decode(&args.priv_key).unwrap();
|
||||
let mut pubk = [0; 32];
|
||||
pubk.copy_from_slice(&pub_key);
|
||||
let mut privk = [0; 32];
|
||||
privk.copy_from_slice(&priv_key);
|
||||
/*privk[0] &= 248;
|
||||
privk[31] &= 63;
|
||||
privk[31] |= 64;*/
|
||||
|
||||
let priv_scal = Scalar::from_bytes_mod_order(privk);
|
||||
//let priv_scal = Scalar::from_bytes_mod_order(privk);
|
||||
let pub_point_compr = CompressedEdwardsY(pubk);
|
||||
let pub_point = -pub_point_compr.decompress().unwrap();
|
||||
//let pub_point = curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
|
||||
|
||||
let res = (pub_point * priv_scal).compress();
|
||||
println!("Result: {}", BASE64_STANDARD.encode(&res.0));
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
use base64::prelude::*;
|
||||
use clap::Parser;
|
||||
use tsproto_types::crypto::EccKeyPubP256;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, about)]
|
||||
struct Args {
|
||||
/// Public key
|
||||
#[arg(short, long)]
|
||||
key: String,
|
||||
/// Data (base64)
|
||||
#[arg(short, long)]
|
||||
data: String,
|
||||
/// Signature (base64)
|
||||
#[arg(short, long)]
|
||||
signature: String,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Parse command line options
|
||||
let args = Args::parse();
|
||||
|
||||
// l → proof
|
||||
// ek || beta → proof
|
||||
|
||||
let data = BASE64_STANDARD.decode(&args.data).unwrap();
|
||||
let signature = BASE64_STANDARD.decode(&args.signature).unwrap();
|
||||
let key = EccKeyPubP256::from_ts(&args.key).unwrap();
|
||||
/*let keyts = tomcrypt::P256EccKey::import(&BASE64_STANDARD.decode(&args.key).unwrap())
|
||||
.unwrap();
|
||||
let res = keyts.verify_hash(&data, &signature).unwrap();
|
||||
println!("Res: {:?}", res);*/
|
||||
|
||||
key.verify(&data, &signature).unwrap();
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::net::UdpSocket;
|
||||
use tracing::{info, info_span};
|
||||
use tsproto::algorithms as algs;
|
||||
use tsproto::client::Client;
|
||||
use tsproto_packets::packets::*;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
pub fn create_logger() { tracing_subscriber::fmt::init(); }
|
||||
|
||||
pub async fn create_client(
|
||||
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
|
||||
) -> Result<Client> {
|
||||
// Get P-256 ECDH key
|
||||
let private_key = EccKeyPrivP256::import_str(
|
||||
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||
|
||||
let udp_socket = UdpSocket::bind(local_address).await?;
|
||||
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
|
||||
|
||||
if verbose >= 1 {
|
||||
tsproto::log::add_logger_with_verbosity(verbose, &mut con)
|
||||
}
|
||||
|
||||
Ok(con)
|
||||
}
|
||||
|
||||
/// Returns the `initserver` command.
|
||||
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
|
||||
con.connect().await?;
|
||||
|
||||
// Send clientinit
|
||||
let private_key = EccKeyPrivP256::import_str(
|
||||
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||
|
||||
// Compute hash cash
|
||||
let offset;
|
||||
{
|
||||
let _span = info_span!("Compute public key hash cash level").entered();
|
||||
let private_key_as_pub = private_key.to_pub();
|
||||
offset = algs::hash_cash(&private_key_as_pub, 8);
|
||||
let omega = private_key_as_pub.to_ts();
|
||||
info!(
|
||||
level = algs::get_hash_cash_level(&omega, offset),
|
||||
offset, "Computed hash cash level"
|
||||
);
|
||||
}
|
||||
|
||||
// Create clientinit packet
|
||||
let offset = offset.to_string();
|
||||
let mut cmd =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
|
||||
cmd.write_arg("client_nickname", &"Bot");
|
||||
cmd.write_arg("client_version", &"3.?.? [Build: 5680278000]");
|
||||
cmd.write_arg("client_platform", &"Linux");
|
||||
|
||||
cmd.write_arg("client_input_hardware", &"1");
|
||||
cmd.write_arg("client_output_hardware", &"1");
|
||||
cmd.write_arg("client_default_channel", &"");
|
||||
cmd.write_arg("client_default_channel_password", &"");
|
||||
cmd.write_arg("client_server_password", &"");
|
||||
cmd.write_arg("client_meta_data", &"");
|
||||
cmd.write_arg(
|
||||
"client_version_sign",
|
||||
&"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
|
||||
);
|
||||
cmd.write_arg("client_nickname_phonetic", &"");
|
||||
cmd.write_arg("client_key_offset", &offset);
|
||||
cmd.write_arg("client_default_token", &"");
|
||||
cmd.write_arg("client_badges", &"Overwolf=0");
|
||||
cmd.write_arg("hwid", &"923f136fb1e22ae6ce95e60255529c00,d13231b1bc33edfecfb9169cc7a63bcc");
|
||||
|
||||
con.send_packet(cmd.into_packet())?;
|
||||
Ok(con
|
||||
.filter_commands(|con, cmd| {
|
||||
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
|
||||
Some(cmd)
|
||||
} else {
|
||||
con.hand_back_buffer(cmd.into_buffer());
|
||||
None
|
||||
})
|
||||
})
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn disconnect(con: &mut Client) -> Result<()> {
|
||||
let mut cmd =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
|
||||
cmd.write_arg("reasonid", &8);
|
||||
cmd.write_arg("reasonmsg", &"Bye");
|
||||
|
||||
con.send_packet(cmd.into_packet())?;
|
||||
con.wait_disconnect().await?;
|
||||
Ok(())
|
||||
}
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
//! Handle packet splitting and cryptography
|
||||
use curve25519_dalek_ng::edwards::EdwardsPoint;
|
||||
use eax::aead::consts::{U16, U8};
|
||||
use eax::{AeadInPlace, Eax, KeyInit};
|
||||
use generic_array::GenericArray;
|
||||
use num_bigint::BigUint;
|
||||
use num_traits::ToPrimitive;
|
||||
use omnom::WriteExt;
|
||||
use quicklz::CompressionLevel;
|
||||
use sha1::Sha1;
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use tsproto_types::crypto::{EccKeyPrivEd25519, EccKeyPubP256};
|
||||
|
||||
use crate::connection::CachedKey;
|
||||
use crate::{Error, Result};
|
||||
use tsproto_packets::packets::*;
|
||||
|
||||
pub fn must_encrypt(t: PacketType) -> bool {
|
||||
match t {
|
||||
PacketType::Command | PacketType::CommandLow => true,
|
||||
PacketType::Voice
|
||||
| PacketType::Ack
|
||||
| PacketType::AckLow
|
||||
| PacketType::VoiceWhisper
|
||||
| PacketType::Ping
|
||||
| PacketType::Pong
|
||||
| PacketType::Init => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn should_encrypt(t: PacketType, voice_encryption: bool) -> bool {
|
||||
must_encrypt(t)
|
||||
|| t == PacketType::Ack
|
||||
|| t == PacketType::AckLow
|
||||
|| (voice_encryption && t.is_voice())
|
||||
}
|
||||
|
||||
/// Compresses and splits the packet data of a `Command` or `CommandLow` packet.
|
||||
///
|
||||
/// Returns the splitted packet data and their headers.
|
||||
/// The headers have their type and the compressed and fragmented flag set
|
||||
/// to the right value.
|
||||
///
|
||||
/// Returns an error if the packet is too large but cannot be splitted.
|
||||
/// Only `Command` and `CommandLow` packets can be compressed and splitted.
|
||||
pub fn compress_and_split(is_client: bool, packet: OutPacket) -> Vec<OutPacket> {
|
||||
// Everything except whisper packets has to be less than 500 bytes
|
||||
let header_size =
|
||||
if is_client { tsproto_packets::C2S_HEADER_LEN } else { tsproto_packets::S2C_HEADER_LEN };
|
||||
let data = packet.content();
|
||||
// The maximum packet size (including header) is 500 bytes.
|
||||
let max_size = 500 - header_size;
|
||||
// Split the data if it is necessary.
|
||||
let compressed;
|
||||
let datas = if data.len() > max_size {
|
||||
// Compress with QuickLZ
|
||||
let cdata = ::quicklz::compress(data, CompressionLevel::Lvl1);
|
||||
// Use only if it is efficient
|
||||
let mut data = if cdata.len() > data.len() {
|
||||
compressed = false;
|
||||
data
|
||||
} else {
|
||||
compressed = true;
|
||||
&cdata
|
||||
};
|
||||
|
||||
// Ignore size limit for whisper packets
|
||||
if data.len() <= max_size || packet.header().packet_type() == PacketType::VoiceWhisper {
|
||||
let mut v = vec![0; header_size + data.len()];
|
||||
v[header_size..].copy_from_slice(data);
|
||||
vec![v]
|
||||
} else {
|
||||
// Split
|
||||
let count = (data.len() + max_size - 1) / max_size;
|
||||
let mut splitted = Vec::with_capacity(count);
|
||||
while data.len() > max_size {
|
||||
let (first, last) = data.split_at(max_size);
|
||||
let mut v = vec![0; header_size + max_size];
|
||||
v[header_size..].copy_from_slice(first);
|
||||
splitted.push(v);
|
||||
data = last;
|
||||
}
|
||||
// Rest
|
||||
let mut v = vec![0; header_size + data.len()];
|
||||
v[header_size..].copy_from_slice(data);
|
||||
splitted.push(v);
|
||||
splitted
|
||||
}
|
||||
} else {
|
||||
return vec![packet];
|
||||
};
|
||||
|
||||
let len = datas.len();
|
||||
let fragmented = len > 1;
|
||||
let orig_header = packet.header_bytes();
|
||||
let dir = packet.direction();
|
||||
let mut packets = Vec::with_capacity(datas.len());
|
||||
for (i, mut d) in datas.into_iter().enumerate() {
|
||||
d[..header_size].copy_from_slice(orig_header);
|
||||
let mut packet = OutPacket::new_from_data(dir, d);
|
||||
// Only set flags on first fragment
|
||||
if i == 0 && compressed {
|
||||
packet.flags(packet.header().flags() | Flags::COMPRESSED);
|
||||
}
|
||||
|
||||
// Set fragmented flag on first and last part
|
||||
if fragmented && (i == 0 || i == len - 1) {
|
||||
packet.flags(packet.header().flags() | Flags::FRAGMENTED);
|
||||
}
|
||||
packets.push(packet);
|
||||
}
|
||||
packets
|
||||
}
|
||||
|
||||
fn create_key_nonce(
|
||||
p_type: PacketType, c_id: Option<u16>, p_id: u16, generation_id: u32, iv: &[u8; 64],
|
||||
cache: &mut [[CachedKey; 2]; 8],
|
||||
) -> (GenericArray<u8, U16>, GenericArray<u8, U16>) {
|
||||
// Check if this generation is cached
|
||||
let cache = &mut cache[p_type.to_usize().unwrap()][if c_id.is_some() { 1 } else { 0 }];
|
||||
if cache.generation_id != generation_id {
|
||||
// Update the cache
|
||||
let mut temp = [0; 70];
|
||||
if c_id.is_some() {
|
||||
temp[0] = 0x31;
|
||||
} else {
|
||||
temp[0] = 0x30;
|
||||
}
|
||||
temp[1] = p_type.to_u8().unwrap();
|
||||
(&mut temp[2..6]).write_be(generation_id).unwrap();
|
||||
temp[6..].copy_from_slice(iv);
|
||||
|
||||
let keynonce = Sha256::digest(&temp[..]);
|
||||
let keynonce = keynonce.as_slice();
|
||||
cache.generation_id = generation_id;
|
||||
cache.key.copy_from_slice(&keynonce[..16]);
|
||||
cache.nonce.copy_from_slice(&keynonce[16..]);
|
||||
}
|
||||
|
||||
// Use the cached version
|
||||
let mut key = cache.key;
|
||||
let nonce = cache.nonce;
|
||||
key[0] ^= (p_id >> 8) as u8;
|
||||
key[1] ^= (p_id & 0xff) as u8;
|
||||
(key, nonce)
|
||||
}
|
||||
|
||||
pub fn encrypt_key_nonce(
|
||||
packet: &mut OutPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
|
||||
) -> Result<()> {
|
||||
let meta = packet.header().get_meta().to_vec();
|
||||
let cipher = Eax::<aes::Aes128, U8>::new(key);
|
||||
let mac = cipher
|
||||
.encrypt_in_place_detached(nonce, &meta, packet.content_mut())
|
||||
.map_err(|_| Error::MaxLengthExceeded("encryption data"))?;
|
||||
packet.mac().copy_from_slice(mac.as_slice());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn encrypt_fake(packet: &mut OutPacket) -> Result<()> {
|
||||
encrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
|
||||
}
|
||||
|
||||
pub fn encrypt(
|
||||
packet: &mut OutPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
|
||||
) -> Result<()> {
|
||||
let header = packet.header();
|
||||
let (key, nonce) = create_key_nonce(
|
||||
header.packet_type(),
|
||||
header.client_id(),
|
||||
header.packet_id(),
|
||||
generation_id,
|
||||
iv,
|
||||
cache,
|
||||
);
|
||||
encrypt_key_nonce(packet, &key, &nonce)
|
||||
}
|
||||
|
||||
pub fn decrypt_key_nonce(
|
||||
packet: &InPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let header = packet.header();
|
||||
let meta = header.get_meta();
|
||||
// TODO decrypt in-place in packet
|
||||
let mut content = packet.content().to_vec();
|
||||
let cipher = Eax::<aes::Aes128, U8>::new(key);
|
||||
cipher
|
||||
.decrypt_in_place_detached(nonce, meta, &mut content, header.mac().into())
|
||||
.map(|()| content)
|
||||
.map_err(|_| Error::WrongMac {
|
||||
p_type: header.packet_type(),
|
||||
generation_id: 0,
|
||||
packet_id: header.packet_id(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn decrypt_fake(packet: &InPacket) -> Result<Vec<u8>> {
|
||||
decrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
|
||||
}
|
||||
|
||||
pub fn decrypt(
|
||||
packet: &InPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
|
||||
) -> Result<Vec<u8>> {
|
||||
let header = packet.header();
|
||||
let (key, nonce) = create_key_nonce(
|
||||
header.packet_type(),
|
||||
header.client_id(),
|
||||
header.packet_id(),
|
||||
generation_id,
|
||||
iv,
|
||||
cache,
|
||||
);
|
||||
decrypt_key_nonce(packet, &key, &nonce).map_err(|e| {
|
||||
if let Error::WrongMac { p_type, packet_id, .. } = e {
|
||||
Error::WrongMac { p_type, generation_id, packet_id }
|
||||
} else {
|
||||
e
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Compute shared iv and shared mac.
|
||||
pub fn compute_iv_mac(
|
||||
alpha: &[u8; 10], beta: &[u8; 54], our_key: &EccKeyPrivEd25519, other_key: &EdwardsPoint,
|
||||
) -> ([u8; 64], [u8; 8]) {
|
||||
let shared_secret = our_key.create_shared_secret(other_key);
|
||||
let mut shared_iv = [0; 64];
|
||||
shared_iv.copy_from_slice(Sha512::digest(shared_secret).as_slice());
|
||||
for i in 0..10 {
|
||||
shared_iv[i] ^= alpha[i];
|
||||
}
|
||||
for i in 0..54 {
|
||||
shared_iv[i + 10] ^= beta[i];
|
||||
}
|
||||
let mut shared_mac = [0; 8];
|
||||
shared_mac.copy_from_slice(&Sha1::digest(shared_iv).as_slice()[..8]);
|
||||
(shared_iv, shared_mac)
|
||||
}
|
||||
|
||||
pub fn hash_cash(key: &EccKeyPubP256, level: u8) -> u64 {
|
||||
let omega = key.to_ts();
|
||||
let mut offset = 0;
|
||||
while offset < u64::MAX && get_hash_cash_level(&omega, offset) < level {
|
||||
offset += 1;
|
||||
}
|
||||
offset
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_hash_cash_level(omega: &str, offset: u64) -> u8 {
|
||||
let data = Sha1::digest(format!("{}{}", omega, offset).as_bytes());
|
||||
let mut res = 0;
|
||||
for &d in data.as_slice() {
|
||||
if d == 0 {
|
||||
res += 8;
|
||||
} else {
|
||||
res += d.trailing_zeros() as u8;
|
||||
break;
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub fn biguint_to_array(i: &BigUint) -> [u8; 64] {
|
||||
let mut v = i.to_bytes_le();
|
||||
|
||||
// Extend with zeroes until 64 bytes
|
||||
let len = v.len();
|
||||
v.append(&mut vec![0; 64 - len]);
|
||||
v.reverse();
|
||||
|
||||
let mut a = [0; 64];
|
||||
a.copy_from_slice(&v);
|
||||
a
|
||||
}
|
||||
|
||||
pub fn array_to_biguint(i: &[u8; 64]) -> BigUint { BigUint::from_bytes_be(i) }
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use base64::prelude::*;
|
||||
|
||||
use super::*;
|
||||
use crate::license::Licenses;
|
||||
use crate::packets::PacketType;
|
||||
use crate::utils;
|
||||
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||
|
||||
#[test]
|
||||
fn test_fake_crypt() {
|
||||
let data = (0..100).into_iter().collect::<Vec<_>>();
|
||||
let mut packet = OutPacket::new_with_dir(Direction::C2S, Flags::empty(), PacketType::Ack);
|
||||
packet.data_mut().extend_from_slice(&data);
|
||||
encrypt_fake(&mut packet).unwrap();
|
||||
let packet =
|
||||
InPacket::try_new(Direction::C2S, packet.data_mut().as_slice().into()).unwrap();
|
||||
let dec_data = decrypt_fake(&packet).unwrap();
|
||||
assert_eq!(&data, &dec_data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fake_encrypt() {
|
||||
let mut packet = OutAck::new(Direction::C2S, PacketType::Command, 0);
|
||||
encrypt_fake(&mut packet).unwrap();
|
||||
|
||||
let real_res: &[u8] =
|
||||
&[0xa4, 0x7b, 0x47, 0x94, 0xdb, 0xa9, 0x6a, 0xc5, 0, 0, 0, 0, 0x6, 0xfe, 0x18];
|
||||
assert_eq!(real_res, packet.data_mut().as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_iv31() {
|
||||
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs\
|
||||
0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC\
|
||||
4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==")
|
||||
.unwrap()).unwrap();
|
||||
let derived_key =
|
||||
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
|
||||
|
||||
let client_ek = [
|
||||
0xb0, 0x4e, 0xa1, 0xd9, 0x5c, 0x72, 0x64, 0xdf, 0x0d, 0xe8, 0xb3, 0x6b, 0xaa, 0x7c,
|
||||
0xa1, 0x5f, 0x75, 0x71, 0xf5, 0x1f, 0xa0, 0x54, 0xb5, 0x51, 0x27, 0x08, 0x8e, 0xdd,
|
||||
0x96, 0x3d, 0x6e, 0x79,
|
||||
];
|
||||
|
||||
let priv_key = EccKeyPrivEd25519::from_bytes(client_ek);
|
||||
|
||||
let alpha_b64 = BASE64_STANDARD.decode("Jkxq1wIvvhzaCA==").unwrap();
|
||||
let mut alpha = [0; 10];
|
||||
alpha.copy_from_slice(&alpha_b64);
|
||||
let beta_b64 = BASE64_STANDARD
|
||||
.decode("wU5T/MM6toW6Wge9th7VlTlzVZ9JDWypw2P9migfc25pjGP2Tj7Hm6rJpmKeHRr08Ch7BEAR")
|
||||
.unwrap();
|
||||
let mut beta = [0; 54];
|
||||
beta.copy_from_slice(&beta_b64);
|
||||
|
||||
let expected_shared_shared_iv: [u8; 64] = [
|
||||
0x58, 0x78, 0xae, 0x08, 0x08, 0x72, 0x05, 0xb0, 0x13, 0x27, 0x10, 0xe9, 0x81, 0xb4,
|
||||
0xaf, 0x14, 0x14, 0x71, 0xad, 0xcd, 0x82, 0x98, 0xf3, 0xd1, 0x1d, 0x07, 0x20, 0x72,
|
||||
0x7e, 0xb2, 0x1b, 0x89, 0x47, 0x82, 0x1e, 0xfb, 0x02, 0x53, 0x5a, 0x8a, 0x52, 0x4d,
|
||||
0x9a, 0x7a, 0x09, 0x2c, 0x1b, 0xe7, 0x1f, 0xd1, 0x9d, 0x2a, 0x9d, 0x4f, 0xbd, 0xe3,
|
||||
0x22, 0x09, 0xe4, 0x86, 0x7d, 0x63, 0x49, 0x07,
|
||||
];
|
||||
|
||||
let expected_xored_shared_shared_iv: [u8; 64] = [
|
||||
0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac, 0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48,
|
||||
0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25, 0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01,
|
||||
0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98, 0xff, 0xc9, 0x72, 0x95, 0x21, 0x23,
|
||||
0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a, 0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe,
|
||||
0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
|
||||
];
|
||||
|
||||
let (mut shared_iv, _shared_mac) = compute_iv_mac(&alpha, &beta, &priv_key, &derived_key);
|
||||
|
||||
assert_eq!(&shared_iv as &[u8], &expected_xored_shared_shared_iv as &[u8]);
|
||||
|
||||
for i in 0..10 {
|
||||
shared_iv[i] ^= alpha[i];
|
||||
}
|
||||
for i in 0..54 {
|
||||
shared_iv[i + 10] ^= beta[i];
|
||||
}
|
||||
|
||||
assert_eq!(&shared_iv as &[u8], &expected_shared_shared_iv as &[u8]);
|
||||
|
||||
let mut temp = [0; 70];
|
||||
temp[0] = 0x31;
|
||||
temp[1] = 0x2 & 0xf;
|
||||
temp[6..].copy_from_slice(&expected_xored_shared_shared_iv);
|
||||
|
||||
let temporary: [u8; 70] = [
|
||||
0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac,
|
||||
0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48, 0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25,
|
||||
0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01, 0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98,
|
||||
0xff, 0xc9, 0x72, 0x95, 0x21, 0x23, 0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a,
|
||||
0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe, 0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
|
||||
];
|
||||
assert!(&temp as &[u8] == &temporary as &[u8]);
|
||||
|
||||
let keynonce = Sha256::digest(&temp);
|
||||
|
||||
let expected_keynonce: [u8; 32] = [
|
||||
0xf3, 0x70, 0xd3, 0x43, 0xe7, 0x78, 0x15, 0x70, 0x7a, 0xff, 0x60, 0x48, 0xfb, 0xd9,
|
||||
0xac, 0x6b, 0xb6, 0x33, 0x35, 0x79, 0x31, 0x9b, 0x88, 0x0e, 0x2d, 0x25, 0xef, 0x9c,
|
||||
0xe9, 0x9e, 0x77, 0x5c,
|
||||
];
|
||||
|
||||
assert!(keynonce.as_slice() == &expected_keynonce as &[u8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_decrypt() {
|
||||
let shared_iv = utils::read_hex(
|
||||
"C2 45 6F CB FC 22 08 AE 44 2B 7D E7 3A 67 1B DA 93 09 B2 00 F2 CD 10 49 08 CD 3A B0 \
|
||||
7B DD 58 AD",
|
||||
)
|
||||
.unwrap();
|
||||
let mut shared_iv = Sha512::digest(&shared_iv).as_slice().to_vec();
|
||||
assert_eq!(
|
||||
utils::read_hex(
|
||||
"4D 3F DA B7 D8 B0 2C 82 70 6A 39 3E 97 17 61 09 FA 03 AB 30 5C BB 78 7A 9A 82 D5 \
|
||||
39 9A 60 FD A9 F6 7A D9 04 52 F2 AE 00 3E 35 E8 19 10 89 40 43 80 58 27 1F 0A E0 \
|
||||
E0 3D E0 9C F0 A3 4D 15 6B F0"
|
||||
)
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
shared_iv.as_slice()
|
||||
);
|
||||
|
||||
let alpha = [0; 10];
|
||||
let beta = BASE64_STANDARD
|
||||
.decode("I4onb0zMyAD6bd24QANDls40eOES7qmjonBFtt5wRWzAfIIQWTSxjEas6TGTZIJ8QSJNX+Pl")
|
||||
.unwrap();
|
||||
|
||||
for i in 0..10 {
|
||||
shared_iv[i] ^= alpha[i];
|
||||
}
|
||||
for i in 0..54 {
|
||||
shared_iv[i + 10] ^= beta[i];
|
||||
}
|
||||
|
||||
let mut temp = [0; 70];
|
||||
temp[0] = 0x31;
|
||||
temp[1] = 0x2 & 0xf;
|
||||
temp[6..].copy_from_slice(&shared_iv);
|
||||
|
||||
let keynonce = Sha256::digest(&temp);
|
||||
let keynonce = keynonce.as_slice();
|
||||
|
||||
let all = utils::read_hex("2b982443ab38be6b00020000329abf64d4572e1349897b5e1e96fbc4a763a4c4ce1f64f0c1e3febd0a5f04a82ab1f2bc2344bb374fd16181beb8233b5b06944280470e9b6893290a1da0776ffcd89f3beec2ce23b9694930c09efaaea0d88a6895a08ede4d5cbfea61291fc553ac651f1e2bc1d2bd277a8bd9ab5386415579a9e56fac46d8b6b119f454bebd99179cd317dec60af205341d11f274d02bbacdd7e9773f72a426358ca1d39016dd95bde2409cd81bf99b340887e997ea982370c6790cf4d23150460820224766838ea4ec4d71dd102ede701ea0001f392623aa410dd9ab0e45874da82e29e6e370515ec30a37dd73f5a364c233ff014384beab5f1708c9f48dfba33a520f8fcdcef055789c54693c3fe72c5bfaca7cb4ca1fed77b8624660b8abc882f4b95b1284cb6dc55019c6082dd6dd146fa50383662d7298bef04ababaf1af80e15cd4c1f81326f085788e2918e00324147dce39b23db71326abc3de4b94df10f1531e9cce202bba71fa3ebeefd77b21fa3260a62e92eeee2183421d384a8c48777e2f9efbc58d4f442c5f0529c7c0e27e81b2b6b1b05eb8fa19256886248d553582dfd24c7cfab3c3f7317a5cebc6504b53fa0e86fc8c1100fc1d506fcf96caa76a7c0b6a27e577f2efdecd4070e847a559bf37d75bfdbe9e814c702426ce696d8645bc300b5f28f9e7f1ce").unwrap();
|
||||
|
||||
let packet = InPacket::try_new(Direction::C2S, &all).unwrap();
|
||||
println!("Packet: {:?}", packet);
|
||||
let mut key = [0; 16];
|
||||
let mut nonce = [0; 16];
|
||||
key.copy_from_slice(&keynonce[..16]);
|
||||
nonce.copy_from_slice(&keynonce[16..]);
|
||||
|
||||
let expected_key =
|
||||
utils::read_hex("D2 42 75 71 9C EE 83 35 EF 8A CE E0 B7 28 40 B8").unwrap();
|
||||
let expected_nonce =
|
||||
utils::read_hex("9C D9 30 B7 58 FE 50 23 64 66 11 C5 36 0E A2 5F").unwrap();
|
||||
|
||||
assert_eq!(&expected_nonce, &nonce);
|
||||
assert_eq!(&expected_key, &key);
|
||||
|
||||
key[1] ^= 2; // packet id
|
||||
let dec = decrypt_key_nonce(&packet, &key.into(), &nonce.into()).unwrap();
|
||||
|
||||
println!("Decrypted: {:?}", String::from_utf8_lossy(&dec));
|
||||
}
|
||||
}
|
||||
Vendored
+1222
File diff suppressed because it is too large.
Load diff
+556
@@ -0,0 +1,556 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::io;
|
||||
use std::mem;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Instant;
|
||||
|
||||
use futures::prelude::*;
|
||||
use generic_array::GenericArray;
|
||||
use generic_array::typenum::consts::U16;
|
||||
use num_traits::ToPrimitive;
|
||||
use tokio::io::ReadBuf;
|
||||
use tokio::net::UdpSocket;
|
||||
use tracing::{Span, info_span};
|
||||
use tsproto_packets::packets::*;
|
||||
use tsproto_types::crypto::EccKeyPubP256;
|
||||
|
||||
use crate::packet_codec::PacketCodec;
|
||||
use crate::resend::{PacketId, PartialPacketId, Resender, ResenderState};
|
||||
use crate::{Error, MAX_UDP_PACKET_LENGTH, Result, UDP_SINK_CAPACITY};
|
||||
|
||||
/// The needed functions, this can be used to abstract from the underlying
|
||||
/// transport and allows simulation.
|
||||
pub trait Socket {
|
||||
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>>;
|
||||
fn poll_send_to(
|
||||
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
|
||||
) -> Poll<io::Result<usize>>;
|
||||
fn local_addr(&self) -> io::Result<SocketAddr>;
|
||||
}
|
||||
|
||||
/// Capture identity retained with encoded audio, without retaining or copying PCM.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AudioSendMetadata {
|
||||
pub captured_at: Instant,
|
||||
pub connection_generation: u64,
|
||||
pub capture_epoch: u64,
|
||||
}
|
||||
|
||||
/// Reusable authorization boundary for the actual, nonblocking socket send.
|
||||
///
|
||||
/// Implementations must invoke `send` synchronously, at most once, and only while
|
||||
/// the capture timestamp, generation and epoch remain valid. The authorization
|
||||
/// check and callback must share the lock used by capture invalidation; checking
|
||||
/// an atomic and releasing the boundary before invoking `send` is insufficient.
|
||||
/// Do not retain the callback or invoke it after returning. Socket backpressure
|
||||
/// causes a fresh authorization on every subsequent poll. This hook is not called
|
||||
/// during enqueue, which may itself run under the same capture lock.
|
||||
pub trait AudioSendGuard: Send + Sync {
|
||||
fn with_valid_audio(&self, metadata: &AudioSendMetadata, send: &mut dyn FnMut());
|
||||
}
|
||||
|
||||
struct AudioAuthorization {
|
||||
metadata: AudioSendMetadata,
|
||||
guard: Arc<dyn AudioSendGuard>,
|
||||
}
|
||||
|
||||
struct PendingPacket {
|
||||
packet: OutUdpPacket,
|
||||
audio: Option<AudioAuthorization>,
|
||||
}
|
||||
|
||||
/// Ten 20-ms audio packets; control packets and unguarded End markers are retained.
|
||||
const GUARDED_AUDIO_CAPACITY: usize = 10;
|
||||
|
||||
/// A cache for the key and nonce for a generation id.
|
||||
/// This has to be stored for each packet type.
|
||||
#[derive(Debug)]
|
||||
pub struct CachedKey {
|
||||
pub generation_id: u32,
|
||||
pub key: GenericArray<u8, U16>,
|
||||
pub nonce: GenericArray<u8, U16>,
|
||||
}
|
||||
|
||||
/// Data that has to be stored for a connection when it is connected.
|
||||
pub struct ConnectedParams {
|
||||
/// The client id of this connection.
|
||||
pub c_id: u16,
|
||||
/// If voice packets should be encrypted
|
||||
pub voice_encryption: bool,
|
||||
|
||||
/// The public key of the other side.
|
||||
pub public_key: EccKeyPubP256,
|
||||
/// The iv used to encrypt and decrypt packets.
|
||||
pub shared_iv: [u8; 64],
|
||||
/// The mac used for unencrypted packets.
|
||||
pub shared_mac: [u8; 8],
|
||||
/// Cached key and nonce per packet type and for server to client (without
|
||||
/// client id inside the packet) and client to server communication.
|
||||
pub key_cache: [[CachedKey; 2]; 8],
|
||||
}
|
||||
|
||||
/// An event that originates from a tsproto raw connection.
|
||||
#[derive(Debug)]
|
||||
pub enum Event<'a> {
|
||||
ReceiveUdpPacket(&'a InUdpPacket<'a>),
|
||||
ReceivePacket(&'a InPacket<'a>),
|
||||
SendUdpPacket(&'a OutUdpPacket),
|
||||
SendPacket(&'a OutPacket),
|
||||
}
|
||||
|
||||
/// An item that originates from a tsproto raw event stream.
|
||||
///
|
||||
/// The disconnected event is signaled by returning `None` from the stream.
|
||||
#[derive(Debug)]
|
||||
pub enum StreamItem {
|
||||
Command(InCommandBuf),
|
||||
Audio(InAudioBuf),
|
||||
C2SInit(InC2SInitBuf),
|
||||
S2CInit(InS2CInitBuf),
|
||||
/// All packets with an id less or equal to this id were acknowledged.
|
||||
AckPacket(PacketId),
|
||||
/// The network statistics were updated.
|
||||
NetworkStatsUpdated,
|
||||
Error(Error),
|
||||
}
|
||||
|
||||
type EventListener = Box<dyn for<'a> Fn(&'a Event<'a>) + Send>;
|
||||
|
||||
/// Represents a currently alive connection.
|
||||
pub struct Connection {
|
||||
pub is_client: bool,
|
||||
pub span: Span,
|
||||
/// The parameters of this connection, if it is already established.
|
||||
pub params: Option<ConnectedParams>,
|
||||
/// The address of the other side, where packets are coming from and going
|
||||
/// to.
|
||||
pub address: SocketAddr,
|
||||
|
||||
pub resender: Resender,
|
||||
pub codec: PacketCodec,
|
||||
pub udp_socket: Box<dyn Socket + Send>,
|
||||
udp_buffer: Vec<u8>,
|
||||
|
||||
/// A buffer of packets that should be returned from the stream.
|
||||
///
|
||||
/// If a new udp packet is received and we already received the following
|
||||
/// ids, we can get multiple packets back at once. As we can only return one
|
||||
/// from the stream, the rest is stored here.
|
||||
pub(crate) stream_items: VecDeque<StreamItem>,
|
||||
|
||||
/// The queue of non-command packets that should be sent.
|
||||
///
|
||||
/// These packets are not influenced by congestion control.
|
||||
/// If it gets too long, we don't poll from the `udp_socket` anymore.
|
||||
acks_to_send: VecDeque<PendingPacket>,
|
||||
guarded_audio_pending: usize,
|
||||
|
||||
pub event_listeners: Vec<EventListener>,
|
||||
}
|
||||
|
||||
impl Socket for UdpSocket {
|
||||
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
|
||||
self.poll_recv_from(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_send_to(
|
||||
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
|
||||
) -> Poll<io::Result<usize>> {
|
||||
self.poll_send_to(cx, buf, target)
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> { self.local_addr() }
|
||||
}
|
||||
|
||||
impl Default for CachedKey {
|
||||
fn default() -> Self {
|
||||
CachedKey { generation_id: u32::MAX, key: [0; 16].into(), nonce: [0; 16].into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectedParams {
|
||||
/// Fills the parameters for a connection with their default state.
|
||||
pub fn new(public_key: EccKeyPubP256, shared_iv: [u8; 64], shared_mac: [u8; 8]) -> Self {
|
||||
Self {
|
||||
c_id: 0,
|
||||
voice_encryption: true,
|
||||
public_key,
|
||||
shared_iv,
|
||||
shared_mac,
|
||||
key_cache: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub fn new(is_client: bool, address: SocketAddr, udp_socket: Box<dyn Socket + Send>) -> Self {
|
||||
let span = info_span!("connection", local_addr = %udp_socket.local_addr().unwrap(),
|
||||
remote_addr = %address);
|
||||
|
||||
let mut res = Self {
|
||||
is_client,
|
||||
span,
|
||||
params: None,
|
||||
address,
|
||||
resender: Default::default(),
|
||||
codec: Default::default(),
|
||||
udp_socket,
|
||||
udp_buffer: Default::default(),
|
||||
|
||||
stream_items: Default::default(),
|
||||
acks_to_send: VecDeque::with_capacity(UDP_SINK_CAPACITY),
|
||||
guarded_audio_pending: 0,
|
||||
event_listeners: Default::default(),
|
||||
};
|
||||
if is_client {
|
||||
// The first command is sent as part of the C2SInit::Init4 packet
|
||||
// so it does not get registered automatically.
|
||||
res.codec.outgoing_p_ids[PacketType::Command.to_usize().unwrap()] =
|
||||
PartialPacketId { generation_id: 0, packet_id: 1 };
|
||||
} else {
|
||||
res.codec.incoming_p_ids[PacketType::Command.to_usize().unwrap()] =
|
||||
PartialPacketId { generation_id: 0, packet_id: 1 };
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
/// Check if a given id is in the receive window.
|
||||
///
|
||||
/// Returns
|
||||
/// 1. If the packet id is inside the receive window
|
||||
/// 1. The generation of the packet
|
||||
/// 1. The minimum accepted packet id
|
||||
/// 1. The maximum accepted packet id
|
||||
pub(crate) fn in_receive_window(&self, p_type: PacketType, p_id: u16) -> (bool, u32, u16, u16) {
|
||||
if p_type == PacketType::Init {
|
||||
return (true, 0, 0, 0);
|
||||
}
|
||||
let type_i = p_type.to_usize().unwrap();
|
||||
// Receive window is the next half of ids
|
||||
let cur_next = self.codec.incoming_p_ids[type_i].packet_id;
|
||||
let (limit, next_gen) = cur_next.overflowing_add(u16::MAX / 2);
|
||||
let gen = self.codec.incoming_p_ids[type_i].generation_id;
|
||||
let in_recv_win = (!next_gen && p_id >= cur_next && p_id < limit)
|
||||
|| (next_gen && (p_id >= cur_next || p_id < limit));
|
||||
let gen_id = if in_recv_win {
|
||||
if next_gen && p_id < limit { gen + 1 } else { gen }
|
||||
} else if p_id < cur_next {
|
||||
gen
|
||||
} else {
|
||||
gen - 1
|
||||
};
|
||||
|
||||
(in_recv_win, gen_id, cur_next, limit)
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: &Event) {
|
||||
for l in &self.event_listeners {
|
||||
l(event)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hand_back_buffer(&mut self, buffer: Vec<u8>) {
|
||||
if self.udp_buffer.capacity() < MAX_UDP_PACKET_LENGTH
|
||||
&& buffer.capacity() >= MAX_UDP_PACKET_LENGTH
|
||||
{
|
||||
self.udp_buffer = buffer;
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_send_acks(&mut self, cx: &mut Context) -> Result<()> {
|
||||
while let Some(pending) = self.acks_to_send.front() {
|
||||
match Self::poll_send_udp_packet_with_guard(
|
||||
&*self.udp_socket,
|
||||
self.address,
|
||||
&self.event_listeners,
|
||||
cx,
|
||||
&pending.packet,
|
||||
pending.audio.as_ref(),
|
||||
) {
|
||||
Some(Poll::Ready(Ok(()))) => {
|
||||
self.resender.handle_loss_outgoing(&pending.packet);
|
||||
}
|
||||
Some(Poll::Ready(Err(e))) => return Err(e),
|
||||
Some(Poll::Pending) => break,
|
||||
// Revoked/expired audio is discarded without polling the socket.
|
||||
None => {}
|
||||
}
|
||||
if pending.audio.is_some() {
|
||||
self.guarded_audio_pending -= 1;
|
||||
}
|
||||
self.acks_to_send.pop_front();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll_incoming_udp_packet(&mut self, cx: &mut Context) -> Poll<Result<StreamItem>> {
|
||||
if self.acks_to_send.len() >= UDP_SINK_CAPACITY {
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
loop {
|
||||
// Poll udp_socket
|
||||
if self.udp_buffer.len() != MAX_UDP_PACKET_LENGTH {
|
||||
self.udp_buffer.resize(MAX_UDP_PACKET_LENGTH, 0);
|
||||
}
|
||||
|
||||
let mut read_buf = ReadBuf::new(&mut self.udp_buffer);
|
||||
match self.udp_socket.poll_recv_from(cx, &mut read_buf) {
|
||||
Poll::Ready(Ok(addr)) => {
|
||||
let size = read_buf.filled().len();
|
||||
let mut udp_buffer = mem::take(&mut self.udp_buffer);
|
||||
udp_buffer.truncate(size);
|
||||
match self.handle_udp_packet(cx, udp_buffer, addr) {
|
||||
Ok(()) => {
|
||||
if let Some(item) = self.stream_items.pop_front() {
|
||||
return Poll::Ready(Ok(item));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return Poll::Ready(Err(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Udp socket closed
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(Error::Network(e))),
|
||||
Poll::Pending => return Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_udp_packet(
|
||||
&mut self, cx: &mut Context, udp_buffer: Vec<u8>, addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
if addr != self.address {
|
||||
self.stream_items.push_back(StreamItem::Error(Error::WrongAddress));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dir = if self.is_client { Direction::S2C } else { Direction::C2S };
|
||||
let packet = InUdpPacket(match InPacket::try_new(dir, &udp_buffer) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
self.stream_items.push_back(StreamItem::Error(Error::PacketParse("udp", e)));
|
||||
return Ok(());
|
||||
}
|
||||
});
|
||||
let event = Event::ReceiveUdpPacket(&packet);
|
||||
self.send_event(&event);
|
||||
|
||||
self.resender.received_packet();
|
||||
PacketCodec::handle_udp_packet(self, cx, udp_buffer)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Try to send an ack packet.
|
||||
///
|
||||
/// If it does not work, add it to the ack queue.
|
||||
pub(crate) fn send_ack_packet(&mut self, cx: &mut Context, packet: OutPacket) -> Result<()> {
|
||||
self.send_event(&Event::SendPacket(&packet));
|
||||
let mut udp_packets = PacketCodec::encode_packet(self, packet)?;
|
||||
assert_eq!(
|
||||
udp_packets.len(),
|
||||
1,
|
||||
"Encoding an ack packet should only yield a single packet"
|
||||
);
|
||||
let packet = udp_packets.pop().unwrap();
|
||||
|
||||
match self.poll_send_udp_packet(cx, &packet) {
|
||||
Poll::Ready(r) => {
|
||||
if r.is_ok() {
|
||||
self.resender.handle_loss_outgoing(&packet);
|
||||
}
|
||||
r
|
||||
}
|
||||
Poll::Pending => {
|
||||
self.acks_to_send.push_back(PendingPacket { packet, audio: None });
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a packet to the send queue.
|
||||
///
|
||||
/// This function buffers indefinitely, to prevent using a large amount of
|
||||
/// memory, check `is_send_queue_full` first and only send a packet if this
|
||||
/// function returns `false`.
|
||||
///
|
||||
/// When the `PacketId` which is returned by this function is acknowledged,
|
||||
/// the packet was successfully received by the other side of the
|
||||
/// connection.
|
||||
pub fn send_packet(&mut self, packet: OutPacket) -> Result<PacketId> {
|
||||
self.send_event(&Event::SendPacket(&packet));
|
||||
let udp_packets = PacketCodec::encode_packet(self, packet)?;
|
||||
|
||||
let id = udp_packets.last().unwrap().into();
|
||||
for p in udp_packets {
|
||||
self.send_udp_packet(p);
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Queue audio whose authorization must still hold at the actual socket poll.
|
||||
///
|
||||
/// The guard is shared across frames; each packet retains only metadata and an
|
||||
/// `Arc` reference. Pending guarded media is capped at ten packets, evicting the
|
||||
/// oldest guarded packet without removing or reordering control/End packets.
|
||||
/// Packet IDs and encryption are assigned once by the normal encoder and are
|
||||
/// never changed when a packet is retried. Use `send_packet` for unguarded End.
|
||||
pub fn send_audio_guarded(
|
||||
&mut self, packet: OutPacket, metadata: AudioSendMetadata, guard: Arc<dyn AudioSendGuard>,
|
||||
) -> Result<()> {
|
||||
assert!(
|
||||
matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper),
|
||||
"Can only send audio packets with send_audio_guarded"
|
||||
);
|
||||
self.send_event(&Event::SendPacket(&packet));
|
||||
let mut packets = PacketCodec::encode_packet(self, packet)?;
|
||||
assert_eq!(packets.len(), 1, "Audio encoding must yield one UDP packet");
|
||||
let packet = packets.pop().unwrap();
|
||||
if self.guarded_audio_pending == GUARDED_AUDIO_CAPACITY {
|
||||
let oldest = self.acks_to_send.iter().position(|p| p.audio.is_some()).unwrap();
|
||||
self.acks_to_send.remove(oldest);
|
||||
self.guarded_audio_pending -= 1;
|
||||
}
|
||||
self.acks_to_send.push_back(PendingPacket {
|
||||
packet,
|
||||
audio: Some(AudioAuthorization { metadata, guard }),
|
||||
});
|
||||
self.guarded_audio_pending += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add an udp packet to the send queue.
|
||||
pub fn send_udp_packet(&mut self, packet: OutUdpPacket) {
|
||||
let _span = self.span.clone().entered();
|
||||
match packet.packet_type() {
|
||||
PacketType::Init | PacketType::Command | PacketType::CommandLow => {
|
||||
Resender::send_packet(self, packet);
|
||||
}
|
||||
_ => self.acks_to_send.push_back(PendingPacket { packet, audio: None }),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll_send_udp_packet(
|
||||
&self, cx: &mut Context, packet: &OutUdpPacket,
|
||||
) -> Poll<Result<()>> {
|
||||
Self::static_poll_send_udp_packet(
|
||||
&*self.udp_socket,
|
||||
self.address,
|
||||
&self.event_listeners,
|
||||
cx,
|
||||
packet,
|
||||
)
|
||||
}
|
||||
|
||||
/// Remember to add the size of the sent packet to the stats in the resender.
|
||||
pub fn static_poll_send_udp_packet(
|
||||
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
|
||||
cx: &mut Context, packet: &OutUdpPacket,
|
||||
) -> Poll<Result<()>> {
|
||||
Self::poll_send_udp_packet_with_guard(
|
||||
udp_socket, address, event_listeners, cx, packet, None,
|
||||
).expect("unguarded socket poll is always attempted")
|
||||
}
|
||||
|
||||
fn poll_send_udp_packet_with_guard(
|
||||
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
|
||||
cx: &mut Context, packet: &OutUdpPacket, authorization: Option<&AudioAuthorization>,
|
||||
) -> Option<Poll<Result<()>>> {
|
||||
let data = packet.data().data();
|
||||
let mut result = None;
|
||||
let mut send = || {
|
||||
// Even an incorrectly repeated callback cannot send a datagram twice.
|
||||
if result.is_none() {
|
||||
result = Some(udp_socket.poll_send_to(cx, data, address));
|
||||
}
|
||||
};
|
||||
if let Some(audio) = authorization {
|
||||
audio.guard.with_valid_audio(&audio.metadata, &mut send);
|
||||
} else {
|
||||
send();
|
||||
}
|
||||
// Listeners and statistics run after releasing the capture boundary.
|
||||
Some(match result? {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(Err(e)) => Poll::Ready(Err(Error::Network(e))),
|
||||
Poll::Ready(Ok(size)) => {
|
||||
let event = Event::SendUdpPacket(packet);
|
||||
for l in event_listeners {
|
||||
l(&event)
|
||||
}
|
||||
|
||||
if size != data.len() {
|
||||
Poll::Ready(Err(Error::Network(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Failed to send whole udp packet",
|
||||
))))
|
||||
} else {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_send_queue_full(&self) -> bool { self.resender.is_full() }
|
||||
pub fn is_send_queue_empty(&self) -> bool { self.resender.is_empty() }
|
||||
}
|
||||
|
||||
/// Pull for events.
|
||||
///
|
||||
/// `Ok(StreamItem::Error)` is recoverable, `Err()` is not.
|
||||
///
|
||||
/// Polling does a few things in round robin fashion:
|
||||
/// 1. Check for new udp packets
|
||||
/// 2. Use the resender to resend packets if necessary
|
||||
/// 3. Use the resender to send ping packets if necessary
|
||||
impl Stream for Connection {
|
||||
type Item = Result<StreamItem>;
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||
let _span = self.span.clone().entered();
|
||||
if let Err(e) = self.poll_send_acks(cx) {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
|
||||
if self.resender.get_state() == ResenderState::Disconnected {
|
||||
// Send all ack packets and return `None` afterwards
|
||||
if self.acks_to_send.is_empty() {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
}
|
||||
|
||||
// Use the resender to resend packets
|
||||
match Resender::poll_resend(&mut self, cx) {
|
||||
Ok(()) => {}
|
||||
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||
}
|
||||
|
||||
// Use the resender to send pings
|
||||
match Resender::poll_ping(&mut self, cx) {
|
||||
Ok(()) => {}
|
||||
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||
}
|
||||
|
||||
// Return existing stream_items
|
||||
if let Some(item) = self.stream_items.pop_front() {
|
||||
return Poll::Ready(Some(Ok(item)));
|
||||
}
|
||||
|
||||
// Check for new udp packets
|
||||
match self.poll_incoming_udp_packet(cx) {
|
||||
Poll::Ready(r) => return Poll::Ready(Some(r)),
|
||||
Poll::Pending => {}
|
||||
}
|
||||
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "connection_tests.rs"]
|
||||
mod tests;
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
use std::sync::Mutex;
|
||||
use std::task::Waker;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::task::noop_waker;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct GuardState {
|
||||
now: Instant,
|
||||
epoch: u64,
|
||||
generation: u64,
|
||||
checks: usize,
|
||||
}
|
||||
|
||||
struct CaptureGuard(Mutex<GuardState>);
|
||||
|
||||
impl CaptureGuard {
|
||||
fn metadata(&self) -> AudioSendMetadata {
|
||||
let state = self.0.lock().unwrap();
|
||||
AudioSendMetadata {
|
||||
captured_at: state.now,
|
||||
connection_generation: state.generation,
|
||||
capture_epoch: state.epoch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioSendGuard for CaptureGuard {
|
||||
fn with_valid_audio(&self, metadata: &AudioSendMetadata, send: &mut dyn FnMut()) {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.checks += 1;
|
||||
if metadata.capture_epoch == state.epoch
|
||||
&& metadata.connection_generation == state.generation
|
||||
&& state.now.checked_duration_since(metadata.captured_at)
|
||||
.is_some_and(|age| age <= Duration::from_millis(200))
|
||||
{
|
||||
send();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SocketState {
|
||||
blocked: bool,
|
||||
attempts: Vec<Vec<u8>>,
|
||||
sent: Vec<Vec<u8>>,
|
||||
waker: Option<Waker>,
|
||||
}
|
||||
|
||||
struct BackpressureSocket {
|
||||
state: Arc<Mutex<SocketState>>,
|
||||
guard: Arc<CaptureGuard>,
|
||||
}
|
||||
|
||||
impl Socket for BackpressureSocket {
|
||||
fn poll_recv_from(&self, _: &mut Context, _: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_send_to(&self, cx: &mut Context, buf: &[u8], _: SocketAddr) -> Poll<io::Result<usize>> {
|
||||
let packet = InPacket::new(Direction::C2S, buf);
|
||||
if matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper)
|
||||
&& packet.content().len() > 3
|
||||
{
|
||||
assert!(self.guard.0.try_lock().is_err(), "socket poll escaped capture boundary");
|
||||
}
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.attempts.push(buf.to_vec());
|
||||
if state.blocked {
|
||||
state.waker = Some(cx.waker().clone());
|
||||
Poll::Pending
|
||||
} else {
|
||||
state.sent.push(buf.to_vec());
|
||||
Poll::Ready(Ok(buf.len()))
|
||||
}
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> { Ok("127.0.0.1:0".parse().unwrap()) }
|
||||
}
|
||||
|
||||
fn setup(encrypted: bool) -> (Connection, Arc<CaptureGuard>, Arc<Mutex<SocketState>>) {
|
||||
let guard = Arc::new(CaptureGuard(Mutex::new(GuardState {
|
||||
now: Instant::now(), epoch: 1, generation: 1, checks: 0,
|
||||
})));
|
||||
let state = Arc::new(Mutex::new(SocketState { blocked: true, ..Default::default() }));
|
||||
let socket = BackpressureSocket { state: state.clone(), guard: guard.clone() };
|
||||
let mut con = Connection::new(true, "127.0.0.1:1".parse().unwrap(), Box::new(socket));
|
||||
let mut params = ConnectedParams::new(EccKeyPrivP256::create().to_pub(), [7; 64], [9; 8]);
|
||||
params.voice_encryption = encrypted;
|
||||
con.params = Some(params);
|
||||
con.resender.set_state(ResenderState::Connected);
|
||||
let listener_guard = guard.clone();
|
||||
con.event_listeners.push(Box::new(move |event| {
|
||||
if matches!(event, Event::SendUdpPacket(_)) {
|
||||
assert!(listener_guard.0.try_lock().is_ok(), "listener ran under capture lock");
|
||||
}
|
||||
}));
|
||||
(con, guard, state)
|
||||
}
|
||||
|
||||
fn poll_pending(con: &mut Connection) {
|
||||
let waker = noop_waker();
|
||||
con.poll_send_acks(&mut Context::from_waker(&waker)).unwrap();
|
||||
}
|
||||
|
||||
fn unblock(state: &Mutex<SocketState>) {
|
||||
let waker = {
|
||||
let mut state = state.lock().unwrap();
|
||||
state.blocked = false;
|
||||
state.waker.take()
|
||||
};
|
||||
if let Some(waker) = waker {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn voice(data: &[u8]) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: CodecType::OpusVoice, data })
|
||||
}
|
||||
|
||||
fn whisper(data: &[u8]) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2SWhisper {
|
||||
id: 0, codec: CodecType::OpusVoice, channels: vec![], clients: vec![1], data,
|
||||
})
|
||||
}
|
||||
|
||||
fn ping() -> OutPacket {
|
||||
OutPacket::new_with_dir(Direction::C2S, Flags::UNENCRYPTED, PacketType::Ping)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guarded_audio_rechecks_revocation_after_socket_backpressure() {
|
||||
for generation_change in [false, true] {
|
||||
for packet in [voice(&[1, 2, 3]), whisper(&[1, 2, 3])] {
|
||||
let (mut con, guard, socket) = setup(true);
|
||||
con.send_audio_guarded(packet, guard.metadata(), guard.clone()).unwrap();
|
||||
con.send_packet(voice(&[])).unwrap();
|
||||
con.send_packet(ping()).unwrap();
|
||||
assert_eq!(guard.0.lock().unwrap().checks, 0, "enqueue must not relock capture");
|
||||
poll_pending(&mut con);
|
||||
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
|
||||
assert!(socket.lock().unwrap().sent.is_empty());
|
||||
{
|
||||
let mut state = guard.0.lock().unwrap();
|
||||
if generation_change { state.generation += 1; } else { state.epoch += 1; }
|
||||
}
|
||||
unblock(&socket);
|
||||
poll_pending(&mut con);
|
||||
let state = socket.lock().unwrap();
|
||||
assert_eq!(state.attempts.len(), 3, "revoked media must not poll the socket again");
|
||||
assert_eq!(state.sent.len(), 2, "End and control survive capture invalidation");
|
||||
let end = InPacket::new(Direction::C2S, &state.sent[0]);
|
||||
assert_eq!(end.header().packet_type(), PacketType::Voice);
|
||||
assert_eq!(end.content().len(), 3);
|
||||
assert_eq!(InPacket::new(Direction::C2S, &state.sent[1]).header().packet_type(), PacketType::Ping);
|
||||
assert!(con.acks_to_send.is_empty());
|
||||
assert_eq!(con.guarded_audio_pending, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guarded_audio_expires_while_socket_is_pending() {
|
||||
let (mut con, guard, socket) = setup(false);
|
||||
con.send_audio_guarded(voice(&[1]), guard.metadata(), guard.clone()).unwrap();
|
||||
poll_pending(&mut con);
|
||||
guard.0.lock().unwrap().now += Duration::from_millis(600);
|
||||
unblock(&socket);
|
||||
poll_pending(&mut con);
|
||||
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
|
||||
assert!(socket.lock().unwrap().sent.is_empty());
|
||||
assert!(con.acks_to_send.is_empty());
|
||||
assert_eq!(con.guarded_audio_pending, 0);
|
||||
// Reject a future timestamp and a frame already stale before its first poll too.
|
||||
for offset in [Duration::from_millis(600), Duration::from_millis(1)] {
|
||||
let mut metadata = guard.metadata();
|
||||
if offset.as_millis() == 600 { metadata.captured_at -= offset; }
|
||||
else { metadata.captured_at += offset; }
|
||||
con.send_audio_guarded(voice(&[2]), metadata, guard.clone()).unwrap();
|
||||
poll_pending(&mut con);
|
||||
}
|
||||
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
|
||||
assert!(con.acks_to_send.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guarded_audio_retries_identical_encrypted_packet_under_boundary() {
|
||||
for packet in [voice(&[1, 2, 3]), whisper(&[4, 5, 6])] {
|
||||
let (mut con, guard, socket) = setup(true);
|
||||
con.send_audio_guarded(packet, guard.metadata(), guard.clone()).unwrap();
|
||||
let expected = con.acks_to_send.front().unwrap().packet.data().data().to_vec();
|
||||
assert!(!InPacket::new(Direction::C2S, &expected).header().flags().contains(Flags::UNENCRYPTED));
|
||||
poll_pending(&mut con);
|
||||
poll_pending(&mut con);
|
||||
assert_eq!(con.guarded_audio_pending, 1);
|
||||
unblock(&socket);
|
||||
poll_pending(&mut con);
|
||||
let state = socket.lock().unwrap();
|
||||
assert_eq!(state.attempts, vec![expected.clone(), expected.clone(), expected.clone()]);
|
||||
assert_eq!(state.sent, vec![expected]);
|
||||
assert_eq!(guard.0.lock().unwrap().checks, 3);
|
||||
assert!(con.acks_to_send.is_empty());
|
||||
assert_eq!(con.guarded_audio_pending, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guarded_audio_capacity_drops_oldest_without_reordering_end_or_control() {
|
||||
let (mut con, guard, socket) = setup(false);
|
||||
con.send_packet(voice(&[])).unwrap();
|
||||
for value in 0..30u8 {
|
||||
con.send_audio_guarded(voice(&[value]), guard.metadata(), guard.clone()).unwrap();
|
||||
if value == 14 {
|
||||
con.send_packet(ping()).unwrap();
|
||||
con.send_packet(voice(&[])).unwrap();
|
||||
}
|
||||
poll_pending(&mut con);
|
||||
assert!(con.guarded_audio_pending <= GUARDED_AUDIO_CAPACITY);
|
||||
}
|
||||
assert_eq!(con.guarded_audio_pending, GUARDED_AUDIO_CAPACITY);
|
||||
assert_eq!(con.acks_to_send.len(), GUARDED_AUDIO_CAPACITY + 3);
|
||||
unblock(&socket);
|
||||
poll_pending(&mut con);
|
||||
let state = socket.lock().unwrap();
|
||||
assert_eq!(state.sent.len(), GUARDED_AUDIO_CAPACITY + 3);
|
||||
let control_types: Vec<_> = state.sent[..3].iter()
|
||||
.map(|data| InPacket::new(Direction::C2S, data).header().packet_type()).collect();
|
||||
assert_eq!(control_types, vec![PacketType::Voice, PacketType::Ping, PacketType::Voice]);
|
||||
for (data, expected) in state.sent[3..].iter().zip(20..30u8) {
|
||||
let packet = InPacket::new(Direction::C2S, data);
|
||||
assert_eq!(packet.header().packet_type(), PacketType::Voice);
|
||||
assert_eq!(&packet.content()[3..], &[expected]);
|
||||
}
|
||||
assert!(con.acks_to_send.is_empty());
|
||||
assert_eq!(con.guarded_audio_pending, 0);
|
||||
}
|
||||
Vendored
+253
@@ -0,0 +1,253 @@
|
||||
//! This library implements the TeamSpeak3 protocol.
|
||||
//!
|
||||
//! For a usable library to build clients and bots, you should take a look at
|
||||
//! [`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
|
||||
//! convenient interface to this library.
|
||||
//!
|
||||
//! If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
|
||||
//! is a cross-platform TeamSpeak client, which is using this library (more
|
||||
//! correctly, it is using `tsclientlib`).
|
||||
//!
|
||||
//! For more info on this project, take a look at the
|
||||
//! [tsclientlib README](https://github.com/ReSpeak/tsclientlib).
|
||||
|
||||
use std::fmt;
|
||||
use std::num::ParseIntError;
|
||||
|
||||
use base64::prelude::*;
|
||||
use serde::de::{Unexpected, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use thiserror::Error;
|
||||
use tsproto_packets::packets;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
pub mod algorithms;
|
||||
pub mod client;
|
||||
pub mod connection;
|
||||
pub mod license;
|
||||
pub mod log;
|
||||
pub mod packet_codec;
|
||||
pub mod resend;
|
||||
pub mod utils;
|
||||
|
||||
use algorithms as algs;
|
||||
|
||||
// The build environment of tsproto.
|
||||
git_testament::git_testament!(TESTAMENT);
|
||||
#[doc(hidden)]
|
||||
pub fn get_testament() -> &'static git_testament::GitTestament<'static> { &TESTAMENT }
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// The maximum number of bytes for a fragmented packet.
|
||||
///
|
||||
/// The maximum packet size is 500 bytes, as used by
|
||||
/// `algorithms::compress_and_split`.
|
||||
/// We pick the ethernet MTU for possible future compatibility, it is unlikely
|
||||
/// that a packet will get bigger.
|
||||
pub const MAX_UDP_PACKET_LENGTH: usize = 1500;
|
||||
|
||||
/// The maximum number of bytes for a fragmented packet.
|
||||
#[allow(clippy::unreadable_literal)]
|
||||
const MAX_FRAGMENTS_LENGTH: usize = 40960;
|
||||
|
||||
/// The maximum number of packets which are stored, if they are received
|
||||
/// out-of-order.
|
||||
const MAX_QUEUE_LEN: u16 = 200;
|
||||
|
||||
/// The maximum decompressed size of a packet.
|
||||
#[allow(clippy::unreadable_literal)]
|
||||
|
||||
/// On large servers with more than 2000 channels, the notifychannelsubscribed packet can be
|
||||
/// 50 kB large (uncompressed). A maximum size to 2 MiB should allow for even larger servers.
|
||||
const MAX_DECOMPRESSED_SIZE: u32 = 2 * 1024 * 1024;
|
||||
const FAKE_KEY: [u8; 16] = *b"c:\\windows\\syste";
|
||||
const FAKE_NONCE: [u8; 16] = *b"m\\firewall32.cpl";
|
||||
|
||||
/// The root key in the TeamSpeak license system.
|
||||
pub const ROOT_KEY: [u8; 32] = [
|
||||
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c, 0xfd, 0x8f, 0x68, 0xb3, 0xdc,
|
||||
0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec, 0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a,
|
||||
];
|
||||
|
||||
/// The maximum amount of ack pachets that a connection intermediately stores.
|
||||
///
|
||||
/// When this amount is stored, no new packets will be polled from the UDP
|
||||
/// connection.
|
||||
const UDP_SINK_CAPACITY: usize = 50;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create ack packet: {0}")]
|
||||
CreateAck(#[source] tsproto_packets::Error),
|
||||
#[error("Failed to decompress packet: {0}")]
|
||||
DecompressPacket(#[source] quicklz::Error),
|
||||
#[error(transparent)]
|
||||
IdentityCrypto(tsproto_types::crypto::Error),
|
||||
#[error("Failed to parse int: {0}")]
|
||||
InvalidHex(#[source] ParseIntError),
|
||||
#[error("Maximum length exceeded for {0}")]
|
||||
MaxLengthExceeded(&'static str),
|
||||
#[error("Network error: {0}")]
|
||||
Network(#[source] std::io::Error),
|
||||
#[error("Packet {id} not in receive window [{next};{limit}) for type {p_type:?}")]
|
||||
NotInReceiveWindow { id: u16, next: u16, limit: u16, p_type: packets::PacketType },
|
||||
#[error("Failed to parse {0} packet: {1}")]
|
||||
PacketParse(&'static str, #[source] tsproto_packets::Error),
|
||||
#[error("Connection timed out: {0}")]
|
||||
Timeout(&'static str),
|
||||
#[error("Got unallowed unencrypted packet")]
|
||||
UnallowedUnencryptedPacket,
|
||||
#[error("Got unexpected init packet")]
|
||||
UnexpectedInitPacket,
|
||||
#[error("Packet has wrong client id {0}")]
|
||||
WrongClientId(u16),
|
||||
#[error("Received udp packet from wrong address")]
|
||||
WrongAddress,
|
||||
#[error("{p_type:?} Packet {generation_id}:{packet_id} has a wrong mac")]
|
||||
WrongMac { p_type: packets::PacketType, generation_id: u32, packet_id: u16 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct Identity {
|
||||
#[serde(serialize_with = "serialize_id_key", deserialize_with = "deserialize_id_key")]
|
||||
key: EccKeyPrivP256,
|
||||
/// The `client_key_offset`/counter for hash cash.
|
||||
counter: u64,
|
||||
/// The maximum counter that was tried, this is greater or equal to
|
||||
/// `counter` but may yield a lower level.
|
||||
max_counter: u64,
|
||||
}
|
||||
|
||||
struct IdKeyVisitor;
|
||||
impl<'de> Visitor<'de> for IdKeyVisitor {
|
||||
type Value = EccKeyPrivP256;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "a P256 private ecc key")
|
||||
}
|
||||
|
||||
fn visit_str<E: serde::de::Error>(self, s: &str) -> std::result::Result<Self::Value, E> {
|
||||
EccKeyPrivP256::import_str(s)
|
||||
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Str(s), &self))
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_id_key<S: Serializer>(
|
||||
key: &EccKeyPrivP256, s: S,
|
||||
) -> std::result::Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&BASE64_STANDARD.encode(key.to_short()))
|
||||
}
|
||||
|
||||
fn deserialize_id_key<'de, D: Deserializer<'de>>(
|
||||
d: D,
|
||||
) -> std::result::Result<EccKeyPrivP256, D::Error> {
|
||||
d.deserialize_str(IdKeyVisitor)
|
||||
}
|
||||
|
||||
impl Identity {
|
||||
#[inline]
|
||||
pub fn create() -> Self {
|
||||
let mut res = Self::new(EccKeyPrivP256::create(), 0);
|
||||
res.upgrade_level(8);
|
||||
res
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new(key: EccKeyPrivP256, counter: u64) -> Self {
|
||||
Self::new_with_max_counter(key, counter, counter)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_with_max_counter(key: EccKeyPrivP256, counter: u64, max_counter: u64) -> Self {
|
||||
Self { key, counter, max_counter }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_from_str(key: &str) -> Result<Self> {
|
||||
if let Ok(identity) = Identity::new_from_ts_str(key) {
|
||||
return Ok(identity);
|
||||
}
|
||||
let mut res = Self::new(EccKeyPrivP256::import_str(key).map_err(Error::IdentityCrypto)?, 0);
|
||||
res.upgrade_level(8);
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn new_from_ts_str(key: &str) -> Result<Self> {
|
||||
let counter_separator = key
|
||||
.find('V')
|
||||
.ok_or(Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
|
||||
let counter = key[..counter_separator]
|
||||
.parse::<u64>()
|
||||
.map_err(|_| Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
|
||||
let ecc_key = EccKeyPrivP256::import_str(&key[(counter_separator + 1)..])
|
||||
.map_err(Error::IdentityCrypto)?;
|
||||
Ok(Self::new(ecc_key, counter))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_from_bytes(key: &[u8]) -> Result<Self> {
|
||||
let mut res = Self::new(EccKeyPrivP256::import(key).map_err(Error::IdentityCrypto)?, 0);
|
||||
res.upgrade_level(8);
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn key(&self) -> &EccKeyPrivP256 { &self.key }
|
||||
#[inline]
|
||||
pub fn counter(&self) -> u64 { self.counter }
|
||||
#[inline]
|
||||
pub fn max_counter(&self) -> u64 { self.max_counter }
|
||||
|
||||
#[inline]
|
||||
pub fn set_key(&mut self, key: EccKeyPrivP256) { self.key = key }
|
||||
#[inline]
|
||||
pub fn set_counter(&mut self, counter: u64) { self.counter = counter; }
|
||||
#[inline]
|
||||
pub fn set_max_counter(&mut self, max_counter: u64) { self.max_counter = max_counter; }
|
||||
|
||||
/// Compute the current hash cash level.
|
||||
#[inline]
|
||||
pub fn level(&self) -> u8 {
|
||||
let omega = self.key.to_pub().to_ts();
|
||||
algs::get_hash_cash_level(&omega, self.counter)
|
||||
}
|
||||
|
||||
/// Compute a better hash cash level.
|
||||
pub fn upgrade_level(&mut self, target: u8) {
|
||||
let omega = self.key.to_pub().to_ts();
|
||||
let mut offset = self.max_counter;
|
||||
while offset < u64::MAX && algs::get_hash_cash_level(&omega, offset) < target {
|
||||
offset += 1;
|
||||
}
|
||||
self.counter = offset;
|
||||
self.max_counter = offset;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod identity_tests {
|
||||
use super::*;
|
||||
|
||||
const TEST_PRIV_KEY: &str =
|
||||
"MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/\
|
||||
vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
|
||||
const TEST_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
|
||||
|
||||
#[test]
|
||||
fn parse_ts_base64() {
|
||||
let identity = Identity::new_from_str(TEST_PRIV_KEY).unwrap();
|
||||
let uid = identity.key().to_pub().get_uid();
|
||||
assert_eq!(TEST_UID, &uid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ts_base64_with_offset() {
|
||||
let ident_str = String::from("2792354V") + TEST_PRIV_KEY;
|
||||
let identity = Identity::new_from_str(&ident_str).unwrap();
|
||||
let uid = identity.key().to_pub().get_uid();
|
||||
assert_eq!(TEST_UID, &uid);
|
||||
assert_eq!(identity.level(), 21u8);
|
||||
}
|
||||
}
|
||||
Vendored
+932
@@ -0,0 +1,932 @@
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::fmt;
|
||||
use std::io::Cursor;
|
||||
use std::str;
|
||||
|
||||
use curve25519_dalek_ng::edwards::EdwardsPoint;
|
||||
use curve25519_dalek_ng::scalar::Scalar;
|
||||
use num_derive::{FromPrimitive, ToPrimitive};
|
||||
use num_traits::{FromPrimitive as _, ToPrimitive as _};
|
||||
use omnom::{ReadExt, WriteExt};
|
||||
use sha2::{Digest, Sha512};
|
||||
use thiserror::Error;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use tracing::trace;
|
||||
use tsproto_packets::HexSlice;
|
||||
use tsproto_types::{
|
||||
LicenseType,
|
||||
crypto::{EccKeyPrivEd25519, EccKeyPubEd25519},
|
||||
};
|
||||
|
||||
pub const TIMESTAMP_OFFSET: i64 = 0x50e2_2700;
|
||||
|
||||
const BLOCK_MIN_LEN: usize = 42;
|
||||
const BLOCK_TYPE_OFFSET: usize = 33;
|
||||
const BLOCK_NOT_VALID_BEFORE_OFFSET: usize = 34;
|
||||
const BLOCK_NOT_VALID_AFTER_OFFSET: usize = 38;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error(
|
||||
"License must not exceed bounds {outer_start} - {outer_end} but has {inner_start} - \
|
||||
{inner_end}"
|
||||
)]
|
||||
Bounds {
|
||||
outer_start: OffsetDateTime,
|
||||
outer_end: OffsetDateTime,
|
||||
inner_start: OffsetDateTime,
|
||||
inner_end: OffsetDateTime,
|
||||
},
|
||||
#[error("Failed to deserialize license: {0}")]
|
||||
Deserialize(#[source] std::io::Error),
|
||||
#[error("Failed to deserialize license: {0}")]
|
||||
DeserializeString(#[source] std::str::Utf8Error),
|
||||
#[error("Failed to deserialize date: {0}")]
|
||||
DeserializeDate(#[source] time::error::ComponentRange),
|
||||
#[error("License is only valid between {start} and {end}")]
|
||||
Expired { start: OffsetDateTime, end: OffsetDateTime },
|
||||
#[error("Cannot uncompress license public key")]
|
||||
InvalidPublicKey,
|
||||
#[error("Invalid data {0:#x} in intermediate license")]
|
||||
IntermediateInvalidData(u32),
|
||||
#[error("Invalid public root key for license")]
|
||||
InvalidRootKey,
|
||||
#[error("Non-null-terminated string")]
|
||||
NonterminatedString,
|
||||
#[error("License contains no private key")]
|
||||
NoPrivateKey,
|
||||
#[error("Too many license blocks: {0}")]
|
||||
TooManyBlocks(usize),
|
||||
#[error("License too short ({0}): {1}")]
|
||||
TooShort(usize, &'static str),
|
||||
#[error("Unknown license block type {0}")]
|
||||
UnknownBlockType(u8),
|
||||
#[error("Unknown license type {0}")]
|
||||
UnknownLicenseType(u8),
|
||||
#[error("Unsupported license version {0}")]
|
||||
UnsupportedVersion(u8),
|
||||
#[error("Wrong key kind {0} in license")]
|
||||
WrongKeyKind(u8),
|
||||
#[error("There is no {0} in this block")]
|
||||
NoSuchProperty(&'static str),
|
||||
#[error("Wrong property type for id {id}: Expected type {expected} but got type {actual}")]
|
||||
WrongPropertyType { id: u8, expected: u8, actual: u8 },
|
||||
#[error(
|
||||
"Property with id {id} and type {typ} has wrong length: Expected length {expected} but \
|
||||
got length {actual}"
|
||||
)]
|
||||
WrongPropertyLength { id: u8, typ: u8, expected: u8, actual: u8 },
|
||||
}
|
||||
|
||||
/// A single block of a license
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct License {
|
||||
/// Length of the block
|
||||
pub len: usize,
|
||||
/// A private key for the block to derive a private key
|
||||
pub private_key: Option<EccKeyPrivEd25519>,
|
||||
pub inner: InnerLicense,
|
||||
}
|
||||
|
||||
/// Helper struct to debug print a license block.
|
||||
pub struct DebugLicense<'a>(&'a License, &'a [u8]);
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, FromPrimitive, ToPrimitive)]
|
||||
pub enum LicenseBlockType {
|
||||
Intermediate,
|
||||
Website,
|
||||
/// Ts3_Server
|
||||
Server,
|
||||
Code,
|
||||
// Not existing in the license parameter:
|
||||
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
|
||||
/// Ts_Server_License
|
||||
Ts5Server = 8,
|
||||
/// 32, Ephemeral_Key
|
||||
Ephemeral = 32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum InnerLicense {
|
||||
Ts5Server {
|
||||
/// Properties from the license, offset from the start of properties for every field
|
||||
properties: Vec<usize>,
|
||||
},
|
||||
Other,
|
||||
}
|
||||
|
||||
/// A list of blocks, forming a complete license
|
||||
#[derive(Clone)]
|
||||
pub struct Licenses {
|
||||
pub data: Vec<u8>,
|
||||
pub blocks: Vec<License>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum LicenseProperty<'a> {
|
||||
/// Unknown property with id 1 and type 1
|
||||
Unknown1(u32),
|
||||
Issuer(&'a str),
|
||||
MaxClients(u32),
|
||||
Unknown {
|
||||
id: u8,
|
||||
typ: u8,
|
||||
data: &'a [u8],
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LicenseBuilder<'a> {
|
||||
licenses: &'a mut Licenses,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LicenseBlockBuilder<'a, 'b> {
|
||||
builder: &'b mut LicenseBuilder<'a>,
|
||||
/// The start offset for the new block
|
||||
offset: usize,
|
||||
typ: LicenseBlockType,
|
||||
}
|
||||
|
||||
type LicenseTimeBounds = (OffsetDateTime, OffsetDateTime);
|
||||
|
||||
impl Licenses {
|
||||
pub fn new() -> Self { Self::default() }
|
||||
|
||||
/// Parse a license but ignore expired licenses.
|
||||
///
|
||||
/// This is useful for tests but should not be used otherwise.
|
||||
pub fn parse_ignore_expired(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, false) }
|
||||
|
||||
pub fn parse(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, true) }
|
||||
|
||||
pub fn parse_internal(data: Vec<u8>, check_expired: bool) -> Result<Self> {
|
||||
let version = data[0];
|
||||
if version != 0 && version != 1 {
|
||||
return Err(Error::UnsupportedVersion(version));
|
||||
}
|
||||
// Read licenses
|
||||
let mut blocks = Vec::new();
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut offset = 1;
|
||||
let mut bounds = None;
|
||||
while data.len() > offset {
|
||||
if blocks.len() >= 8 {
|
||||
// Accept only 8 blocks
|
||||
return Err(Error::TooManyBlocks(blocks.len()));
|
||||
}
|
||||
|
||||
// Read next license
|
||||
let (license, b) = Self::parse_block(&data[offset..], check_expired, now, bounds)?;
|
||||
offset += license.len;
|
||||
bounds = Some(b);
|
||||
|
||||
blocks.push(license);
|
||||
}
|
||||
|
||||
Ok(Licenses { data, blocks })
|
||||
}
|
||||
|
||||
fn parse_block(
|
||||
data: &[u8], check_expired: bool, now: OffsetDateTime, bounds: Option<LicenseTimeBounds>,
|
||||
) -> Result<(License, LicenseTimeBounds)> {
|
||||
let license = License::parse(data)?;
|
||||
let license_data = &data[..license.len];
|
||||
|
||||
// Check if the certificate is valid
|
||||
let new_bounds = (
|
||||
license.get_not_valid_before(license_data)?,
|
||||
license.get_not_valid_after(license_data)?,
|
||||
);
|
||||
if new_bounds.0 > now && check_expired {
|
||||
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
|
||||
}
|
||||
if new_bounds.1 < now && check_expired {
|
||||
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
|
||||
}
|
||||
if let Some((start, end)) = bounds {
|
||||
// The inner license must not have wider bounds
|
||||
if new_bounds.0 < start || new_bounds.1 > end {
|
||||
return Err(Error::Bounds {
|
||||
outer_start: start,
|
||||
outer_end: end,
|
||||
inner_start: new_bounds.0,
|
||||
inner_end: new_bounds.1,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok((license, new_bounds))
|
||||
}
|
||||
|
||||
pub fn derive_public_key(&self, root: EccKeyPubEd25519) -> Result<EdwardsPoint> {
|
||||
let mut last_round = root.0.decompress().ok_or(Error::InvalidRootKey)?;
|
||||
let mut offset = 1;
|
||||
trace!("Deriving public key for license");
|
||||
for l in &self.blocks {
|
||||
trace!(current_key = %HexSlice((&last_round.compress().0) as &[u8]));
|
||||
last_round = l.derive_public_key(&self.data[offset..offset + l.len], &last_round)?;
|
||||
offset += l.len;
|
||||
}
|
||||
trace!(
|
||||
final_key = %HexSlice((&last_round.compress().0) as &[u8]),
|
||||
"Finished deriving public key"
|
||||
);
|
||||
Ok(last_round)
|
||||
}
|
||||
|
||||
/// Derive the private key of this license, starting with a specific block.
|
||||
///
|
||||
/// The keys which are stored inside the licenses from the starting block on
|
||||
/// have to be private keys.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `starting_block`: The index of the first block for the key computation.
|
||||
/// `first_key`: The starting private key (the key of a parent block or the
|
||||
/// root private key).
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `starting_block` is not a valid license block index.
|
||||
pub fn derive_private_key(
|
||||
&self, starting_block: usize, first_key: EccKeyPrivEd25519,
|
||||
) -> Result<EccKeyPrivEd25519> {
|
||||
let mut res = first_key;
|
||||
let mut offset = 1;
|
||||
for (i, l) in self.blocks.iter().enumerate() {
|
||||
if i >= starting_block {
|
||||
res = l.derive_private_key(&self.data[offset..offset + l.len], &res)?;
|
||||
}
|
||||
offset += l.len;
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn build<F: FnOnce(LicenseBuilder)>(mut self, f: F) -> Result<Self> {
|
||||
let len = self.data.len();
|
||||
|
||||
f(LicenseBuilder { licenses: &mut self });
|
||||
|
||||
// Parse new blocks
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut offset = len;
|
||||
let mut bounds = self
|
||||
.blocks
|
||||
.last()
|
||||
.map(|b| {
|
||||
let b_offset = len - b.len;
|
||||
let b_data = &self.data[b_offset..len];
|
||||
Ok((b.get_not_valid_before(b_data)?, b.get_not_valid_after(b_data)?))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
while self.data.len() > offset {
|
||||
if self.blocks.len() >= 8 {
|
||||
// Accept only 8 blocks
|
||||
return Err(Error::TooManyBlocks(self.blocks.len()));
|
||||
}
|
||||
|
||||
// Read next license
|
||||
let (license, b) = Self::parse_block(&self.data[offset..], false, now, bounds)?;
|
||||
offset += license.len;
|
||||
bounds = Some(b);
|
||||
|
||||
self.blocks.push(license);
|
||||
}
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn is_valid(&self) -> Result<()> {
|
||||
let mut offset = 1;
|
||||
for b in &self.blocks {
|
||||
b.is_valid(&self.data[offset..offset + b.len])?;
|
||||
offset += b.len;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Licenses {
|
||||
fn default() -> Self { Self { data: vec![1], blocks: Default::default() } }
|
||||
}
|
||||
|
||||
impl fmt::Debug for Licenses {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "Licenses ")?;
|
||||
let mut offset = 1;
|
||||
f.debug_list()
|
||||
.entries(self.blocks.iter().map(|b| {
|
||||
let o = offset;
|
||||
offset += b.len;
|
||||
DebugLicense(b, &self.data[o..o + b.len])
|
||||
}))
|
||||
.finish()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl License {
|
||||
/// Parse license and return read length.
|
||||
pub fn parse(data: &[u8]) -> Result<Self> {
|
||||
let len = data.len();
|
||||
if data.len() < BLOCK_MIN_LEN {
|
||||
return Err(Error::TooShort(len, "less than minimum block length"));
|
||||
}
|
||||
if data[0] != 0 {
|
||||
return Err(Error::WrongKeyKind(data[0]));
|
||||
}
|
||||
|
||||
let typ_i = data[BLOCK_TYPE_OFFSET];
|
||||
let typ = LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))?;
|
||||
let data = &data[BLOCK_MIN_LEN..];
|
||||
let (inner, extra_len) = match typ {
|
||||
LicenseBlockType::Intermediate => {
|
||||
if data.len() < 5 {
|
||||
return Err(Error::TooShort(
|
||||
len,
|
||||
"less than minimum length of intermediate license",
|
||||
));
|
||||
}
|
||||
// 4 byte unknown
|
||||
// Issuer string
|
||||
|
||||
let len = if let Some(len) = data[4..].iter().position(|&b| b == 0) {
|
||||
len
|
||||
} else {
|
||||
return Err(Error::NonterminatedString);
|
||||
};
|
||||
(InnerLicense::Other, 5 + len)
|
||||
}
|
||||
LicenseBlockType::Server => {
|
||||
if data.len() < 6 {
|
||||
return Err(Error::TooShort(
|
||||
len,
|
||||
"less than minimum length of TS3 server license",
|
||||
));
|
||||
}
|
||||
// 1 byte server license type
|
||||
// 4 byte max clients
|
||||
// Issuer string
|
||||
let len = if let Some(len) = data[5..].iter().position(|&b| b == 0) {
|
||||
len
|
||||
} else {
|
||||
return Err(Error::NonterminatedString);
|
||||
};
|
||||
|
||||
(InnerLicense::Other, 6 + len)
|
||||
}
|
||||
LicenseBlockType::Ts5Server => {
|
||||
if data.len() < 2 {
|
||||
return Err(Error::TooShort(
|
||||
len,
|
||||
"less than minimum length of TS5 server license",
|
||||
));
|
||||
}
|
||||
// 1 byte server license type
|
||||
// Property count and properties
|
||||
let property_count = data[1];
|
||||
let mut pos = 2;
|
||||
|
||||
let properties = (0..property_count)
|
||||
.map(|_| {
|
||||
let p = pos - 2;
|
||||
if pos >= data.len() {
|
||||
return Err(Error::TooShort(len, "missing TS5 license property"));
|
||||
}
|
||||
let len = usize::from(data[pos]);
|
||||
pos += 1;
|
||||
if pos + len >= data.len() {
|
||||
return Err(Error::TooShort(len, "cut off TS5 license property"));
|
||||
}
|
||||
pos += len;
|
||||
Ok(p)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
(InnerLicense::Ts5Server { properties }, pos)
|
||||
}
|
||||
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
_ => {
|
||||
return Err(Error::UnknownBlockType(typ_i));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(License { len: BLOCK_MIN_LEN + extra_len, private_key: None, inner })
|
||||
}
|
||||
|
||||
pub fn get_type(&self, data: &[u8]) -> Result<LicenseBlockType> {
|
||||
let typ_i = data[BLOCK_TYPE_OFFSET];
|
||||
LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))
|
||||
}
|
||||
|
||||
pub fn get_public_key(&self, data: &[u8]) -> Result<EdwardsPoint> {
|
||||
let k = EccKeyPubEd25519::from_bytes(data[1..33].try_into().unwrap());
|
||||
k.0.decompress().ok_or(Error::InvalidPublicKey)
|
||||
}
|
||||
|
||||
fn get_timestamp(&self, data: &[u8], block_offset: usize) -> Result<OffsetDateTime> {
|
||||
let num: u32 = (&data[block_offset..]).read_be().map_err(Error::Deserialize)?;
|
||||
OffsetDateTime::from_unix_timestamp(i64::from(num) + TIMESTAMP_OFFSET)
|
||||
.map_err(Error::DeserializeDate)
|
||||
}
|
||||
|
||||
pub fn get_not_valid_before(&self, data: &[u8]) -> Result<OffsetDateTime> {
|
||||
self.get_timestamp(data, BLOCK_NOT_VALID_BEFORE_OFFSET)
|
||||
}
|
||||
|
||||
pub fn get_not_valid_after(&self, data: &[u8]) -> Result<OffsetDateTime> {
|
||||
self.get_timestamp(data, BLOCK_NOT_VALID_AFTER_OFFSET)
|
||||
}
|
||||
|
||||
pub fn get_license_type(&self, data: &[u8]) -> Result<LicenseType> {
|
||||
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.get_type(data)?)
|
||||
{
|
||||
return Err(Error::NoSuchProperty("license type"));
|
||||
}
|
||||
LicenseType::from_u8(data[BLOCK_MIN_LEN])
|
||||
.ok_or(Error::UnknownLicenseType(data[BLOCK_MIN_LEN]))
|
||||
}
|
||||
|
||||
pub fn get_issuer<'a>(&self, data: &'a [u8]) -> Result<&'a str> {
|
||||
let typ = self.get_type(data)?;
|
||||
|
||||
if typ == LicenseBlockType::Ts5Server {
|
||||
// Search in properties
|
||||
let res = self
|
||||
.get_properties(data)?
|
||||
.find_map(|p| if let Ok(LicenseProperty::Issuer(i)) = p { Some(i) } else { None })
|
||||
.ok_or(Error::NoSuchProperty("issuer"));
|
||||
return res;
|
||||
}
|
||||
|
||||
let offset = BLOCK_MIN_LEN
|
||||
+ match typ {
|
||||
LicenseBlockType::Intermediate => 4,
|
||||
LicenseBlockType::Website | LicenseBlockType::Code => 0,
|
||||
LicenseBlockType::Server => 5,
|
||||
_ => return Err(Error::NoSuchProperty("issuer")),
|
||||
};
|
||||
let len = match typ {
|
||||
LicenseBlockType::Intermediate
|
||||
| LicenseBlockType::Website
|
||||
| LicenseBlockType::Code
|
||||
| LicenseBlockType::Server => self.len - offset - 1,
|
||||
_ => return Err(Error::NoSuchProperty("issuer")),
|
||||
};
|
||||
str::from_utf8(&data[offset..offset + len]).map_err(Error::DeserializeString)
|
||||
}
|
||||
|
||||
pub fn get_max_clients(&self, data: &[u8]) -> Result<u32> {
|
||||
let typ = self.get_type(data)?;
|
||||
|
||||
if typ == LicenseBlockType::Ts5Server {
|
||||
// Search in properties
|
||||
let res = self
|
||||
.get_properties(data)?
|
||||
.find_map(
|
||||
|p| if let Ok(LicenseProperty::MaxClients(i)) = p { Some(i) } else { None },
|
||||
)
|
||||
.ok_or(Error::NoSuchProperty("max clients"));
|
||||
return res;
|
||||
}
|
||||
|
||||
let offset = BLOCK_MIN_LEN
|
||||
+ match typ {
|
||||
LicenseBlockType::Intermediate => 0,
|
||||
LicenseBlockType::Server => 1,
|
||||
_ => return Err(Error::NoSuchProperty("max clients")),
|
||||
};
|
||||
(&data[offset..offset + 4]).read_be().map_err(Error::Deserialize)
|
||||
}
|
||||
|
||||
pub fn get_properties<'a: 'b, 'b>(
|
||||
&'b self, data: &'a [u8],
|
||||
) -> Result<impl Iterator<Item = Result<LicenseProperty<'a>>> + 'b> {
|
||||
if let InnerLicense::Ts5Server { properties } = &self.inner {
|
||||
Ok(properties.iter().map(move |p| {
|
||||
let o = BLOCK_MIN_LEN + 2 + p;
|
||||
let len = data[o];
|
||||
let len_usize = len as usize;
|
||||
let id = data[o + 1];
|
||||
let typ = data[o + 2];
|
||||
|
||||
// Check length
|
||||
if let Some(expected) = match typ {
|
||||
// String, check that it is null-terminated
|
||||
0 => {
|
||||
if data[o + len_usize] != 0 {
|
||||
return Err(Error::NonterminatedString);
|
||||
}
|
||||
None
|
||||
}
|
||||
1 | 3 => Some(4),
|
||||
2 | 4 => Some(8),
|
||||
_ => None,
|
||||
} {
|
||||
if len != expected {
|
||||
return Err(Error::WrongPropertyLength { id, typ, expected, actual: len });
|
||||
}
|
||||
}
|
||||
|
||||
match id {
|
||||
1 => {
|
||||
if typ != 1 {
|
||||
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
|
||||
}
|
||||
Ok(LicenseProperty::Unknown1(
|
||||
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
|
||||
))
|
||||
}
|
||||
2 => {
|
||||
if typ != 0 {
|
||||
return Err(Error::WrongPropertyType { id, expected: 0, actual: typ });
|
||||
}
|
||||
let s = str::from_utf8(&data[o + 3..o + len_usize])
|
||||
.map_err(Error::DeserializeString)?;
|
||||
Ok(LicenseProperty::Issuer(s))
|
||||
}
|
||||
3 => {
|
||||
if typ != 1 {
|
||||
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
|
||||
}
|
||||
Ok(LicenseProperty::MaxClients(
|
||||
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
|
||||
))
|
||||
}
|
||||
_ => {
|
||||
Ok(LicenseProperty::Unknown { id, typ, data: &data[o + 3..o + len_usize] })
|
||||
}
|
||||
}
|
||||
}))
|
||||
} else {
|
||||
Err(Error::NoSuchProperty("properties"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the private key from the hash of this license block.
|
||||
pub fn get_hash_key(&self, data: &[u8]) -> Scalar {
|
||||
// Make a valid private key from the hash
|
||||
let mut hash_key = Sha512::digest(&data[1..]);
|
||||
hash_key[0] &= 248;
|
||||
hash_key[31] &= 63;
|
||||
hash_key[31] |= 64;
|
||||
Scalar::from_bytes_mod_order(hash_key.as_slice()[..32].try_into().unwrap())
|
||||
}
|
||||
|
||||
pub fn derive_public_key(
|
||||
&self, data: &[u8], parent_key: &EdwardsPoint,
|
||||
) -> Result<EdwardsPoint> {
|
||||
let pub_key = self.get_public_key(data)?;
|
||||
let hash_key = self.get_hash_key(data);
|
||||
Ok(pub_key * hash_key + parent_key)
|
||||
}
|
||||
|
||||
/// Derive the private key of this license block.
|
||||
///
|
||||
/// The key which is stored inside this license has to be a private key.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `parent_key`: The resulting private key of the previous block.
|
||||
pub fn derive_private_key(
|
||||
&self, data: &[u8], parent_key: &EccKeyPrivEd25519,
|
||||
) -> Result<EccKeyPrivEd25519> {
|
||||
let priv_key = if let Some(k) = &self.private_key {
|
||||
&k.0
|
||||
} else {
|
||||
return Err(Error::NoPrivateKey);
|
||||
};
|
||||
let hash_key = self.get_hash_key(data);
|
||||
Ok(EccKeyPrivEd25519(priv_key * hash_key + parent_key.0))
|
||||
}
|
||||
|
||||
/// Check if this is a valid license.
|
||||
///
|
||||
/// Does some sanity checking on fields. Does not need to be called for correctness.
|
||||
pub fn is_valid(&self, data: &[u8]) -> Result<()> {
|
||||
self.get_public_key(data)?;
|
||||
self.get_not_valid_before(data)?;
|
||||
self.get_not_valid_after(data)?;
|
||||
|
||||
if let Err(e) = self.get_license_type(data) {
|
||||
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.get_issuer(data) {
|
||||
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
match self.get_properties(data) {
|
||||
Ok(ps) => {
|
||||
for p in ps {
|
||||
p?;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for DebugLicense<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let from = self
|
||||
.0
|
||||
.get_not_valid_before(self.1)
|
||||
.ok()
|
||||
.and_then(|d| d.format(&Rfc3339).ok())
|
||||
.unwrap_or_else(|| "error".to_string());
|
||||
let to = self
|
||||
.0
|
||||
.get_not_valid_after(self.1)
|
||||
.ok()
|
||||
.and_then(|d| d.format(&Rfc3339).ok())
|
||||
.unwrap_or_else(|| "error".to_string());
|
||||
|
||||
let mut d = f.debug_struct("License");
|
||||
let typ = self.0.get_type(self.1).unwrap();
|
||||
d.field("type", &typ);
|
||||
if let Some(key) = &self.0.private_key {
|
||||
d.field("private_key", key);
|
||||
}
|
||||
d.field("not_valid_before", &from).field("not_valid_after", &to);
|
||||
|
||||
match typ {
|
||||
LicenseBlockType::Intermediate => {
|
||||
if let Ok(num) = self.0.get_max_clients(self.1) {
|
||||
d.field("data", &num);
|
||||
} else {
|
||||
d.field("data", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Website | LicenseBlockType::Code => {
|
||||
if let Ok(issuer) = self.0.get_issuer(self.1) {
|
||||
d.field("issuer", &issuer);
|
||||
} else {
|
||||
d.field("issuer", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Server => {
|
||||
if let Ok(license_type) = self.0.get_license_type(self.1) {
|
||||
d.field("license_type", &license_type);
|
||||
} else {
|
||||
d.field("license_type", &"error");
|
||||
}
|
||||
if let Ok(issuer) = self.0.get_issuer(self.1) {
|
||||
d.field("issuer", &issuer);
|
||||
} else {
|
||||
d.field("issuer", &"error");
|
||||
}
|
||||
if let Ok(max_clients) = self.0.get_max_clients(self.1) {
|
||||
d.field("max_clients", &max_clients);
|
||||
} else {
|
||||
d.field("max_clients", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Ts5Server => {
|
||||
if let Ok(props) =
|
||||
self.0.get_properties(self.1).and_then(|ps| ps.collect::<Result<Vec<_>>>())
|
||||
{
|
||||
d.field("properties", &props);
|
||||
} else {
|
||||
d.field("properties", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Ephemeral => {}
|
||||
}
|
||||
|
||||
d.finish()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LicenseBlockType {
|
||||
fn min_len(&self) -> usize {
|
||||
BLOCK_MIN_LEN
|
||||
+ match self {
|
||||
Self::Intermediate => 5,
|
||||
Self::Website | Self::Code => 1,
|
||||
Self::Server => 6,
|
||||
Self::Ts5Server => 2,
|
||||
Self::Ephemeral => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LicenseBuilder<'a> {
|
||||
pub fn add_block<'b>(&'b mut self, typ: LicenseBlockType) -> LicenseBlockBuilder<'a, 'b> {
|
||||
let len = self.licenses.data.len();
|
||||
self.licenses.data.resize(len + typ.min_len(), 0);
|
||||
self.licenses.data[len + BLOCK_TYPE_OFFSET] = typ.to_u8().unwrap();
|
||||
LicenseBlockBuilder { builder: self, offset: len, typ }
|
||||
}
|
||||
}
|
||||
|
||||
impl LicenseBlockBuilder<'_, '_> {
|
||||
pub fn public_key(&mut self, key: &EccKeyPubEd25519) -> &mut Self {
|
||||
let o = self.offset + 1;
|
||||
self.builder.licenses.data[o..o + 32].copy_from_slice(&key.0.0);
|
||||
self
|
||||
}
|
||||
|
||||
fn write_timestamp(&mut self, offset: usize, time: OffsetDateTime) -> &mut Self {
|
||||
let o = self.offset + offset;
|
||||
Cursor::new(&mut self.builder.licenses.data[o..o + 4])
|
||||
.write_be((time.unix_timestamp() - TIMESTAMP_OFFSET) as u32)
|
||||
.unwrap();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn not_valid_before(&mut self, time: OffsetDateTime) -> &mut Self {
|
||||
self.write_timestamp(BLOCK_NOT_VALID_BEFORE_OFFSET, time)
|
||||
}
|
||||
|
||||
pub fn not_valid_after(&mut self, time: OffsetDateTime) -> &mut Self {
|
||||
self.write_timestamp(BLOCK_NOT_VALID_AFTER_OFFSET, time)
|
||||
}
|
||||
|
||||
/// Only valid for Server and Ts5Server license types
|
||||
pub fn server_license_type(&mut self, typ: LicenseType) -> &mut Self {
|
||||
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.typ) {
|
||||
panic!(
|
||||
"Setting the license type is only allowed for Server and Ts5Server license types, \
|
||||
but this is a {:?}",
|
||||
self.typ
|
||||
);
|
||||
}
|
||||
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN] = typ.to_u8().unwrap();
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a property in a TS5 license block.
|
||||
///
|
||||
/// `len` is the length of the content, excluding id, type and length field.
|
||||
/// Return the byte offset to where the contents of the property starts.
|
||||
fn ts5_add_property(&mut self, id: u8, typ: u8, len: usize) -> usize {
|
||||
let o = self.builder.licenses.data.len();
|
||||
self.builder.licenses.data.resize(o + len + 3, 0);
|
||||
// Increment property count
|
||||
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN + 1] += 1;
|
||||
self.builder.licenses.data[o] = u8::try_from(len).unwrap() + 2;
|
||||
self.builder.licenses.data[o + 1] = id;
|
||||
self.builder.licenses.data[o + 2] = typ;
|
||||
o + 3
|
||||
}
|
||||
|
||||
/// Only valid for Intermediate, Server and Ts5Server license types
|
||||
pub fn max_clients(&mut self, max_clients: u32) -> &mut Self {
|
||||
let o = if self.typ == LicenseBlockType::Ts5Server {
|
||||
self.ts5_add_property(3, 1, 4)
|
||||
} else {
|
||||
self.offset
|
||||
+ BLOCK_MIN_LEN
|
||||
+ match self.typ {
|
||||
LicenseBlockType::Intermediate => 0,
|
||||
LicenseBlockType::Server => 1,
|
||||
_ => panic!(
|
||||
"Setting max clients is only allowed for Intermediate, Server and \
|
||||
Ts5Server license types, but this is a {:?}",
|
||||
self.typ
|
||||
),
|
||||
}
|
||||
};
|
||||
Cursor::new(&mut self.builder.licenses.data[o..o + 4]).write_be(max_clients).unwrap();
|
||||
self
|
||||
}
|
||||
|
||||
/// Only valid for Intermediate, Server and Ts5Server license types
|
||||
pub fn issuer(&mut self, issuer: &str) -> &mut Self {
|
||||
// Check that the issuer does not contain null bytes
|
||||
assert!(
|
||||
!issuer.contains('\0'),
|
||||
"The issuer is written as a null-terminated string so it cannot contain null bytes"
|
||||
);
|
||||
|
||||
let o = if self.typ == LicenseBlockType::Ts5Server {
|
||||
self.ts5_add_property(2, 0, issuer.len() + 1)
|
||||
} else {
|
||||
if ![LicenseBlockType::Intermediate, LicenseBlockType::Server].contains(&self.typ) {
|
||||
panic!(
|
||||
"Setting the issuer is only allowed for Intermediate, Server and Ts5Server \
|
||||
license types, but this is a {:?}",
|
||||
self.typ
|
||||
);
|
||||
}
|
||||
// Check that no issuer was written so far
|
||||
assert!(
|
||||
self.builder.licenses.data.len() - self.offset == self.typ.min_len(),
|
||||
"Only a single issuer can be written into a license block"
|
||||
);
|
||||
let o = self.builder.licenses.data.len();
|
||||
self.builder.licenses.data.resize(o + issuer.len(), 0);
|
||||
o - 1
|
||||
};
|
||||
self.builder.licenses.data[o..o + issuer.len()].copy_from_slice(issuer.as_bytes());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn parse_standard_license() {
|
||||
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_standard_license_expired() {
|
||||
assert!(Licenses::parse(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_aal_license() {
|
||||
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
|
||||
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
|
||||
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
|
||||
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
|
||||
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
|
||||
3B78eHGeePIAm98vQJvpu0").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ts5_server_license_long() {
|
||||
// Slightly older format having a block with a Ts5 license block in it
|
||||
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
|
||||
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAALB6Qfbe\
|
||||
JyN+9foJhe+/KPFwyU+i++4MAA0q1/WCnizwARRuEPN1aeBQAAASBUZWFtU3BlYWsgc3lzdGV\
|
||||
tcyBHbWJIAADrhbI5gUR3thsS7FqKV5P5h7djnwMSJfF2vi58lm1VcwgRUFMAE0P7gAUCGQIA\
|
||||
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFAAf2KhQ7WLjOvwwY0Bi7LxAcWmQeT+LQt\
|
||||
uaOzjhYoA+YIBGNq1kRjlQZ").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ts5_server_license_long2() {
|
||||
// Also slightly older, has 3 properties
|
||||
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
|
||||
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAAtXG5p2n\
|
||||
iXlDfpVAGuD88w8hetKYL4vqHRkB5xB8ASRwAR2t/MN+ttjAAAASBUZWFtU3BlYWsgc3lzdGV\
|
||||
tcyBHbWJIAAAdZYGtwkeZFhzqnoV1uk+Tcphe8GgcqiPVtELF9y4wOAgR4qmAF4jnAAkDGQIA\
|
||||
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFBgEBAAGGoADzyFvD+9G6uhIxmh0jK+Uo8\
|
||||
z8fYGJVH81vWFULDS0l8yATKe4cEyqW3A==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ts5_server_license_single_block_with_issuer() {
|
||||
Licenses::parse_ignore_expired(
|
||||
BASE64_STANDARD
|
||||
.decode(
|
||||
"AQBgjAAqtcBUrw5futTtkl3+EM3OW4Lal6OTPlwuv4xV/\
|
||||
gIRFlEAG0NlAAcAAAAgQW5vbnltb3VzAACKNY+/\
|
||||
9qCbonCSxG18vBb7y7zPIgDdjTmcZoAHHclnJSATPa69Ez5XfQ==",
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ts5_server_license_single_block() {
|
||||
// Only a single server block and the ephemeral block
|
||||
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQAuio9ZxThXKE+hmzQyzBRedysp9\
|
||||
79JBTv2xP3s2oCkiAgQI70AE+YkAAcBBgMBAAAABQBoazM313063zaipPTH06zrXc91ch3huB\
|
||||
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_public_key() {
|
||||
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
|
||||
let derived_key =
|
||||
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
|
||||
|
||||
let expected_key = [
|
||||
0x40, 0xe9, 0x50, 0xc4, 0x61, 0xba, 0x18, 0x3a, 0x1e, 0xb7, 0xcb, 0xb1, 0x9a, 0xc3,
|
||||
0xd8, 0xd9, 0xc4, 0xd5, 0x24, 0xdb, 0x38, 0xf7, 0x2d, 0x3d, 0x66, 0x75, 0x77, 0x2a,
|
||||
0xc5, 0x9c, 0xc5, 0xc6,
|
||||
];
|
||||
let derived_key = derived_key.compress().0;
|
||||
assert_eq!(derived_key, expected_key);
|
||||
}
|
||||
}
|
||||
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
use std::fmt::Debug;
|
||||
use std::str;
|
||||
|
||||
use tracing::{debug, debug_span, Span};
|
||||
use tsproto_packets::packets::{InUdpPacket, OutUdpPacket, PacketType};
|
||||
use tsproto_packets::HexSlice;
|
||||
|
||||
use crate::connection::{Connection, Event};
|
||||
|
||||
fn prepare_span(is_client: bool, incoming: bool) -> Span {
|
||||
let dir = if incoming {
|
||||
if !cfg!(windows) { "\x1b[1;32mIN\x1b[0m" } else { "IN" }
|
||||
} else if !cfg!(windows) {
|
||||
"\x1b[1;31mOUT\x1b[0m"
|
||||
} else {
|
||||
"OUT"
|
||||
};
|
||||
let to = if is_client { "S" } else { "C" };
|
||||
debug_span!("packet", to, %dir)
|
||||
}
|
||||
|
||||
pub fn log_udp_packet(is_client: bool, incoming: bool, packet: &InUdpPacket) {
|
||||
let _span = prepare_span(is_client, incoming).entered();
|
||||
debug!(header = ?packet.0.header(), content = %HexSlice(packet.0.content()), "UdpPacket");
|
||||
}
|
||||
|
||||
pub fn log_out_udp_packet(is_client: bool, incoming: bool, packet: &OutUdpPacket) {
|
||||
let _span = prepare_span(is_client, incoming).entered();
|
||||
debug!(
|
||||
generation = packet.generation_id(),
|
||||
header = ?packet.data().header(),
|
||||
content = %HexSlice(packet.data().content()),
|
||||
"UdpPacket"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn log_packet<P: Debug>(is_client: bool, incoming: bool, packet: &P) {
|
||||
// packet.header.c_id is not set for newly created packets so we cannot
|
||||
// detect if a packet is incoming or not.
|
||||
let _span = prepare_span(is_client, incoming).entered();
|
||||
debug!(content = ?packet, "Packet");
|
||||
}
|
||||
|
||||
pub fn log_command(is_client: bool, incoming: bool, p_type: PacketType, cmd: &str) {
|
||||
// packet.header.c_id is not set for newly created packets so we cannot
|
||||
// detect if a packet is incoming or not.
|
||||
let _span = prepare_span(is_client, incoming).entered();
|
||||
if p_type == PacketType::Command {
|
||||
debug!(content = cmd, "Command");
|
||||
} else {
|
||||
debug!(content = cmd, "CommandLow");
|
||||
}
|
||||
}
|
||||
|
||||
/// Print the content of all packets
|
||||
///
|
||||
/// 0 - Print commands
|
||||
/// 1 - Print packets
|
||||
/// 2 - Print udp packets
|
||||
pub fn add_logger_with_verbosity(verbosity: u8, con: &mut Connection) {
|
||||
let log_commands = verbosity > 0;
|
||||
let log_packets = verbosity > 1;
|
||||
let log_udp_packets = verbosity > 2;
|
||||
add_logger(log_commands, log_packets, log_udp_packets, con);
|
||||
}
|
||||
|
||||
pub fn add_logger(
|
||||
log_commands: bool, log_packets: bool, log_udp_packets: bool, con: &mut Connection,
|
||||
) {
|
||||
if log_commands || log_packets || log_udp_packets {
|
||||
let is_client = con.is_client;
|
||||
let listener = Box::new(move |event: &Event| match event {
|
||||
Event::ReceiveUdpPacket(packet) => {
|
||||
if log_udp_packets {
|
||||
log_udp_packet(is_client, true, packet);
|
||||
}
|
||||
}
|
||||
Event::ReceivePacket(packet) => {
|
||||
if log_packets {
|
||||
log_packet(is_client, true, packet);
|
||||
} else if log_commands {
|
||||
let p_type = packet.header().packet_type();
|
||||
if p_type.is_command() {
|
||||
if let Ok(s) = str::from_utf8(packet.content()) {
|
||||
log_command(is_client, true, p_type, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::SendUdpPacket(packet) => {
|
||||
if log_udp_packets {
|
||||
log_out_udp_packet(is_client, false, packet);
|
||||
}
|
||||
}
|
||||
Event::SendPacket(packet) => {
|
||||
if log_packets {
|
||||
log_packet(is_client, false, &packet.packet());
|
||||
} else if log_commands {
|
||||
let p_type = packet.header().packet_type();
|
||||
if p_type.is_command() {
|
||||
if let Ok(s) = str::from_utf8(packet.content()) {
|
||||
log_command(is_client, false, p_type, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
con.event_listeners.push(listener);
|
||||
}
|
||||
}
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
use std::io::Cursor;
|
||||
use std::task::Context;
|
||||
|
||||
use num_traits::ToPrimitive;
|
||||
use omnom::WriteExt;
|
||||
use tracing::warn;
|
||||
use tsproto_packets::packets::*;
|
||||
|
||||
use crate::algorithms as algs;
|
||||
use crate::connection::{Connection, Event, StreamItem};
|
||||
use crate::resend::{PartialPacketId, Resender};
|
||||
use crate::{Error, Result, MAX_FRAGMENTS_LENGTH, MAX_QUEUE_LEN};
|
||||
|
||||
/// Encodes outgoing packets.
|
||||
///
|
||||
/// This part does the compression, encryption and fragmentation.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PacketCodec {
|
||||
/// The next packet id that should be sent.
|
||||
///
|
||||
/// This list is indexed by the `PacketType`, `PacketType::Init` is an
|
||||
/// invalid index.
|
||||
pub outgoing_p_ids: [PartialPacketId; 8],
|
||||
/// Used for incoming out-of-order packets.
|
||||
///
|
||||
/// Only used for `Command` and `CommandLow` packets.
|
||||
pub receive_queue: [Vec<Vec<u8>>; 2],
|
||||
/// Used for incoming fragmented packets.
|
||||
///
|
||||
/// Contains the accumulated data from fragmented packets, the header of the
|
||||
/// first packet is at the beginning, all other headers are stripped away.
|
||||
/// Only used for `Command` and `CommandLow` packets.
|
||||
pub fragmented_queue: [Option<Vec<u8>>; 2],
|
||||
/// The next packet id that is expected.
|
||||
///
|
||||
/// Works like the `outgoing_p_ids`.
|
||||
pub incoming_p_ids: [PartialPacketId; 8],
|
||||
}
|
||||
|
||||
impl PacketCodec {
|
||||
/// Handle a packet for a specific connection.
|
||||
///
|
||||
/// This part does the defragmentation, decryption and decompression.
|
||||
pub fn handle_udp_packet(
|
||||
con: &mut Connection, cx: &mut Context, mut packet_data: Vec<u8>,
|
||||
) -> Result<()> {
|
||||
let mut ack = false;
|
||||
|
||||
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
|
||||
let packet = InPacket::new(dir, &packet_data);
|
||||
let p_type = packet.header().packet_type();
|
||||
let type_i = p_type.to_usize().unwrap();
|
||||
let id = packet.header().packet_id();
|
||||
let (in_recv_win, gen_id, cur_next, limit) = con.in_receive_window(p_type, id);
|
||||
|
||||
con.resender.handle_loss_incoming(&packet, in_recv_win, cur_next);
|
||||
|
||||
if let Some(params) = &con.params {
|
||||
if p_type == PacketType::Init {
|
||||
con.stream_items.push_back(StreamItem::Error(Error::UnexpectedInitPacket));
|
||||
return Ok(());
|
||||
}
|
||||
if !con.is_client {
|
||||
let c_id = packet.header().client_id().unwrap();
|
||||
// Accept any client id for the first few acks
|
||||
let is_first_ack = gen_id == 0 && id <= 3 && p_type == PacketType::Ack;
|
||||
if c_id != params.c_id && !is_first_ack {
|
||||
con.stream_items.push_back(StreamItem::Error(Error::WrongClientId(c_id)));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore range for acks and audio packets
|
||||
if [PacketType::Ack, PacketType::AckLow, PacketType::Voice, PacketType::VoiceWhisper]
|
||||
.contains(&p_type)
|
||||
|| in_recv_win
|
||||
{
|
||||
if !packet.header().flags().contains(Flags::UNENCRYPTED) {
|
||||
if p_type == PacketType::Ack && id == 1 && con.is_client {
|
||||
// This is the ack packet for the clientinit, we take the
|
||||
// initserver as ack instead.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// If it is the first ack packet of a client, try to fake
|
||||
// decrypt it.
|
||||
let new_content = if (p_type == PacketType::Ack && id <= 1 && con.is_client)
|
||||
|| con.params.is_none()
|
||||
{
|
||||
match algs::decrypt_fake(&packet).or_else(|_| {
|
||||
if let Some(params) = &mut con.params {
|
||||
// Decrypt the packet
|
||||
algs::decrypt(&packet, gen_id, ¶ms.shared_iv, &mut params.key_cache)
|
||||
} else {
|
||||
// Failed to fake decrypt the packet
|
||||
Err(Error::WrongMac { p_type, generation_id: gen_id, packet_id: id })
|
||||
}
|
||||
}) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
con.stream_items.push_back(StreamItem::Error(e));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else if let Some(params) = &mut con.params {
|
||||
// Decrypt the packet
|
||||
match algs::decrypt(&packet, gen_id, ¶ms.shared_iv, &mut params.key_cache) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
con.stream_items.push_back(StreamItem::Error(e));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Failed to fake decrypt the packet
|
||||
con.stream_items.push_back(StreamItem::Error(Error::WrongMac {
|
||||
p_type,
|
||||
generation_id: gen_id,
|
||||
packet_id: id,
|
||||
}));
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let start = packet.header().data().len();
|
||||
packet_data[start..].copy_from_slice(&new_content);
|
||||
} else if algs::must_encrypt(p_type) {
|
||||
// Check if it is ok for the packet to be unencrypted
|
||||
con.stream_items.push_back(StreamItem::Error(Error::UnallowedUnencryptedPacket));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let packet = InPacket::new(dir, &packet_data);
|
||||
match p_type {
|
||||
PacketType::Command | PacketType::CommandLow => {
|
||||
ack = true;
|
||||
|
||||
let commands = Self::handle_command_packet(con, packet_data)?;
|
||||
|
||||
// Be careful with command packets, they are guaranteed to
|
||||
// be in the right order now.
|
||||
for c in commands {
|
||||
// Send again
|
||||
let packet = InPacket::new(dir, &c);
|
||||
let event = Event::ReceivePacket(&packet);
|
||||
con.send_event(&event);
|
||||
|
||||
let item = match InCommandBuf::try_new(dir, c) {
|
||||
Ok(c) => {
|
||||
// initivexpand2 is the ack for the last init packet
|
||||
if con.is_client
|
||||
&& c.data().packet().content().starts_with(b"initivexpand2 ")
|
||||
{
|
||||
Resender::ack_packet(con, cx, PacketType::Init, 4);
|
||||
} else if con.is_client
|
||||
&& c.data().packet().content().starts_with(b"initserver ")
|
||||
{
|
||||
// initserver acks clientinit
|
||||
Resender::ack_packet(con, cx, PacketType::Command, 2);
|
||||
} else if !con.is_client
|
||||
&& c.data().packet().content().starts_with(b"clientek ")
|
||||
{
|
||||
// clientek acks initivexpand2
|
||||
Resender::ack_packet(con, cx, PacketType::Command, 0);
|
||||
}
|
||||
StreamItem::Command(c)
|
||||
}
|
||||
Err(e) => return Err(Error::PacketParse("command", e)),
|
||||
};
|
||||
con.stream_items.push_back(item);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if p_type == PacketType::Ping {
|
||||
ack = true;
|
||||
}
|
||||
// Update packet ids
|
||||
let in_ids = &mut con.codec.incoming_p_ids;
|
||||
if p_type != PacketType::Init {
|
||||
let (id, next_gen) = id.overflowing_add(1);
|
||||
let generation_id = if next_gen { gen_id + 1 } else { gen_id };
|
||||
in_ids[type_i] = PartialPacketId { generation_id, packet_id: id };
|
||||
}
|
||||
|
||||
match packet.ack_packet() {
|
||||
Ok(Some(ack_id)) => {
|
||||
// Remove command packet from send queue if the fitting ack is received.
|
||||
let p_type = if p_type == PacketType::Ack {
|
||||
PacketType::Command
|
||||
} else if p_type == PacketType::AckLow {
|
||||
PacketType::CommandLow
|
||||
} else if p_type == PacketType::Pong {
|
||||
PacketType::Ping
|
||||
} else {
|
||||
p_type
|
||||
};
|
||||
Resender::ack_packet(con, cx, p_type, ack_id);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
con.stream_items.push_back(StreamItem::Error(Error::CreateAck(e)));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Send event after handling acks
|
||||
let event = Event::ReceivePacket(&packet);
|
||||
con.send_event(&event);
|
||||
|
||||
if p_type.is_voice() {
|
||||
con.stream_items.push_back(match InAudioBuf::try_new(dir, packet_data) {
|
||||
Ok(r) => StreamItem::Audio(r),
|
||||
Err(e) => StreamItem::Error(Error::PacketParse("audio", e)),
|
||||
});
|
||||
} else if p_type == PacketType::Init {
|
||||
con.stream_items.push_back(if con.is_client {
|
||||
match InS2CInitBuf::try_new(dir, packet_data) {
|
||||
Ok(r) => StreamItem::S2CInit(r),
|
||||
Err(e) => StreamItem::Error(Error::PacketParse("s2cinit", e)),
|
||||
}
|
||||
} else {
|
||||
match InC2SInitBuf::try_new(dir, packet_data) {
|
||||
Ok(r) => StreamItem::C2SInit(r),
|
||||
Err(e) => StreamItem::Error(Error::PacketParse("c2sinit", e)),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Send an ack for the case when it was lost
|
||||
if p_type == PacketType::Command || p_type == PacketType::CommandLow {
|
||||
ack = true;
|
||||
con.resender.handle_loss_resend_ack();
|
||||
}
|
||||
con.stream_items.push_back(StreamItem::Error(Error::NotInReceiveWindow {
|
||||
id,
|
||||
next: cur_next,
|
||||
limit,
|
||||
p_type,
|
||||
}));
|
||||
}
|
||||
|
||||
// Send ack
|
||||
if ack {
|
||||
con.send_ack_packet(cx, OutAck::new(dir.reverse(), p_type, id))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle `Command` and `CommandLow` packets.
|
||||
///
|
||||
/// They have to be handled in the right order.
|
||||
fn handle_command_packet(
|
||||
con: &mut Connection, mut packet_data: Vec<u8>,
|
||||
) -> Result<Vec<Vec<u8>>> {
|
||||
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
|
||||
let mut packet = InPacket::new(dir, &packet_data);
|
||||
let header = packet.header();
|
||||
let p_type = header.packet_type();
|
||||
let mut id = header.packet_id();
|
||||
let type_i = p_type.to_usize().unwrap();
|
||||
let cmd_i = if p_type == PacketType::Command { 0 } else { 1 };
|
||||
let r_queue = &mut con.codec.receive_queue[cmd_i];
|
||||
let frag_queue = &mut con.codec.fragmented_queue[cmd_i];
|
||||
let in_ids = &mut con.codec.incoming_p_ids[type_i];
|
||||
let cur_next = in_ids.packet_id;
|
||||
if cur_next == id {
|
||||
// In order
|
||||
let mut packets = Vec::new();
|
||||
loop {
|
||||
// Update next packet id
|
||||
*in_ids = *in_ids + 1;
|
||||
|
||||
let flags = packet.header().flags();
|
||||
let res_packet = if flags.contains(Flags::FRAGMENTED) {
|
||||
if let Some(mut frag_queue) = frag_queue.take() {
|
||||
// Last fragmented packet
|
||||
frag_queue.extend_from_slice(packet.content());
|
||||
let header = InPacket::new(dir, &frag_queue);
|
||||
// Decompress
|
||||
if header.header().flags().contains(Flags::COMPRESSED) {
|
||||
let decompressed = quicklz::decompress(
|
||||
&mut Cursor::new(header.content()),
|
||||
crate::MAX_DECOMPRESSED_SIZE,
|
||||
)
|
||||
.map_err(Error::DecompressPacket)?;
|
||||
let start = header.header().data().len();
|
||||
frag_queue.truncate(start);
|
||||
frag_queue.extend_from_slice(&decompressed);
|
||||
}
|
||||
|
||||
Some(frag_queue)
|
||||
} else {
|
||||
// Enqueue
|
||||
*frag_queue = Some(packet_data);
|
||||
None
|
||||
}
|
||||
} else if let Some(frag_queue) = frag_queue {
|
||||
// The packet is fragmented
|
||||
if frag_queue.len() < MAX_FRAGMENTS_LENGTH {
|
||||
frag_queue.extend_from_slice(packet.content());
|
||||
None
|
||||
} else {
|
||||
return Err(Error::MaxLengthExceeded("fragment queue"));
|
||||
}
|
||||
} else {
|
||||
// Decompress
|
||||
if flags.contains(Flags::COMPRESSED) {
|
||||
let decompressed = quicklz::decompress(
|
||||
&mut Cursor::new(packet.content()),
|
||||
crate::MAX_DECOMPRESSED_SIZE,
|
||||
)
|
||||
.map_err(Error::DecompressPacket)?;
|
||||
let start = packet.header().data().len();
|
||||
packet_data.truncate(start);
|
||||
packet_data.extend_from_slice(&decompressed);
|
||||
};
|
||||
Some(packet_data)
|
||||
};
|
||||
if let Some(p) = res_packet {
|
||||
packets.push(p);
|
||||
}
|
||||
|
||||
// Check if there are following packets in the receive queue.
|
||||
id = id.wrapping_add(1);
|
||||
if let Some(pos) =
|
||||
r_queue.iter().position(|p| InHeader::new(dir, p).packet_id() == id)
|
||||
{
|
||||
packet_data = r_queue.remove(pos);
|
||||
packet = InPacket::new(dir, &packet_data);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(packets)
|
||||
} else {
|
||||
// Out of order
|
||||
warn!(got = id, expected = cur_next, "Out of order command packet");
|
||||
let (limit, next_gen) = cur_next.overflowing_add(MAX_QUEUE_LEN);
|
||||
if (!next_gen && id >= cur_next && id < limit)
|
||||
|| (next_gen && (id >= cur_next || id < limit))
|
||||
{
|
||||
r_queue.push(packet_data);
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(Error::MaxLengthExceeded("command queue"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_packet(con: &mut Connection, mut packet: OutPacket) -> Result<Vec<OutUdpPacket>> {
|
||||
let p_type = packet.header().packet_type();
|
||||
let type_i = p_type.to_usize().unwrap();
|
||||
|
||||
// TODO Needed, commands should set their own flag?
|
||||
if (p_type == PacketType::Command || p_type == PacketType::CommandLow) && con.is_client {
|
||||
// Set newprotocol flag
|
||||
packet.flags(packet.header().flags() | Flags::NEWPROTOCOL);
|
||||
}
|
||||
|
||||
let p_id = if p_type == PacketType::Init {
|
||||
PartialPacketId { generation_id: 0, packet_id: 0 }
|
||||
} else {
|
||||
con.codec.outgoing_p_ids[type_i]
|
||||
};
|
||||
// We fake encrypt the first command packet of the server (id 0) and the
|
||||
// first command packet of the client (id 1, clientek).
|
||||
let mut fake_encrypt = p_type == PacketType::Command
|
||||
&& p_id.generation_id == 0
|
||||
&& ((!con.is_client && p_id.packet_id == 0)
|
||||
|| (con.is_client && p_id.packet_id == 1 && {
|
||||
// Test if it is a clientek packet
|
||||
packet.content().starts_with(b"clientek")
|
||||
}));
|
||||
// Also fake encrypt the first ack of the client, which is the response
|
||||
// for the initivexpand2 packet.
|
||||
fake_encrypt |= con.is_client
|
||||
&& p_type == PacketType::Ack
|
||||
&& p_id.generation_id == 0
|
||||
&& p_id.packet_id == 0;
|
||||
|
||||
// Get values from parameters
|
||||
let should_encrypt;
|
||||
let c_id;
|
||||
if let Some(params) = con.params.as_mut() {
|
||||
should_encrypt = algs::should_encrypt(p_type, params.voice_encryption);
|
||||
c_id = params.c_id;
|
||||
} else {
|
||||
should_encrypt = algs::should_encrypt(p_type, false);
|
||||
if should_encrypt {
|
||||
fake_encrypt = true;
|
||||
}
|
||||
c_id = 0;
|
||||
}
|
||||
|
||||
// Client id for clients
|
||||
if con.is_client {
|
||||
packet.client_id(c_id);
|
||||
}
|
||||
|
||||
if !should_encrypt && !fake_encrypt {
|
||||
packet.flags(packet.header().flags() | Flags::UNENCRYPTED);
|
||||
if let Some(params) = con.params.as_mut() {
|
||||
packet.mac().copy_from_slice(¶ms.shared_mac);
|
||||
}
|
||||
}
|
||||
|
||||
// Compress and split packet
|
||||
let packets = if p_type == PacketType::Command || p_type == PacketType::CommandLow {
|
||||
algs::compress_and_split(con.is_client, packet)
|
||||
} else {
|
||||
// Set the inner packet id for voice packets
|
||||
if con.is_client && (p_type == PacketType::Voice || p_type == PacketType::VoiceWhisper)
|
||||
{
|
||||
(&mut packet.content_mut()[..2])
|
||||
.write_be(con.codec.outgoing_p_ids[type_i].packet_id)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
vec![packet]
|
||||
};
|
||||
|
||||
let packets = packets
|
||||
.into_iter()
|
||||
.map(|mut packet| -> Result<_> {
|
||||
// Get packet id
|
||||
let p_id = if p_type == PacketType::Init {
|
||||
PartialPacketId { generation_id: 0, packet_id: 0 }
|
||||
} else {
|
||||
packet.packet_id(con.codec.outgoing_p_ids[type_i].packet_id);
|
||||
con.codec.outgoing_p_ids[type_i]
|
||||
};
|
||||
|
||||
// Encrypt if necessary
|
||||
if fake_encrypt {
|
||||
algs::encrypt_fake(&mut packet)?;
|
||||
} else if should_encrypt {
|
||||
// The params are set
|
||||
let params = con.params.as_mut().unwrap();
|
||||
algs::encrypt(
|
||||
&mut packet,
|
||||
p_id.generation_id,
|
||||
¶ms.shared_iv,
|
||||
&mut params.key_cache,
|
||||
)?;
|
||||
}
|
||||
|
||||
// Increment outgoing_p_ids
|
||||
let p_id = p_id + 1;
|
||||
if p_type != PacketType::Init {
|
||||
con.codec.outgoing_p_ids[type_i] = p_id;
|
||||
}
|
||||
Ok(OutUdpPacket::new(p_id.generation_id, packet))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(packets)
|
||||
}
|
||||
}
|
||||
Vendored
+1067
File diff suppressed because it is too large.
Load diff
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Try to approximate the not stabilized ip.is_global().
|
||||
pub fn is_global_ip(ip: &IpAddr) -> bool {
|
||||
if !ip.is_unspecified() && !ip.is_loopback() && !ip.is_multicast() {
|
||||
match *ip {
|
||||
IpAddr::V4(ref ip) => !ip.is_broadcast() && !ip.is_link_local() && !ip.is_private(),
|
||||
IpAddr::V6(_) => true,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_hex(s: &str) -> Result<Vec<u8>> {
|
||||
// Detect hex format
|
||||
if s.chars().nth(2) == Some(':') {
|
||||
// Wireshark
|
||||
Ok(s.split(':')
|
||||
.map(|s| u8::from_str_radix(s, 16))
|
||||
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||
.map_err(Error::InvalidHex)?)
|
||||
} else if s.chars().nth(2) == Some(' ') {
|
||||
// Wireshark
|
||||
Ok(s.split(' ')
|
||||
.map(|s| u8::from_str_radix(s, 16))
|
||||
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||
.map_err(Error::InvalidHex)?)
|
||||
} else if s.starts_with("0x") {
|
||||
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
// Own dumps
|
||||
Ok(s[2..]
|
||||
.split(',')
|
||||
.map(|s| u8::from_str_radix(s.trim_start_matches("0x"), 16))
|
||||
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||
.map_err(Error::InvalidHex)?)
|
||||
} else {
|
||||
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
Ok(s.as_bytes()
|
||||
.chunks(2)
|
||||
.map(|s| u8::from_str_radix(::std::str::from_utf8(s).unwrap(), 16))
|
||||
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||
.map_err(Error::InvalidHex)?)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user