use std::fmt;
use shared::error::Result;
use super::{TypedAttribute, string_attribute};
use crate::grammar::{self, invalid, syntax};
use crate::util::ConnectionRole;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fingerprint {
pub hash_function: String,
pub bytes: Vec<u8>,
}
impl Fingerprint {
fn digest_len(hash_function: &str) -> Option<usize> {
Some(match hash_function.to_ascii_lowercase().as_str() {
"md2" | "md5" => 16,
"sha-1" => 20,
"sha-224" => 28,
"sha-256" => 32,
"sha-384" => 48,
"sha-512" => 64,
_ => return None,
})
}
}
impl TypedAttribute for Fingerprint {
const NAME: &'static str = "fingerprint";
fn parse(value: &str) -> Result<Self> {
let Some((hash_function, fingerprint)) = value.split_once(' ') else {
return Err(syntax("a=fingerprint", value));
};
if !grammar::is_token(hash_function) {
return Err(syntax("a=fingerprint", value));
}
let mut bytes = Vec::with_capacity(fingerprint.len() / 3 + 1);
for pair in fingerprint.split(':') {
match pair.as_bytes() {
[high, low] if high.is_ascii_hexdigit() && low.is_ascii_hexdigit() => {
let digit = |b: u8| (b as char).to_digit(16).unwrap_or(0) as u8;
bytes.push(digit(*high) << 4 | digit(*low));
}
_ => return Err(syntax("a=fingerprint", value)),
}
}
if Self::digest_len(hash_function).is_some_and(|len| len != bytes.len()) {
return Err(invalid("a=fingerprint length", value));
}
Ok(Fingerprint {
hash_function: hash_function.to_owned(),
bytes,
})
}
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ", self.hash_function)?;
for (i, byte) in self.bytes.iter().enumerate() {
if i > 0 {
f.write_str(":")?;
}
write!(f, "{byte:02X}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Setup(pub ConnectionRole);
impl TypedAttribute for Setup {
const NAME: &'static str = "setup";
fn parse(value: &str) -> Result<Self> {
match ConnectionRole::from(value) {
ConnectionRole::Unspecified => Err(syntax("a=setup", value)),
role => Ok(Setup(role)),
}
}
}
impl fmt::Display for Setup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
string_attribute!(
TlsId,
"tls-id",
"a=tls-id",
|v| (20..=255).contains(&v.len())
&& v.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'-' | b'_'))
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub assertion: String,
pub extensions: Vec<(String, Option<String>)>,
}
impl TypedAttribute for Identity {
const NAME: &'static str = "identity";
fn parse(value: &str) -> Result<Self> {
let mut fields = grammar::fields("a=identity", value)?.into_iter();
let assertion = fields.next().unwrap_or_default();
if !grammar::is_base64(assertion) {
return Err(syntax("a=identity", "(assertion)"));
}
let mut extensions = Vec::new();
for extension in fields {
let (name, extension_value) = match extension.split_once('=') {
Some((name, v)) => (name, Some(v)),
None => (extension, None),
};
if !grammar::is_token(name)
|| !extension_value.is_none_or(|v| !v.is_empty() && !v.contains(';'))
{
return Err(syntax("a=identity extension", extension));
}
extensions.push((name.to_owned(), extension_value.map(str::to_owned)));
}
Ok(Identity {
assertion: assertion.to_owned(),
extensions,
})
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.assertion)?;
for (name, value) in &self.extensions {
write!(f, " {name}")?;
if let Some(value) = value {
write!(f, "={value}")?;
}
}
Ok(())
}
}