chadtmiller.com/monolith
An atproto PDS
0
0
//! RFC 9651 structured fields, as far as the spaces headers need them: a
//! Dictionary read (§4.2.2), and a Dictionary and an Inner List with its
//! parameters written (§4.1.2, §4.1.1.1). Every bare item type is read and
//! written.
use base64::Engine;
use base64::alphabet;
use base64::engine::general_purpose::STANDARD;
use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
/// Byte Sequences are read with or without padding.
const B64_ANY_PAD: GeneralPurpose = GeneralPurpose::new(
&alphabet::STANDARD,
GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Bare {
Integer(i64),
/// In thousandths: a Decimal has at most three fractional digits.
Decimal(i64),
String(String),
Token(String),
Bytes(Vec<u8>),
Boolean(bool),
Date(i64),
DisplayString(String),
}
/// Parameters in order, each key once.
pub type Params = Vec<(String, Bare)>;
pub type Item = (Bare, Params);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Member {
Item(Item),
InnerList(Vec<Item>, Params),
}
/// Keys in order, each once: a key given again keeps its place and takes
/// the later value, as RFC 9651 reads a Dictionary.
pub type Dictionary = Vec<(String, Member)>;
/// The member of `d` named `key`.
pub fn member<'a>(d: &'a Dictionary, key: &str) -> Option<&'a Member> {
d.iter().find(|(k, _)| k == key).map(|(_, m)| m)
}
/// The parameter of `p` named `key`.
pub fn param<'a>(p: &'a Params, key: &str) -> Option<&'a Bare> {
p.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// The members of `d` tagged `tag`, as `spec/SPACES.md` ("HTTP Message
/// Signatures") says: those whose value is an Inner List with a parameter
/// `tag` that is the String `tag`, each as its label, items and parameters.
pub fn tagged<'a>(d: &'a Dictionary, tag: &str) -> Vec<(&'a str, &'a [Item], &'a Params)> {
d.iter()
.filter_map(|(label, m)| match m {
Member::InnerList(items, params)
if matches!(param(params, "tag"), Some(Bare::String(t)) if t == tag) =>
{
Some((label.as_str(), items.as_slice(), params))
}
_ => None,
})
.collect()
}
fn put<T>(into: &mut Vec<(String, T)>, key: String, value: T) {
match into.iter_mut().find(|(k, _)| *k == key) {
Some(slot) => slot.1 = value,
None => into.push((key, value)),
}
}
/// A field value read as a Dictionary; None if it is not one. Leading and
/// trailing whitespace, which HTTP does not count as the value's, is
/// passed over.
pub fn parse_dictionary(field: &str) -> Option<Dictionary> {
let mut p = Parser(field.trim_matches([' ', '\t']).as_bytes());
let d = p.dictionary()?;
p.0.is_empty().then_some(d)
}
struct Parser<'a>(&'a [u8]);
impl Parser<'_> {
fn peek(&self) -> Option<u8> {
self.0.first().copied()
}
fn next(&mut self) -> Option<u8> {
let (&c, rest) = self.0.split_first()?;
self.0 = rest;
Some(c)
}
fn skip(&mut self, what: &[u8]) {
while self.peek().is_some_and(|c| what.contains(&c)) {
self.0 = &self.0[1..];
}
}
fn dictionary(&mut self) -> Option<Dictionary> {
let mut d = Dictionary::new();
while !self.0.is_empty() {
let key = self.key()?;
let m = if self.peek() == Some(b'=') {
self.next();
self.item_or_inner_list()?
} else {
Member::Item((Bare::Boolean(true), self.params()?))
};
put(&mut d, key, m);
self.skip(b" \t");
if self.0.is_empty() {
break;
}
if self.next()? != b',' {
return None;
}
self.skip(b" \t");
if self.0.is_empty() {
return None;
}
}
Some(d)
}
fn item_or_inner_list(&mut self) -> Option<Member> {
if self.peek() != Some(b'(') {
return Some(Member::Item(self.item()?));
}
self.next();
let mut items = Vec::new();
loop {
self.skip(b" ");
if self.peek()? == b')' {
self.next();
return Some(Member::InnerList(items, self.params()?));
}
items.push(self.item()?);
if !matches!(self.peek()?, b' ' | b')') {
return None;
}
}
}
fn item(&mut self) -> Option<Item> {
Some((self.bare()?, self.params()?))
}
fn params(&mut self) -> Option<Params> {
let mut p = Params::new();
while self.peek() == Some(b';') {
self.next();
self.skip(b" ");
let key = self.key()?;
let value = if self.peek() == Some(b'=') {
self.next();
self.bare()?
} else {
Bare::Boolean(true)
};
put(&mut p, key, value);
}
Some(p)
}
fn key(&mut self) -> Option<String> {
let first = self.peek()?;
if !(first.is_ascii_lowercase() || first == b'*') {
return None;
}
let n = self
.0
.iter()
.take_while(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_-.*".contains(c))
.count();
let key = String::from_utf8(self.0[..n].to_vec()).ok()?;
self.0 = &self.0[n..];
Some(key)
}
fn bare(&mut self) -> Option<Bare> {
match self.peek()? {
b'-' | b'0'..=b'9' => self.number(),
b'"' => self.string().map(Bare::String),
b'*' | b'A'..=b'Z' | b'a'..=b'z' => Some(self.token()),
b':' => self.bytes(),
b'?' => {
self.next();
match self.next()? {
b'1' => Some(Bare::Boolean(true)),
b'0' => Some(Bare::Boolean(false)),
_ => None,
}
}
b'@' => {
self.next();
match self.number()? {
Bare::Integer(n) => Some(Bare::Date(n)),
_ => None,
}
}
b'%' => self.display_string(),
_ => None,
}
}
fn number(&mut self) -> Option<Bare> {
let negative = self.peek() == Some(b'-');
if negative {
self.next();
}
if !self.peek()?.is_ascii_digit() {
return None;
}
let (mut int, mut frac, mut decimal) = (String::new(), String::new(), false);
while let Some(c) = self.peek() {
if c.is_ascii_digit() {
let digits = if decimal { &mut frac } else { &mut int };
digits.push(c as char);
} else if c == b'.' && !decimal {
if int.len() > 12 {
return None;
}
decimal = true;
} else {
break;
}
self.next();
if (!decimal && int.len() > 15) || (decimal && int.len() + 1 + frac.len() > 16) {
return None;
}
}
let sign = if negative { -1 } else { 1 };
if !decimal {
return Some(Bare::Integer(sign * int.parse::<i64>().ok()?));
}
if frac.is_empty() || frac.len() > 3 {
return None;
}
let thousandths =
int.parse::<i64>().ok()? * 1000 + format!("{frac:0<3}").parse::<i64>().ok()?;
Some(Bare::Decimal(sign * thousandths))
}
fn string(&mut self) -> Option<String> {
self.next();
let mut out = String::new();
loop {
match self.next()? {
b'\\' => match self.next()? {
c @ (b'"' | b'\\') => out.push(c as char),
_ => return None,
},
b'"' => return Some(out),
c @ 0x20..=0x7e => out.push(c as char),
_ => return None,
}
}
}
fn token(&mut self) -> Bare {
let n = 1 + self.0[1..]
.iter()
.take_while(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~:/".contains(c))
.count();
let token = String::from_utf8_lossy(&self.0[..n]).into_owned();
self.0 = &self.0[n..];
Bare::Token(token)
}
fn bytes(&mut self) -> Option<Bare> {
self.next();
let n = self.0.iter().position(|&c| c == b':')?;
let text = &self.0[..n];
if !text
.iter()
.all(|c| c.is_ascii_alphanumeric() || b"+/=".contains(c))
{
return None;
}
let bytes = B64_ANY_PAD.decode(text).ok()?;
self.0 = &self.0[n + 1..];
Some(Bare::Bytes(bytes))
}
fn display_string(&mut self) -> Option<Bare> {
self.next();
if self.next()? != b'"' {
return None;
}
let mut out = Vec::new();
loop {
match self.next()? {
b'%' => {
let hex = |c: u8| match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
_ => None,
};
let (hi, lo) = (hex(self.next()?)?, hex(self.next()?)?);
out.push(hi << 4 | lo);
}
b'"' => return String::from_utf8(out).ok().map(Bare::DisplayString),
c @ 0x20..=0x7e => out.push(c),
_ => return None,
}
}
}
}
/// An Inner List and its parameters, serialized.
pub fn serialize_inner_list(items: &[Item], params: &Params) -> String {
let mut out = String::new();
put_inner_list(&mut out, items, params);
out
}
/// A Dictionary, serialized: each member `key=value`, a Boolean true Item
/// as its key and parameters alone, joined by `, `.
pub fn serialize_dictionary(d: &Dictionary) -> String {
let mut out = String::new();
for (i, (key, m)) in d.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
out.push_str(key);
match m {
Member::Item((Bare::Boolean(true), p)) => serialize_params(&mut out, p),
Member::Item((bare, p)) => {
out.push('=');
serialize_bare(&mut out, bare);
serialize_params(&mut out, p);
}
Member::InnerList(items, p) => {
out.push('=');
put_inner_list(&mut out, items, p);
}
}
}
out
}
fn put_inner_list(out: &mut String, items: &[Item], params: &Params) {
out.push('(');
for (i, (bare, p)) in items.iter().enumerate() {
if i > 0 {
out.push(' ');
}
serialize_bare(out, bare);
serialize_params(out, p);
}
out.push(')');
serialize_params(out, params);
}
fn serialize_params(out: &mut String, params: &Params) {
for (k, v) in params {
out.push(';');
out.push_str(k);
if *v != Bare::Boolean(true) {
out.push('=');
serialize_bare(out, v);
}
}
}
fn serialize_bare(out: &mut String, bare: &Bare) {
match bare {
Bare::Integer(n) => out.push_str(&n.to_string()),
Bare::Decimal(t) => {
if *t < 0 {
out.push('-');
}
let t = t.unsigned_abs();
let frac = format!("{:03}", t % 1000);
let frac = frac.trim_end_matches('0');
out.push_str(&format!(
"{}.{}",
t / 1000,
if frac.is_empty() { "0" } else { frac }
));
}
Bare::String(s) => {
out.push('"');
for c in s.chars() {
if c == '"' || c == '\\' {
out.push('\\');
}
out.push(c);
}
out.push('"');
}
Bare::Token(t) => out.push_str(t),
Bare::Bytes(b) => {
out.push(':');
out.push_str(&STANDARD.encode(b));
out.push(':');
}
Bare::Boolean(b) => out.push_str(if *b { "?1" } else { "?0" }),
Bare::Date(n) => out.push_str(&format!("@{n}")),
Bare::DisplayString(s) => {
out.push_str("%\"");
for &b in s.as_bytes() {
if b == b'%' || b == b'"' || !(0x20..=0x7e).contains(&b) {
out.push_str(&format!("%{b:02x}"));
} else {
out.push(b as char);
}
}
out.push('"');
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip(field: &str) -> String {
let d = parse_dictionary(field).unwrap();
let Member::InnerList(items, params) = &d[0].1 else {
panic!("{field}")
};
serialize_inner_list(items, params)
}
#[test]
fn reads_and_writes_every_bare_item() {
let field = r#"a=("x\"y" tok:en/1 :AQID: ?0 @-5 %"caf%c3%a9 %25" 12 -3.50);int=-15;dec=0.001;t;f=?0"#;
assert_eq!(
round_trip(field),
r#"("x\"y" tok:en/1 :AQID: ?0 @-5 %"caf%c3%a9 %25" 12 -3.5);int=-15;dec=0.001;t;f=?0"#
);
// Spaces inside the list, and padding left off a Byte Sequence.
assert_eq!(round_trip("a=( 1 :AQ: )"), "(1 :AQ==:)");
}
#[test]
fn refuses_what_is_no_dictionary() {
for bad in [
"a=",
"a=1,",
"A=1",
"a=(1",
"a=(1)x",
"a=\"\\x\"",
"a=1.2345",
"a=1234567890123456",
"a=?2",
"a=%\"%C3\"",
"a=:**:",
"a=1;",
"a=1 b=2",
",a=1",
] {
assert_eq!(parse_dictionary(bad), None, "{bad}");
}
assert_eq!(
parse_dictionary("a=1, a=2, b"),
Some(vec![
("a".into(), Member::Item((Bare::Integer(2), vec![]))),
("b".into(), Member::Item((Bare::Boolean(true), vec![])))
])
);
assert_eq!(parse_dictionary(""), Some(vec![]));
}
#[test]
fn writes_a_dictionary_as_read() {
let field = "a=1,b=?1;x=?1, c=(\"q\";sf=?1 tok);p=:AQ:, d;y=\"\\\\\", e=?0";
assert_eq!(
serialize_dictionary(&parse_dictionary(field).unwrap()),
"a=1, b;x, c=(\"q\";sf tok);p=:AQ==:, d;y=\"\\\\\", e=?0"
);
let tagged_d =
parse_dictionary("a=(1);tag=\"t\", b=(2);tag=t, c=1;tag=\"t\", d=();tag=\"t\"")
.unwrap();
let labels: Vec<&str> = tagged(&tagged_d, "t").iter().map(|m| m.0).collect();
assert_eq!(labels, ["a", "d"]);
}
}