// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! A strict tokenizer, parser and writer for Valve's KeyValues text format (VDF), as used by Steam's //! `libraryfolders.vdf` and `appmanifest_.acf`. //! //! Accepted: quoted strings with the escapes `\\`, `\"`, `\n`, `\t` and `\r`; `{` and `}`; whitespace (space, tab, //! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: input that is not //! UTF-8 as a whole, unquoted tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control //! characters (other than tab) or line breaks inside a string, NUL anywhere, empty keys, a key repeated in the same //! object (ignoring ASCII case), and anything over the caps in [`crate::limits`]. use crate::error::ParseError; use crate::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE}; use std::collections::BTreeMap; /// One token and the byte offset where it starts. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Token { pub kind: TokenKind, pub at: usize, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TokenKind { /// `{` Open, /// `}` Close, /// A quoted string, unescaped. Str(String), } /// A value: a string or a nested object. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Value { Str(String), Obj(Obj), } /// An ordered list of key/value pairs with unique keys (ignoring ASCII case). It carries its own caps: at most /// [`MAX_DEPTH`] levels of objects below it and [`MAX_ENTRIES`] pairs in total, so every `Obj` can be written and /// read back. #[derive(Debug, Clone, Default)] pub struct Obj { entries: Vec<(String, Value)>, /// ASCII-lowercased key -> position in `entries`. index: BTreeMap, /// Levels of objects inside this one (0 when it holds only strings). depth: usize, /// Pairs at every level, this one included. total: usize, } impl PartialEq for Obj { fn eq(&self, other: &Obj) -> bool { self.entries == other.entries } } impl Eq for Obj {} impl Obj { pub fn new() -> Obj { Obj::default() } /// Appends a pair. Refuses an empty key, a key or value over its cap, a key already present, an object value /// that would nest deeper than [`MAX_DEPTH`], and more than [`MAX_ENTRIES`] pairs in total. pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> { if key.is_empty() { return Err(ParseError::Missing("key")); } if key.len() > MAX_KEY { return Err(ParseError::TooLong("key")); } writable(&key, "key")?; let (depth, added) = match &value { Value::Str(s) if s.len() > MAX_VALUE => return Err(ParseError::TooLong("value")), Value::Str(s) => { writable(s, "value")?; (0, 1) } Value::Obj(o) => (o.depth + 1, o.total + 1), }; if depth > MAX_DEPTH { return Err(ParseError::TooDeep); } let total = self.total + added; if total > MAX_ENTRIES { return Err(ParseError::TooMany("entries")); } let folded = key.to_ascii_lowercase(); if self.index.contains_key(&folded) { return Err(ParseError::Duplicate("key")); } self.index.insert(folded, self.entries.len()); self.entries.push((key, value)); self.depth = self.depth.max(depth); self.total = total; Ok(()) } /// The value under `key`, ignoring ASCII case. pub fn get(&self, key: &str) -> Option<&Value> { let i = *self.index.get(&key.to_ascii_lowercase())?; self.entries.get(i).map(|(_, v)| v) } /// The pairs in file order. pub fn iter(&self) -> impl Iterator { self.entries.iter().map(|(k, v)| (k.as_str(), v)) } pub fn len(&self) -> usize { self.entries.len() } pub fn is_empty(&self) -> bool { self.entries.is_empty() } } /// A string [`write`] can carry and [`parse`] reads back: no control characters other than tab, CR and LF, and at /// most [`MAX_ESCAPES`] characters that need an escape. fn writable(s: &str, what: &'static str) -> Result<(), ParseError> { let mut escapes = 0usize; for c in s.chars() { match c { '\\' | '"' | '\n' | '\r' => escapes += 1, '\t' => {} c if c.is_ascii_control() => return Err(ParseError::BadValue(what)), _ => {} } } if escapes > MAX_ESCAPES { return Err(ParseError::TooMany("escapes")); } Ok(()) } /// Reads tokens one at a time. struct Lexer<'a> { input: &'a [u8], pos: usize, } impl<'a> Lexer<'a> { fn new(input: &'a [u8]) -> Result, ParseError> { if input.len() > MAX_FILE { return Err(ParseError::TooLarge); } if std::str::from_utf8(input).is_err() { return Err(ParseError::NotUtf8); } let pos = if input.starts_with(b"\xEF\xBB\xBF") { 3 } else { 0 }; Ok(Lexer { input, pos }) } fn peek(&self, ahead: usize) -> Option { self.input.get(self.pos + ahead).copied() } fn next_token(&mut self) -> Result, ParseError> { loop { let at = self.pos; let Some(b) = self.peek(0) else { return Ok(None) }; match b { b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1, b'/' if self.peek(1) == Some(b'/') => self.skip_comment()?, b'{' => { self.pos += 1; return Ok(Some(Token { kind: TokenKind::Open, at })); } b'}' => { self.pos += 1; return Ok(Some(Token { kind: TokenKind::Close, at })); } b'"' => { let s = self.string()?; return Ok(Some(Token { kind: TokenKind::Str(s), at })); } _ => return Err(ParseError::Syntax { at }), } } } /// Skips `//...` up to (not including) the line break. NUL is refused here too. fn skip_comment(&mut self) -> Result<(), ParseError> { while let Some(b) = self.peek(0) { match b { b'\n' => break, 0 => return Err(ParseError::Syntax { at: self.pos }), _ => self.pos += 1, } } Ok(()) } /// A quoted string starting at `self.pos`; an unterminated one is reported at its opening quote. fn string(&mut self) -> Result { let start = self.pos; self.pos += 1; let mut buf: Vec = Vec::new(); let mut escapes = 0usize; loop { let Some(b) = self.peek(0) else { return Err(ParseError::Syntax { at: start }) }; match b { b'"' => { self.pos += 1; break; } b'\\' => { let decoded = match self.peek(1) { None => return Err(ParseError::Syntax { at: start }), Some(b'\\') => b'\\', Some(b'"') => b'"', Some(b'n') => b'\n', Some(b't') => b'\t', Some(b'r') => b'\r', Some(_) => return Err(ParseError::Syntax { at: self.pos }), }; escapes += 1; if escapes > MAX_ESCAPES { return Err(ParseError::TooMany("escapes")); } buf.push(decoded); self.pos += 2; } b'\t' => { buf.push(b); self.pos += 1; } 0x00..=0x1f | 0x7f => return Err(ParseError::Syntax { at: self.pos }), _ => { buf.push(b); self.pos += 1; } } if buf.len() > MAX_VALUE { return Err(ParseError::TooLong("value")); } } String::from_utf8(buf).map_err(|_| ParseError::NotUtf8) } } /// Splits `input` into tokens. Checks size, UTF-8, escapes and string lengths; not nesting. pub fn tokenize(input: &[u8]) -> Result, ParseError> { let mut lx = Lexer::new(input)?; let mut out = Vec::new(); while let Some(t) = lx.next_token()? { out.push(t); } Ok(out) } /// Parses a whole document: a sequence of top-level pairs. pub fn parse(input: &[u8]) -> Result { let mut lx = Lexer::new(input)?; parse_obj(&mut lx, 0) } /// Reads pairs until `}` (inside an object, `depth > 0`) or the end of input (at the top, `depth == 0`). /// Recursion is bounded by `MAX_DEPTH`. fn parse_obj(lx: &mut Lexer<'_>, depth: usize) -> Result { let end = lx.input.len(); let mut obj = Obj::new(); loop { let key = match lx.next_token()? { None if depth == 0 => return Ok(obj), None => return Err(ParseError::Syntax { at: end }), Some(Token { kind: TokenKind::Close, .. }) if depth > 0 => return Ok(obj), Some(Token { kind: TokenKind::Close | TokenKind::Open, at }) => return Err(ParseError::Syntax { at }), Some(Token { kind: TokenKind::Str(k), .. }) => k, }; if key.len() > MAX_KEY { return Err(ParseError::TooLong("key")); } let value = match lx.next_token()? { None => return Err(ParseError::Syntax { at: end }), Some(Token { kind: TokenKind::Str(s), .. }) => Value::Str(s), Some(Token { kind: TokenKind::Open, .. }) => { if depth >= MAX_DEPTH { return Err(ParseError::TooDeep); } Value::Obj(parse_obj(lx, depth + 1)?) } Some(Token { kind: TokenKind::Close, at }) => return Err(ParseError::Syntax { at }), }; obj.insert(key, value)?; } } /// Writes a document in Valve's layout (tabs, one pair per line). [`parse`] of the result gives `doc` back. pub fn write(doc: &Obj) -> String { let mut out = String::new(); write_obj(doc, 0, &mut out); out } fn write_obj(o: &Obj, indent: usize, out: &mut String) { for (k, v) in &o.entries { push_tabs(out, indent); push_quoted(out, k); match v { Value::Str(s) => { out.push_str("\t\t"); push_quoted(out, s); out.push('\n'); } Value::Obj(inner) => { out.push('\n'); push_tabs(out, indent); out.push_str("{\n"); write_obj(inner, indent + 1, out); push_tabs(out, indent); out.push_str("}\n"); } } } } fn push_tabs(out: &mut String, n: usize) { out.extend(std::iter::repeat_n('\t', n)); } fn push_quoted(out: &mut String, s: &str) { out.push('"'); for c in s.chars() { match c { '\\' => out.push_str("\\\\"), '"' => out.push_str("\\\""), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), _ => out.push(c), } } out.push('"'); }