use std::collections::BTreeMap;
use std::fmt;
pub mod setting_id {
pub const HEADER_TABLE_SIZE: u16 = 0x1;
pub const ENABLE_PUSH: u16 = 0x2;
pub const MAX_CONCURRENT_STREAMS: u16 = 0x3;
pub const INITIAL_WINDOW_SIZE: u16 = 0x4;
pub const MAX_FRAME_SIZE: u16 = 0x5;
pub const MAX_HEADER_LIST_SIZE: u16 = 0x6;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct H2Setting {
pub id: u16,
pub value: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct H2Priority {
pub stream_id: u32,
pub exclusive: u8,
pub dependent: u32,
pub weight: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PseudoHeader {
Method,
Path,
Authority,
Scheme,
}
impl PseudoHeader {
#[must_use]
pub fn code(self) -> char {
match self {
Self::Method => 'm',
Self::Path => 'p',
Self::Authority => 'a',
Self::Scheme => 's',
}
}
fn from_code(c: char) -> Option<Self> {
match c {
'm' => Some(Self::Method),
'p' => Some(Self::Path),
'a' => Some(Self::Authority),
's' => Some(Self::Scheme),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AkamaiH2ParseError {
SectionCount(usize),
Settings(String),
WindowUpdate(String),
Priority(String),
PseudoHeader(String),
}
impl fmt::Display for AkamaiH2ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SectionCount(n) => write!(
f,
"Akamai H2 fingerprint must have 4 `|`-separated sections, got {n}"
),
Self::Settings(t) => write!(f, "malformed SETTINGS token `{t}` (want `id:value`)"),
Self::WindowUpdate(t) => write!(f, "malformed WINDOW_UPDATE `{t}` (want one integer)"),
Self::Priority(t) => write!(
f,
"malformed PRIORITY frame `{t}` (want `stream:exclusive:dependent:weight`)"
),
Self::PseudoHeader(t) => {
write!(f, "malformed pseudo-header section `{t}` (codes m/p/a/s)")
}
}
}
}
impl std::error::Error for AkamaiH2ParseError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AkamaiH2Divergence {
Setting {
id: u16,
observed: Option<u32>,
target: Option<u32>,
},
SettingsOrder {
observed: Vec<u16>,
target: Vec<u16>,
},
WindowUpdate {
observed: u32,
target: u32,
},
Priority {
observed: Vec<H2Priority>,
target: Vec<H2Priority>,
},
PseudoHeaderOrder {
observed: Vec<PseudoHeader>,
target: Vec<PseudoHeader>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AkamaiH2Fingerprint {
pub settings: Vec<H2Setting>,
pub window_update: u32,
pub priorities: Vec<H2Priority>,
pub pseudo_header_order: Vec<PseudoHeader>,
}
impl AkamaiH2Fingerprint {
pub fn parse(raw: &str) -> Result<Self, AkamaiH2ParseError> {
let sections: Vec<&str> = raw.split('|').collect();
if sections.len() != 4 {
return Err(AkamaiH2ParseError::SectionCount(sections.len()));
}
let settings = parse_settings(sections[0])?;
let window_update: u32 = sections[1]
.parse()
.map_err(|_| AkamaiH2ParseError::WindowUpdate(sections[1].to_string()))?;
let priorities = parse_priorities(sections[2])?;
let pseudo_header_order = parse_pseudo_headers(sections[3])?;
Ok(Self {
settings,
window_update,
priorities,
pseudo_header_order,
})
}
#[must_use]
pub fn to_canonical(&self) -> String {
let settings = self
.settings
.iter()
.map(|s| format!("{}:{}", s.id, s.value))
.collect::<Vec<_>>()
.join(";");
let priorities = if self.priorities.is_empty() {
"0".to_string()
} else {
self.priorities
.iter()
.map(|p| {
format!(
"{}:{}:{}:{}",
p.stream_id, p.exclusive, p.dependent, p.weight
)
})
.collect::<Vec<_>>()
.join(",")
};
let pseudo = self
.pseudo_header_order
.iter()
.map(|p| p.code().to_string())
.collect::<Vec<_>>()
.join(",");
format!("{settings}|{}|{priorities}|{pseudo}", self.window_update)
}
#[must_use]
pub fn setting(&self, id: u16) -> Option<u32> {
self.settings.iter().find(|s| s.id == id).map(|s| s.value)
}
#[must_use]
pub fn header_table_size(&self) -> Option<u32> {
self.setting(setting_id::HEADER_TABLE_SIZE)
}
#[must_use]
pub fn enable_push(&self) -> Option<u32> {
self.setting(setting_id::ENABLE_PUSH)
}
#[must_use]
pub fn max_concurrent_streams(&self) -> Option<u32> {
self.setting(setting_id::MAX_CONCURRENT_STREAMS)
}
#[must_use]
pub fn initial_window_size(&self) -> Option<u32> {
self.setting(setting_id::INITIAL_WINDOW_SIZE)
}
#[must_use]
pub fn max_frame_size(&self) -> Option<u32> {
self.setting(setting_id::MAX_FRAME_SIZE)
}
#[must_use]
pub fn max_header_list_size(&self) -> Option<u32> {
self.setting(setting_id::MAX_HEADER_LIST_SIZE)
}
#[must_use]
pub fn matches(&self, other: &Self) -> bool {
self.diff(other).is_empty()
}
#[must_use]
pub fn diff(&self, target: &Self) -> Vec<AkamaiH2Divergence> {
let mut out = Vec::new();
let self_map: BTreeMap<u16, u32> = self.settings.iter().map(|s| (s.id, s.value)).collect();
let target_map: BTreeMap<u16, u32> =
target.settings.iter().map(|s| (s.id, s.value)).collect();
let mut ids: Vec<u16> = self_map.keys().chain(target_map.keys()).copied().collect();
ids.sort_unstable();
ids.dedup();
for id in ids {
let o = self_map.get(&id).copied();
let t = target_map.get(&id).copied();
if o != t {
out.push(AkamaiH2Divergence::Setting {
id,
observed: o,
target: t,
});
}
}
if self_map == target_map {
let self_order: Vec<u16> = self.settings.iter().map(|s| s.id).collect();
let target_order: Vec<u16> = target.settings.iter().map(|s| s.id).collect();
if self_order != target_order {
out.push(AkamaiH2Divergence::SettingsOrder {
observed: self_order,
target: target_order,
});
}
}
if self.window_update != target.window_update {
out.push(AkamaiH2Divergence::WindowUpdate {
observed: self.window_update,
target: target.window_update,
});
}
if self.priorities != target.priorities {
out.push(AkamaiH2Divergence::Priority {
observed: self.priorities.clone(),
target: target.priorities.clone(),
});
}
if self.pseudo_header_order != target.pseudo_header_order {
out.push(AkamaiH2Divergence::PseudoHeaderOrder {
observed: self.pseudo_header_order.clone(),
target: target.pseudo_header_order.clone(),
});
}
out
}
}
fn parse_settings(section: &str) -> Result<Vec<H2Setting>, AkamaiH2ParseError> {
if section.is_empty() {
return Ok(Vec::new());
}
section
.split(';')
.map(|tok| {
let (id, value) = tok
.split_once(':')
.ok_or_else(|| AkamaiH2ParseError::Settings(tok.to_string()))?;
let id: u16 = id
.parse()
.map_err(|_| AkamaiH2ParseError::Settings(tok.to_string()))?;
let value: u32 = value
.parse()
.map_err(|_| AkamaiH2ParseError::Settings(tok.to_string()))?;
Ok(H2Setting { id, value })
})
.collect()
}
fn parse_priorities(section: &str) -> Result<Vec<H2Priority>, AkamaiH2ParseError> {
if section == "0" || section.is_empty() {
return Ok(Vec::new());
}
section
.split(',')
.map(|frame| {
let parts: Vec<&str> = frame.split(':').collect();
if parts.len() != 4 {
return Err(AkamaiH2ParseError::Priority(frame.to_string()));
}
let stream_id: u32 = parts[0]
.parse()
.map_err(|_| AkamaiH2ParseError::Priority(frame.to_string()))?;
let exclusive: u8 = parts[1]
.parse()
.map_err(|_| AkamaiH2ParseError::Priority(frame.to_string()))?;
let dependent: u32 = parts[2]
.parse()
.map_err(|_| AkamaiH2ParseError::Priority(frame.to_string()))?;
let weight: u16 = parts[3]
.parse()
.map_err(|_| AkamaiH2ParseError::Priority(frame.to_string()))?;
Ok(H2Priority {
stream_id,
exclusive,
dependent,
weight,
})
})
.collect()
}
fn parse_pseudo_headers(section: &str) -> Result<Vec<PseudoHeader>, AkamaiH2ParseError> {
if section.is_empty() {
return Err(AkamaiH2ParseError::PseudoHeader(section.to_string()));
}
section
.split(',')
.map(|tok| {
let mut chars = tok.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => PseudoHeader::from_code(c)
.ok_or_else(|| AkamaiH2ParseError::PseudoHeader(tok.to_string())),
_ => Err(AkamaiH2ParseError::PseudoHeader(tok.to_string())),
}
})
.collect()
}
#[cfg(test)]
#[path = "akamai_h2/tests.rs"]
mod tests;