1#![forbid(unsafe_code)]
51
52use sha2::{Digest, Sha256};
53
54#[doc = include_str!("../SPEC.md")]
55pub mod spec {
56 #[doc = include_str!("../CITATIONS.md")]
57 pub mod citations {}
58 #[doc = include_str!("../KEYLOG.md")]
59 pub mod keylog {}
60}
61
62pub mod cite;
63pub mod keylog;
64
65pub const LABEL: &str = "echovalidum";
67pub const TAG: &str = "echovalidum-content";
69pub const COMPONENTS: [&str; 5] = ["\"@status\"", "\"content-type\"", "\"content-digest\"", "\"@authority\";req", "\"@path\";req"];
71pub const ALGORITHMS: [&str; 3] = ["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"];
73
74#[derive(Debug, Clone, Copy)]
77pub struct Response<'a> {
78 pub status: u16,
79 pub authority: &'a str,
80 pub path: &'a str,
81 pub headers: &'a [(&'a str, &'a str)],
82 pub body: &'a [u8],
83}
84
85impl Response<'_> {
86 pub fn header(&self, name: &str) -> &str {
88 self.headers.iter().find(|h| h.0.eq_ignore_ascii_case(name)).map_or("", |h| h.1)
89 }
90
91 pub fn field(&self, name: &str) -> Option<String> {
94 let values: Vec<&str> = self.headers.iter().filter(|h| h.0.eq_ignore_ascii_case(name)).map(|h| h.1.trim_matches([' ', '\t'])).collect();
95 (!values.is_empty()).then(|| values.join(", "))
96 }
97}
98
99#[derive(Debug, Clone, Copy)]
102pub struct Key<'a> {
103 pub alg: &'a str,
104 pub public: &'a str,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct DirectoryKey {
110 pub kty: String,
112 pub alg: String,
114 pub public: String,
116 pub kid: Option<String>,
118 pub nbf: Option<i64>,
120 pub exp: Option<i64>,
122}
123
124impl DirectoryKey {
125 pub fn thumbprint(&self) -> String {
127 jwk_thumbprint(&self.alg, &self.kty, &self.public)
128 }
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct Directory {
134 pub keys: Vec<DirectoryKey>,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum DirectoryError {
142 NotJson,
144 NoKeys,
146}
147
148impl std::fmt::Display for DirectoryError {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 f.write_str(match self {
151 DirectoryError::NotJson => "the key directory isn't JSON",
152 DirectoryError::NoKeys => "the key directory has no \"keys\" list",
153 })
154 }
155}
156
157impl std::error::Error for DirectoryError {}
158
159impl Directory {
160 pub fn from_json(text: &str) -> Result<Directory, DirectoryError> {
162 let value = json::parse(text).ok_or(DirectoryError::NotJson)?;
163 let keys = value.get("keys").and_then(json::Value::as_array).ok_or(DirectoryError::NoKeys)?;
164 let whole = |v: Option<&json::Value>| -> Result<Option<i64>, ()> {
165 match v {
166 None => Ok(None),
167 Some(json::Value::Number(n)) if n.fract() == 0.0 && n.abs() < 9.0e15 => Ok(Some(*n as i64)),
168 Some(_) => Err(()),
169 }
170 };
171 let keys = keys
172 .iter()
173 .filter_map(|k| {
174 let text = |name: &str| k.get(name).and_then(json::Value::as_str).map(str::to_string);
175 Some(DirectoryKey {
176 kty: text("kty")?,
177 alg: text("alg")?,
178 public: text("pub")?,
179 kid: text("kid"),
180 nbf: whole(k.get("nbf")).ok()?,
181 exp: whole(k.get("exp")).ok()?,
182 })
183 })
184 .collect();
185 Ok(Directory { keys })
186 }
187
188 pub fn find(&self, keyid: &str) -> Option<&DirectoryKey> {
190 self.keys.iter().find(|k| k.kty == "AKP" && k.thumbprint() == keyid)
191 }
192
193 pub fn check(&self, response: &Response<'_>) -> Check {
195 examine(response, &self.keys, false)
196 }
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
201pub enum Problem {
202 NotSigned,
204 Malformed,
206 NotAReceipt,
208 Uncovered,
210 MissingHeader,
212 UnsupportedDigest,
214 DigestMismatch,
216 UnknownKey,
218 UnsupportedAlgorithm,
220 KeyNotValidThen,
222 BadSignature,
224}
225
226impl Problem {
227 pub const ALL: [Problem; 11] = [
229 Problem::NotSigned,
230 Problem::Malformed,
231 Problem::NotAReceipt,
232 Problem::Uncovered,
233 Problem::MissingHeader,
234 Problem::UnsupportedDigest,
235 Problem::DigestMismatch,
236 Problem::UnknownKey,
237 Problem::UnsupportedAlgorithm,
238 Problem::KeyNotValidThen,
239 Problem::BadSignature,
240 ];
241
242 pub fn code(self) -> &'static str {
244 match self {
245 Problem::NotSigned => "not-signed",
246 Problem::Malformed => "malformed",
247 Problem::NotAReceipt => "not-a-receipt",
248 Problem::Uncovered => "uncovered",
249 Problem::MissingHeader => "missing-header",
250 Problem::UnsupportedDigest => "unsupported-digest",
251 Problem::DigestMismatch => "digest-mismatch",
252 Problem::UnknownKey => "unknown-key",
253 Problem::UnsupportedAlgorithm => "unsupported-algorithm",
254 Problem::KeyNotValidThen => "key-not-valid-then",
255 Problem::BadSignature => "bad-signature",
256 }
257 }
258
259 pub fn from_code(code: &str) -> Option<Problem> {
261 Problem::ALL.into_iter().find(|p| p.code() == code)
262 }
263
264 pub fn explain(self) -> &'static str {
266 match self {
267 Problem::NotSigned => "It carries no signature labelled echovalidum, so it isn't a signed receipt.",
268 Problem::Malformed => "Its Signature-Input or Signature can't be read as a receipt's.",
269 Problem::NotAReceipt => "Its signature isn't tagged echovalidum-content: it's another kind of signature, not a receipt.",
270 Problem::Uncovered => "Its signature doesn't cover exactly the five parts a receipt signs: its status, Content-Type and Content-Digest, and the address it answered.",
271 Problem::MissingHeader => "A header its signature covers is missing, so what was signed can't be rebuilt.",
272 Problem::UnsupportedDigest => "Its Content-Digest isn't a single SHA-256 digest.",
273 Problem::DigestMismatch => "The SHA-256 of its bytes doesn't match its Content-Digest: the bytes were changed.",
274 Problem::UnknownKey => "No key in the site's key directory has the thumbprint its signature names.",
275 Problem::UnsupportedAlgorithm => "The key it names isn't an ML-DSA-44, ML-DSA-65 or ML-DSA-87 key.",
276 Problem::KeyNotValidThen => "It was signed at a time the key directory says its key wasn't in use.",
277 Problem::BadSignature => "Its signature doesn't verify with its key: what was signed isn't what it shows.",
278 }
279 }
280}
281
282impl std::fmt::Display for Problem {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.write_str(self.code())
285 }
286}
287
288#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct SignatureBase {
291 pub label: String,
293 pub parts: usize,
295 pub keyid: String,
297 pub text: String,
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct Check {
304 pub bytes: usize,
306 pub status: u16,
307 pub authority: String,
308 pub path: String,
309 pub alg: String,
311 pub digest_matches: bool,
313 pub keyid: String,
315 pub key_matches: bool,
317 pub parts: usize,
319 pub signature_bytes: usize,
321 pub verified: bool,
323 pub number: String,
326 pub created: Option<i64>,
328 pub problems: Vec<Problem>,
330}
331
332impl Check {
333 pub fn ok(&self) -> bool {
335 self.problems.is_empty()
336 }
337
338 pub fn why(&self) -> Vec<&'static str> {
340 self.problems.iter().map(|p| p.explain()).collect()
341 }
342
343 pub fn lines(&self) -> Vec<String> {
345 let short = &self.keyid[..self.keyid.len().min(12)];
346 let by = if self.alg.is_empty() { String::new() } else { format!(" with {}", self.alg) };
347 vec![
348 format!("Receipt: {} bytes from {}{}, HTTP {}, signed by the site{by}.", self.bytes, self.authority, self.path, self.status),
349 if self.digest_matches {
350 "Receipt digest: the SHA-256 of those bytes matches its Content-Digest.".to_string()
351 } else {
352 "Receipt digest: the SHA-256 of those bytes doesn't match its Content-Digest: they were changed.".to_string()
353 },
354 if self.key_matches {
355 format!("Receipt key: {short}..., echovalidum.com's {} key; its thumbprint matches.", self.alg)
356 } else if self.alg.is_empty() {
357 format!("Receipt key: the signature names {short}..., which the site's key directory doesn't list.")
358 } else {
359 format!("Receipt key: the signature names {short}..., not this key.")
360 },
361 format!("Receipt signature: {} bytes over {} signed parts: {}.", self.signature_bytes, self.parts,
362 if self.verified { "verified" } else { "doesn't verify" }),
363 format!("Receipt number: {}, from the SHA-256 of that signature: your card's.", self.number),
364 ]
365 }
366}
367
368pub fn check(response: &Response<'_>, key: &Key<'_>) -> Check {
372 let key = DirectoryKey { kty: "AKP".into(), alg: key.alg.into(), public: key.public.into(), kid: None, nbf: None, exp: None };
373 examine(response, std::slice::from_ref(&key), true)
374}
375
376struct Signed {
378 components: Vec<(String, Vec<(String, sf::Bare)>)>,
379 params: Vec<(String, sf::Bare)>,
380 signature: Vec<u8>,
381}
382
383impl Signed {
384 fn param(&self, name: &str) -> Option<&sf::Bare> {
385 self.params.iter().rev().find(|p| p.0 == name).map(|p| &p.1)
386 }
387 fn keyid(&self) -> String {
388 match self.param("keyid") {
389 Some(sf::Bare::String(s)) => s.clone(),
390 _ => String::new(),
391 }
392 }
393 fn created(&self) -> Option<i64> {
394 match self.param("created") {
395 Some(sf::Bare::Integer(n)) => Some(*n),
396 _ => None,
397 }
398 }
399 fn serialized(&self) -> String {
401 let items: Vec<String> = self.components.iter().map(|(name, params)| format!("{}{}", sf::string(name), sf::params(params))).collect();
402 format!("({}){}", items.join(" "), sf::params(&self.params))
403 }
404 fn component_ids(&self) -> Vec<String> {
405 self.components.iter().map(|(name, params)| format!("{}{}", sf::string(name), sf::params(params))).collect()
406 }
407}
408
409fn signed(response: &Response<'_>) -> Result<Signed, Problem> {
411 let (Some(input), Some(signature)) = (response.field("signature-input"), response.field("signature")) else {
412 return Err(Problem::NotSigned);
413 };
414 let (Some(input), Some(signature)) = (sf::dictionary(&input), sf::dictionary(&signature)) else {
415 return Err(Problem::Malformed);
416 };
417 let member = |d: &[(String, sf::Member)]| d.iter().rev().find(|m| m.0 == LABEL).map(|m| m.1.clone());
418 let (Some(input), Some(signature)) = (member(&input), member(&signature)) else {
419 return Err(Problem::NotSigned);
420 };
421 match (input, signature) {
422 (sf::Member::InnerList(components, params), sf::Member::Item(sf::Bare::Bytes(signature), _)) => {
423 let components = components
424 .into_iter()
425 .map(|(item, params)| match item {
426 sf::Bare::String(name) => Ok((name, params)),
427 _ => Err(Problem::Malformed),
428 })
429 .collect::<Result<Vec<_>, _>>()?;
430 Ok(Signed { components, params, signature })
431 }
432 _ => Err(Problem::Malformed),
433 }
434}
435
436fn read_receipt(response: &Response<'_>) -> Result<Signed, (Problem, Option<Signed>)> {
438 let signed = signed(response).map_err(|p| (p, None))?;
439 if !matches!(signed.param("tag"), Some(sf::Bare::String(tag)) if tag == TAG) {
440 return Err((Problem::NotAReceipt, Some(signed)));
441 }
442 let names_ok = signed.params.iter().all(|(name, _)| ["created", "keyid", "tag"].contains(&name.as_str()));
443 let created_ok = matches!(signed.param("created"), Some(sf::Bare::Integer(n)) if *n >= 0);
444 let keyid_ok = matches!(signed.param("keyid"), Some(sf::Bare::String(_)));
445 if !(names_ok && created_ok && keyid_ok) {
446 return Err((Problem::Malformed, Some(signed)));
447 }
448 if signed.component_ids() != COMPONENTS {
449 return Err((Problem::Uncovered, Some(signed)));
450 }
451 Ok(signed)
452}
453
454fn base_of(response: &Response<'_>, signed: &Signed, lenient: bool) -> Option<String> {
457 let mut lines = Vec::new();
458 for (id, (name, _)) in signed.component_ids().iter().zip(&signed.components) {
459 let value = match name.as_str() {
460 "@status" => response.status.to_string(),
461 "@authority" => response.authority.to_string(),
462 "@path" => response.path.to_string(),
463 header => match response.field(header) {
464 Some(value) => value,
465 None if lenient => String::new(),
466 None => return None,
467 },
468 };
469 lines.push(format!("{id}: {value}"));
470 }
471 lines.push(format!("\"@signature-params\": {}", signed.serialized()));
472 Some(lines.join("\n"))
473}
474
475fn examine(response: &Response<'_>, keys: &[DirectoryKey], one_key: bool) -> Check {
476 let digest = format!("sha-256=:{}:", base64(&Sha256::digest(response.body), false));
477 let field = response.field("content-digest");
478 let mut found = Check {
479 bytes: response.body.len(),
480 status: response.status,
481 authority: response.authority.to_string(),
482 path: response.path.to_string(),
483 alg: if one_key { keys[0].alg.clone() } else { String::new() },
484 digest_matches: field.as_deref() == Some(digest.as_str()),
485 keyid: String::new(),
486 key_matches: false,
487 parts: 0,
488 signature_bytes: 0,
489 verified: false,
490 number: String::new(),
491 created: None,
492 problems: Vec::new(),
493 };
494 let signed = match read_receipt(response) {
495 Ok(signed) => signed,
496 Err((problem, signed)) => {
497 found.problems.push(problem);
498 if let Some(signed) = signed {
499 found.keyid = signed.keyid();
500 found.created = signed.created();
501 found.parts = signed.components.len();
502 found.signature_bytes = signed.signature.len();
503 found.number = number(&signed.signature);
504 }
505 return found;
506 }
507 };
508 found.keyid = signed.keyid();
509 found.created = signed.created();
510 found.parts = signed.components.len();
511 found.signature_bytes = signed.signature.len();
512 found.number = number(&signed.signature);
513
514 let base = base_of(response, &signed, false);
515 if base.is_none() {
516 found.problems.push(Problem::MissingHeader);
517 }
518 if let Some(field) = &field {
519 if !is_sha256_digest(field) {
520 found.problems.push(Problem::UnsupportedDigest);
521 } else if *field != digest {
522 found.problems.push(Problem::DigestMismatch);
523 }
524 }
525 let key = keys.iter().find(|k| k.kty == "AKP" && k.thumbprint() == found.keyid);
526 let mut try_with = None;
527 match key {
528 None => {
529 found.problems.push(Problem::UnknownKey);
530 if one_key {
531 try_with = keys.first().filter(|k| ALGORITHMS.contains(&k.alg.as_str()));
532 }
533 }
534 Some(key) => {
535 found.alg = key.alg.clone();
536 found.key_matches = true;
537 if !ALGORITHMS.contains(&key.alg.as_str()) {
538 found.problems.push(Problem::UnsupportedAlgorithm);
539 } else {
540 let created = found.created.unwrap_or(0);
541 if key.nbf.is_some_and(|nbf| created < nbf) || key.exp.is_some_and(|exp| created > exp) {
542 found.problems.push(Problem::KeyNotValidThen);
543 }
544 try_with = Some(key);
545 }
546 }
547 }
548 if let (Some(base), Some(key)) = (&base, try_with) {
549 found.verified = verify(&key.alg, &unbase64(&key.public), base.as_bytes(), &signed.signature);
550 if !found.verified && found.key_matches {
551 found.problems.push(Problem::BadSignature);
552 }
553 }
554 found.problems.sort();
555 found
556}
557
558fn is_sha256_digest(field: &str) -> bool {
560 let Some(b64) = field.strip_prefix("sha-256=:").and_then(|s| s.strip_suffix(':')) else {
561 return false;
562 };
563 b64.len() == 44 && b64.ends_with('=') && !b64.ends_with("==") && b64[..43].bytes().all(|c| c.is_ascii_alphanumeric() || c == b'+' || c == b'/')
564}
565
566pub fn signature_base(response: &Response<'_>) -> SignatureBase {
570 let Ok(signed) = signed(response) else {
571 return SignatureBase { label: String::new(), parts: 0, keyid: String::new(), text: String::new() };
572 };
573 let text = base_of(response, &signed, true).unwrap_or_default();
574 SignatureBase { label: LABEL.to_string(), parts: signed.components.len(), keyid: signed.keyid(), text }
575}
576
577pub fn thumbprint(key: &Key<'_>) -> String {
579 jwk_thumbprint(key.alg, "AKP", key.public)
580}
581
582fn jwk_thumbprint(alg: &str, kty: &str, public: &str) -> String {
583 let canonical = format!("{{\"alg\":{},\"kty\":{},\"pub\":{}}}", json::quote(alg), json::quote(kty), json::quote(public));
584 base64(&Sha256::digest(canonical.as_bytes()), true)
585}
586
587pub fn number(signature: &[u8]) -> String {
590 const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
591 let hash = Sha256::digest(signature);
592 let bits = hash[..5].iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b));
593 let out: String = (0..8).rev().map(|i| CROCKFORD[((bits >> (i * 5)) & 31) as usize] as char).collect();
594 format!("{}-{}", &out[..4], &out[4..])
595}
596
597pub fn verify(alg: &str, public: &[u8], message: &[u8], signature: &[u8]) -> bool {
599 match alg {
600 "ML-DSA-44" => verify_at::<ml_dsa::MlDsa44>(public, message, signature),
601 "ML-DSA-65" => verify_at::<ml_dsa::MlDsa65>(public, message, signature),
602 "ML-DSA-87" => verify_at::<ml_dsa::MlDsa87>(public, message, signature),
603 _ => false,
604 }
605}
606
607fn verify_at<P: ml_dsa::MlDsaParams>(public: &[u8], message: &[u8], signature: &[u8]) -> bool {
608 match (ml_dsa::EncodedVerifyingKey::<P>::try_from(public), ml_dsa::Signature::<P>::try_from(signature)) {
609 (Ok(encoded), Ok(signature)) => ml_dsa::VerifyingKey::<P>::decode(&encoded).verify_with_context(message, &[], &signature),
610 _ => false,
611 }
612}
613
614pub fn base64(bytes: &[u8], url: bool) -> String {
616 let alphabet: &[u8; 64] = if url {
617 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
618 } else {
619 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
620 };
621 let mut out = String::new();
622 for chunk in bytes.chunks(3) {
623 let n = chunk.iter().enumerate().fold(0u32, |acc, (i, &b)| acc | (u32::from(b) << (16 - 8 * i)));
624 for i in 0..=chunk.len() {
625 out.push(alphabet[((n >> (18 - 6 * i)) & 63) as usize] as char);
626 }
627 if !url {
628 out.push_str(&"=".repeat(3 - chunk.len()));
629 }
630 }
631 out
632}
633
634pub fn unbase64(text: &str) -> Vec<u8> {
636 let value = |c: u8| match c {
637 b'A'..=b'Z' => Some(c - b'A'),
638 b'a'..=b'z' => Some(c - b'a' + 26),
639 b'0'..=b'9' => Some(c - b'0' + 52),
640 b'+' | b'-' => Some(62),
641 b'/' | b'_' => Some(63),
642 _ => None,
643 };
644 let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0);
645 for v in text.bytes().filter_map(value) {
646 acc = (acc << 6) | u32::from(v);
647 bits += 6;
648 if bits >= 8 {
649 bits -= 8;
650 out.push((acc >> bits) as u8);
651 }
652 }
653 out
654}
655
656mod sf {
659 #[derive(Debug, Clone, PartialEq)]
660 pub enum Bare {
661 Integer(i64),
662 Decimal(String),
663 String(String),
664 Token(String),
665 Bytes(Vec<u8>),
666 Boolean(bool),
667 }
668
669 pub type Params = Vec<(String, Bare)>;
670
671 fn put<T>(map: &mut Vec<(String, T)>, key: String, value: T) {
673 match map.iter_mut().find(|m| m.0 == key) {
674 Some(m) => m.1 = value,
675 None => map.push((key, value)),
676 }
677 }
678
679 #[derive(Debug, Clone, PartialEq)]
680 pub enum Member {
681 Item(Bare, Params),
682 InnerList(Vec<(Bare, Params)>, Params),
683 }
684
685 struct Reader<'a> {
686 s: &'a [u8],
687 i: usize,
688 }
689
690 impl Reader<'_> {
691 fn peek(&self) -> Option<u8> {
692 self.s.get(self.i).copied()
693 }
694 fn skip(&mut self, set: &[u8]) {
695 while self.peek().is_some_and(|c| set.contains(&c)) {
696 self.i += 1;
697 }
698 }
699 fn key(&mut self) -> Option<String> {
700 let start = self.i;
701 match self.peek() {
702 Some(c) if c.is_ascii_lowercase() || c == b'*' => self.i += 1,
703 _ => return None,
704 }
705 while self.peek().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_-.*".contains(&c)) {
706 self.i += 1;
707 }
708 Some(String::from_utf8_lossy(&self.s[start..self.i]).into_owned())
709 }
710 fn params(&mut self) -> Option<Params> {
711 let mut out: Params = Vec::new();
712 while self.peek() == Some(b';') {
713 self.i += 1;
714 self.skip(b" ");
715 let key = self.key()?;
716 let value = if self.peek() == Some(b'=') {
717 self.i += 1;
718 self.bare()?
719 } else {
720 Bare::Boolean(true)
721 };
722 put(&mut out, key, value);
723 }
724 Some(out)
725 }
726 fn bare(&mut self) -> Option<Bare> {
727 match self.peek()? {
728 b'-' | b'0'..=b'9' => self.number(),
729 b'"' => self.string(),
730 b':' => self.bytes(),
731 b'?' => {
732 self.i += 1;
733 let b = match self.peek()? {
734 b'1' => true,
735 b'0' => false,
736 _ => return None,
737 };
738 self.i += 1;
739 Some(Bare::Boolean(b))
740 }
741 c if c.is_ascii_alphabetic() || c == b'*' => {
742 let start = self.i;
743 self.i += 1;
744 while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~:/".contains(&c)) {
745 self.i += 1;
746 }
747 Some(Bare::Token(String::from_utf8_lossy(&self.s[start..self.i]).into_owned()))
748 }
749 _ => None,
750 }
751 }
752 fn number(&mut self) -> Option<Bare> {
753 let start = self.i;
754 if self.peek() == Some(b'-') {
755 self.i += 1;
756 }
757 let digits = self.i;
758 while self.peek().is_some_and(|c| c.is_ascii_digit()) {
759 self.i += 1;
760 }
761 let whole = self.i - digits;
762 if whole == 0 {
763 return None;
764 }
765 if self.peek() == Some(b'.') {
766 if whole > 12 {
767 return None;
768 }
769 self.i += 1;
770 let frac = self.i;
771 while self.peek().is_some_and(|c| c.is_ascii_digit()) {
772 self.i += 1;
773 }
774 if !(1..=3).contains(&(self.i - frac)) {
775 return None;
776 }
777 return Some(Bare::Decimal(String::from_utf8_lossy(&self.s[start..self.i]).into_owned()));
778 }
779 if whole > 15 {
780 return None;
781 }
782 std::str::from_utf8(&self.s[start..self.i]).ok()?.parse().ok().map(Bare::Integer)
783 }
784 fn string(&mut self) -> Option<Bare> {
785 self.i += 1;
786 let mut out = String::new();
787 loop {
788 let c = self.peek()?;
789 self.i += 1;
790 match c {
791 b'"' => return Some(Bare::String(out)),
792 b'\\' => {
793 let e = self.peek()?;
794 if e != b'"' && e != b'\\' {
795 return None;
796 }
797 self.i += 1;
798 out.push(e as char);
799 }
800 0x20..=0x7e => out.push(c as char),
801 _ => return None,
802 }
803 }
804 }
805 fn bytes(&mut self) -> Option<Bare> {
806 self.i += 1;
807 let start = self.i;
808 while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || b"+/=".contains(&c)) {
809 self.i += 1;
810 }
811 let text = std::str::from_utf8(&self.s[start..self.i]).ok()?;
812 if self.peek() != Some(b':') {
813 return None;
814 }
815 self.i += 1;
816 Some(Bare::Bytes(super::unbase64(text)))
817 }
818 fn member(&mut self) -> Option<Member> {
819 if self.peek() == Some(b'(') {
820 self.i += 1;
821 let mut items = Vec::new();
822 loop {
823 self.skip(b" ");
824 if self.peek() == Some(b')') {
825 self.i += 1;
826 return Some(Member::InnerList(items, self.params()?));
827 }
828 let item = self.bare()?;
829 let params = self.params()?;
830 items.push((item, params));
831 if !matches!(self.peek(), Some(b' ' | b')')) {
832 return None;
833 }
834 }
835 }
836 let item = self.bare()?;
837 Some(Member::Item(item, self.params()?))
838 }
839 }
840
841 pub fn dictionary(text: &str) -> Option<Vec<(String, Member)>> {
843 let mut r = Reader { s: text.as_bytes(), i: 0 };
844 let mut out: Vec<(String, Member)> = Vec::new();
845 r.skip(b" ");
846 if r.peek().is_none() {
847 return Some(out);
848 }
849 loop {
850 let key = r.key()?;
851 let member = if r.peek() == Some(b'=') {
852 r.i += 1;
853 r.member()?
854 } else {
855 Member::Item(Bare::Boolean(true), r.params()?)
856 };
857 put(&mut out, key, member);
858 r.skip(b" \t");
859 match r.peek() {
860 None => return Some(out),
861 Some(b',') => {
862 r.i += 1;
863 r.skip(b" \t");
864 r.peek()?;
865 }
866 Some(_) => return None,
867 }
868 }
869 }
870
871 pub fn string(s: &str) -> String {
872 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
873 }
874
875 fn bare(b: &Bare) -> String {
876 match b {
877 Bare::Integer(n) => n.to_string(),
878 Bare::Decimal(d) => d.clone(),
879 Bare::String(s) => string(s),
880 Bare::Token(t) => t.clone(),
881 Bare::Bytes(v) => format!(":{}:", super::base64(v, false)),
882 Bare::Boolean(b) => format!("?{}", u8::from(*b)),
883 }
884 }
885
886 pub fn params(params: &Params) -> String {
887 params
888 .iter()
889 .map(|(k, v)| match v {
890 Bare::Boolean(true) => format!(";{k}"),
891 v => format!(";{k}={}", bare(v)),
892 })
893 .collect()
894 }
895}
896
897mod json {
899 #[derive(Debug, Clone, PartialEq)]
900 pub enum Value {
901 Null,
902 Bool(bool),
903 Number(f64),
904 String(String),
905 Array(Vec<Value>),
906 Object(Vec<(String, Value)>),
907 }
908
909 impl Value {
910 pub fn get(&self, name: &str) -> Option<&Value> {
911 match self {
912 Value::Object(members) => members.iter().rev().find(|m| m.0 == name).map(|m| &m.1),
913 _ => None,
914 }
915 }
916 pub fn as_str(&self) -> Option<&str> {
917 match self {
918 Value::String(s) => Some(s),
919 _ => None,
920 }
921 }
922 pub fn as_array(&self) -> Option<&[Value]> {
923 match self {
924 Value::Array(items) => Some(items),
925 _ => None,
926 }
927 }
928 }
929
930 pub fn quote(s: &str) -> String {
931 let mut out = String::from("\"");
932 for c in s.chars() {
933 match c {
934 '"' => out.push_str("\\\""),
935 '\\' => out.push_str("\\\\"),
936 '\u{8}' => out.push_str("\\b"),
937 '\u{c}' => out.push_str("\\f"),
938 '\n' => out.push_str("\\n"),
939 '\r' => out.push_str("\\r"),
940 '\t' => out.push_str("\\t"),
941 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
942 c => out.push(c),
943 }
944 }
945 out.push('"');
946 out
947 }
948
949 struct Reader<'a> {
950 s: &'a [u8],
951 i: usize,
952 depth: usize,
953 }
954
955 pub fn parse(text: &str) -> Option<Value> {
956 let mut r = Reader { s: text.as_bytes(), i: 0, depth: 0 };
957 let v = r.value()?;
958 r.space();
959 (r.i == r.s.len()).then_some(v)
960 }
961
962 impl Reader<'_> {
963 fn space(&mut self) {
964 while self.s.get(self.i).is_some_and(|c| b" \t\r\n".contains(c)) {
965 self.i += 1;
966 }
967 }
968 fn literal(&mut self, word: &str, v: Value) -> Option<Value> {
969 self.s[self.i..].starts_with(word.as_bytes()).then(|| {
970 self.i += word.len();
971 v
972 })
973 }
974 fn value(&mut self) -> Option<Value> {
975 self.space();
976 match *self.s.get(self.i)? {
977 b'{' => self.nested(|r| {
978 let mut members = Vec::new();
979 r.space();
980 if r.s.get(r.i) == Some(&b'}') {
981 r.i += 1;
982 return Some(Value::Object(members));
983 }
984 loop {
985 r.space();
986 let Value::String(name) = r.string()? else { return None };
987 r.space();
988 (r.s.get(r.i) == Some(&b':')).then_some(())?;
989 r.i += 1;
990 members.push((name, r.value()?));
991 r.space();
992 match r.s.get(r.i)? {
993 b',' => r.i += 1,
994 b'}' => {
995 r.i += 1;
996 return Some(Value::Object(members));
997 }
998 _ => return None,
999 }
1000 }
1001 }),
1002 b'[' => self.nested(|r| {
1003 let mut items = Vec::new();
1004 r.space();
1005 if r.s.get(r.i) == Some(&b']') {
1006 r.i += 1;
1007 return Some(Value::Array(items));
1008 }
1009 loop {
1010 items.push(r.value()?);
1011 r.space();
1012 match r.s.get(r.i)? {
1013 b',' => r.i += 1,
1014 b']' => {
1015 r.i += 1;
1016 return Some(Value::Array(items));
1017 }
1018 _ => return None,
1019 }
1020 }
1021 }),
1022 b'"' => self.string(),
1023 b't' => self.literal("true", Value::Bool(true)),
1024 b'f' => self.literal("false", Value::Bool(false)),
1025 b'n' => self.literal("null", Value::Null),
1026 _ => self.number(),
1027 }
1028 }
1029 fn nested(&mut self, inner: impl FnOnce(&mut Self) -> Option<Value>) -> Option<Value> {
1030 self.depth += 1;
1031 if self.depth > 64 {
1032 return None;
1033 }
1034 self.i += 1;
1035 let v = inner(self);
1036 self.depth -= 1;
1037 v
1038 }
1039 fn number(&mut self) -> Option<Value> {
1040 let start = self.i;
1041 while self.s.get(self.i).is_some_and(|c| c.is_ascii_digit() || b"+-.eE".contains(c)) {
1042 self.i += 1;
1043 }
1044 let text = std::str::from_utf8(&self.s[start..self.i]).ok()?;
1045 let valid = {
1046 let t = text.strip_prefix('-').unwrap_or(text);
1047 let (mantissa, exponent) = t.split_once(['e', 'E']).map_or((t, None), |(m, e)| (m, Some(e)));
1048 let (int, frac) = mantissa.split_once('.').map_or((mantissa, None), |(i, f)| (i, Some(f)));
1049 let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
1050 digits(int)
1051 && (int == "0" || !int.starts_with('0'))
1052 && frac.is_none_or(digits)
1053 && exponent.is_none_or(|e| digits(e.strip_prefix(['+', '-']).unwrap_or(e)))
1054 };
1055 valid.then(|| text.parse().ok().map(Value::Number))?
1056 }
1057 fn hex4(&mut self) -> Option<u32> {
1058 let h = std::str::from_utf8(self.s.get(self.i..self.i + 4)?).ok()?;
1059 self.i += 4;
1060 u32::from_str_radix(h, 16).ok()
1061 }
1062 fn string(&mut self) -> Option<Value> {
1063 (self.s.get(self.i) == Some(&b'"')).then_some(())?;
1064 self.i += 1;
1065 let mut out: Vec<u8> = Vec::new();
1066 loop {
1067 let c = *self.s.get(self.i)?;
1068 self.i += 1;
1069 match c {
1070 b'"' => return String::from_utf8(out).ok().map(Value::String),
1071 b'\\' => {
1072 let e = *self.s.get(self.i)?;
1073 self.i += 1;
1074 let ch = match e {
1075 b'"' => '"',
1076 b'\\' => '\\',
1077 b'/' => '/',
1078 b'b' => '\u{8}',
1079 b'f' => '\u{c}',
1080 b'n' => '\n',
1081 b'r' => '\r',
1082 b't' => '\t',
1083 b'u' => {
1084 let hi = self.hex4()?;
1085 let code = if (0xD800..0xDC00).contains(&hi) {
1086 (self.s.get(self.i..self.i + 2) == Some(b"\\u")).then_some(())?;
1087 self.i += 2;
1088 let lo = self.hex4()?;
1089 (0xDC00..0xE000).contains(&lo).then_some(())?;
1090 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
1091 } else {
1092 hi
1093 };
1094 char::from_u32(code)?
1095 }
1096 _ => return None,
1097 };
1098 let mut buf = [0u8; 4];
1099 out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1100 }
1101 0x00..=0x1f => return None,
1102 c => out.push(c),
1103 }
1104 }
1105 }
1106 }
1107}