Skip to main content

ostrya_gvariant/
de.rs

1use crate::codec::{ArrayReader, TupleReader};
2use crate::ser::offset_max;
3use crate::{Error, GvDecode, Result, Type, Value};
4
5/// Maximum value nesting depth. Nested variants let value nesting exceed the
6/// static depth of the type signature, so the parser and the serializer carry
7/// their own limit.
8pub(crate) const MAX_VALUE_DEPTH: usize = 128;
9
10/// Deserialize normal-form GVariant bytes as `ty`.
11///
12/// The parser is strict: any deviation from normal form (nonzero padding,
13/// unterminated or non-UTF-8 strings, out-of-order framing offsets, trailing
14/// bytes) is an error. A successful parse therefore re-serializes to the
15/// identical bytes, which is what object checksumming relies on.
16pub fn from_bytes(ty: &Type, data: &[u8]) -> Result<Value> {
17    parse(ty, data, 0)
18}
19
20fn parse(ty: &Type, data: &[u8], depth: usize) -> Result<Value> {
21    if depth > MAX_VALUE_DEPTH {
22        return Err(Error::DepthExceeded);
23    }
24    match ty {
25        // Scalar and string leaves share the strict checks with the typed
26        // decoders; the `Value` path only wraps their results.
27        Type::Bool => Ok(Value::Bool(bool::decode(data)?)),
28        Type::Byte => Ok(Value::Byte(u8::decode(data)?)),
29        Type::I16 => Ok(Value::I16(i16::from_le_bytes(exact::<2>(data)?))),
30        Type::U16 => Ok(Value::U16(u16::from_le_bytes(exact::<2>(data)?))),
31        Type::I32 | Type::Handle => Ok(Value::I32(i32::from_le_bytes(exact::<4>(data)?))),
32        Type::U32 => Ok(Value::U32(u32::decode(data)?)),
33        Type::I64 => Ok(Value::I64(i64::from_le_bytes(exact::<8>(data)?))),
34        Type::U64 => Ok(Value::U64(u64::decode(data)?)),
35        Type::Double => Ok(Value::Double(u64::from_le_bytes(exact::<8>(data)?))),
36        Type::Str | Type::ObjectPath | Type::Signature => {
37            Ok(Value::Str(<&str>::decode(data)?.to_owned()))
38        }
39        Type::Maybe(elem) => parse_maybe(elem, data, depth),
40        Type::Array(elem) if **elem == Type::Byte => Ok(Value::Bytes(data.to_vec())),
41        Type::Array(elem) => parse_array(elem, data, depth),
42        Type::Tuple(members) => parse_struct(ty, members.iter(), data, depth),
43        Type::DictEntry(key, value) => {
44            parse_struct(ty, [&**key, &**value].into_iter(), data, depth)
45        }
46        Type::Variant => {
47            let (child, _, child_ty) = split_variant(data)?;
48            let value = parse(&child_ty, child, depth + 1)?;
49            Ok(Value::variant(child_ty, value))
50        }
51    }
52}
53
54/// Upper bound on the element count preallocated for an array before any
55/// element is validated. The count comes straight from the input length (one
56/// element per byte for fixed-size elements), so capping it keeps hostile
57/// input from forcing an allocation proportional to its own size; a genuinely
58/// large valid array still grows amortized past the cap.
59const ARRAY_PREALLOC_CAP: usize = 4096;
60
61/// Parse `m<T>`: no bytes is `Nothing`, and any other input is `Just`, whose
62/// element bytes are the whole input for a fixed-size element and the input
63/// less its trailing zero byte for a variable-size one.
64fn parse_maybe(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
65    if data.is_empty() {
66        return Ok(Value::Maybe(None));
67    }
68    let child = if elem.fixed_size().is_some() {
69        data
70    } else {
71        match data.split_last() {
72            Some((0, rest)) => rest,
73            _ => return Err(Error::NotNormal("maybe lacks its terminating zero byte")),
74        }
75    };
76    Ok(Value::Maybe(Some(Box::new(parse(elem, child, depth + 1)?))))
77}
78
79fn parse_array(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
80    let mut reader = ArrayReader::new(data, elem.alignment(), elem.fixed_size())?;
81    let mut items = Vec::with_capacity(reader.len().min(ARRAY_PREALLOC_CAP));
82    while let Some(slice) = reader.next_slice() {
83        items.push(parse(elem, slice?, depth + 1)?);
84    }
85    Ok(Value::Array(items))
86}
87
88fn parse_struct<'t>(
89    whole: &Type,
90    members: impl ExactSizeIterator<Item = &'t Type> + Clone,
91    data: &[u8],
92    depth: usize,
93) -> Result<Value> {
94    let n = members.len();
95    if n == 0 {
96        if data != [0] {
97            return Err(Error::NotNormal("empty tuple is not a single zero byte"));
98        }
99        return Ok(Value::Tuple(Vec::new()));
100    }
101    // Framing offsets cover variable-size members other than the last member.
102    let n_offsets = members
103        .clone()
104        .take(n - 1)
105        .filter(|m| m.fixed_size().is_none())
106        .count();
107    let mut reader = TupleReader::new(data, n_offsets, whole.fixed_size())?;
108    let mut items = Vec::with_capacity(n);
109    let last = n - 1;
110    for (i, member_ty) in members.enumerate() {
111        let slice = reader.field(member_ty.alignment(), member_ty.fixed_size(), i == last)?;
112        items.push(parse(member_ty, slice, depth + 1)?);
113    }
114    reader.finish()?;
115    Ok(Value::Tuple(items))
116}
117
118pub(crate) fn exact<const N: usize>(data: &[u8]) -> Result<[u8; N]> {
119    data.try_into()
120        .map_err(|_| Error::NotNormal("scalar has the wrong size"))
121}
122
123/// Split a serialized variant into its child bytes, the borrowed signature
124/// bytes, and the parsed child type. Shared by the `Value` and typed decoders.
125pub(crate) fn split_variant(data: &[u8]) -> Result<(&[u8], &[u8], Type)> {
126    let Some(sep) = data.iter().rposition(|&b| b == 0) else {
127        return Err(Error::NotNormal("variant lacks a type separator"));
128    };
129    let signature = &data[sep + 1..];
130    let sig = std::str::from_utf8(signature)
131        .map_err(|_| Error::NotNormal("variant type signature is not UTF-8"))?;
132    let ty = Type::parse(sig).map_err(|_| Error::NotNormal("variant type signature is invalid"))?;
133    Ok((&data[..sep], signature, ty))
134}
135
136pub(crate) fn check_padding(padding: &[u8]) -> Result<()> {
137    if padding.iter().any(|&b| b != 0) {
138        return Err(Error::NotNormal("padding bytes are not zero"));
139    }
140    Ok(())
141}
142
143/// The framing-offset size implied by a container's total serialized size.
144pub(crate) fn offset_size_for(len: usize) -> usize {
145    for z in [1usize, 2, 4] {
146        if len <= offset_max(z) {
147            return z;
148        }
149    }
150    8
151}
152
153pub(crate) fn read_offset(bytes: &[u8], z: usize) -> usize {
154    let mut buf = [0u8; 8];
155    buf[..z].copy_from_slice(bytes);
156    u64::from_le_bytes(buf) as usize
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::to_bytes;
163
164    fn round_trip(sig: &str, value: &Value) {
165        let ty = Type::parse(sig).unwrap();
166        let bytes = to_bytes(&ty, value).unwrap();
167        let parsed = from_bytes(&ty, &bytes).unwrap();
168        assert_eq!(&parsed, value, "value round-trip for {sig}");
169        assert_eq!(
170            to_bytes(&ty, &parsed).unwrap(),
171            bytes,
172            "byte round-trip for {sig}"
173        );
174    }
175
176    fn checksum_bytes(seed: u8) -> Value {
177        Value::Bytes((0..32).map(|i| seed.wrapping_add(i)).collect())
178    }
179
180    #[test]
181    fn round_trips_scalars_and_simple_containers() {
182        round_trip("y", &Value::Byte(7));
183        round_trip("b", &Value::Bool(true));
184        round_trip("u", &Value::U32(0xdead_beef));
185        round_trip("t", &Value::U64(0x0123_4567_89ab_cdef));
186        round_trip("s", &Value::Str("héllo wörld".into()));
187        round_trip("ay", &Value::Bytes(vec![0, 1, 2, 0, 4]));
188        round_trip(
189            "as",
190            &Value::Array(vec!["a".into(), "".into(), "ccc".into()]),
191        );
192        round_trip(
193            "aay",
194            &Value::Array(vec![Value::Bytes(vec![]), Value::Bytes(vec![1, 2])]),
195        );
196        round_trip("v", &Value::variant(Type::Str, "nested".into()));
197        round_trip(
198            "v",
199            &Value::variant(
200                Type::parse("v").unwrap(),
201                Value::variant(Type::U32, Value::U32(5)),
202            ),
203        );
204    }
205
206    /// The types outside the on-disk format, which `commit --add-metadata`
207    /// writes into a commit's metadata dict.
208    #[test]
209    fn round_trips_the_metadata_only_types() {
210        round_trip("n", &Value::I16(-5));
211        round_trip("q", &Value::U16(5));
212        round_trip("i", &Value::I32(-42));
213        round_trip("h", &Value::I32(7));
214        round_trip("x", &Value::I64(-5));
215        round_trip("d", &Value::double(1.5));
216        round_trip("o", &Value::Str("/a/b".into()));
217        round_trip("g", &Value::Str("ay".into()));
218        round_trip("ms", &Value::Maybe(None));
219        round_trip("ms", &Value::Maybe(Some(Box::new(Value::Str("x".into())))));
220        round_trip(
221            "ms",
222            &Value::Maybe(Some(Box::new(Value::Str(String::new())))),
223        );
224        round_trip("mi", &Value::Maybe(None));
225        round_trip("mi", &Value::Maybe(Some(Box::new(Value::I32(3)))));
226        round_trip(
227            "ami",
228            &Value::Array(vec![
229                Value::Maybe(Some(Box::new(Value::I32(1)))),
230                Value::Maybe(None),
231            ]),
232        );
233        round_trip(
234            "(sid)",
235            &Value::Tuple(vec![
236                Value::Str("a".into()),
237                Value::I32(5),
238                Value::double(-0.5),
239            ]),
240        );
241    }
242
243    /// A maybe of a variable-size element ends in one zero byte, which is what
244    /// tells `Just ""` from `Nothing`.
245    #[test]
246    fn maybe_framing() {
247        let ty = Type::parse("ms").unwrap();
248        assert_eq!(
249            to_bytes(&ty, &Value::Maybe(None)).unwrap(),
250            Vec::<u8>::new()
251        );
252        assert_eq!(
253            to_bytes(
254                &ty,
255                &Value::Maybe(Some(Box::new(Value::Str(String::new()))))
256            )
257            .unwrap(),
258            [0, 0]
259        );
260        assert_eq!(
261            from_bytes(&ty, &[]).unwrap(),
262            Value::Maybe(None),
263            "no bytes is Nothing"
264        );
265        assert!(from_bytes(&ty, &[1]).is_err(), "a missing terminator");
266    }
267
268    #[test]
269    fn round_trips_commit_shaped_value() {
270        // (a{sv}aya(say)sstayay) with representative metadata.
271        let metadata = Value::Array(vec![
272            Value::Tuple(vec![
273                "ostree.ref-binding".into(),
274                Value::variant(
275                    Type::parse("as").unwrap(),
276                    Value::Array(vec!["test/main".into()]),
277                ),
278            ]),
279            Value::Tuple(vec![
280                "version".into(),
281                Value::variant(Type::Str, "1.0".into()),
282            ]),
283        ]);
284        let commit = Value::Tuple(vec![
285            metadata,
286            Value::Bytes(vec![]), // root commit: no parent
287            Value::Array(vec![]), // related objects
288            "subject".into(),
289            "".into(),
290            Value::U64(1_700_000_000u64.swap_bytes()),
291            checksum_bytes(0x10),
292            checksum_bytes(0x50),
293        ]);
294        round_trip("(a{sv}aya(say)sstayay)", &commit);
295    }
296
297    #[test]
298    fn round_trips_summary_shaped_value() {
299        // (a(s(taya{sv}))a{sv}) with one ref entry and global metadata.
300        let ref_meta = Value::Array(vec![Value::Tuple(vec![
301            "ostree.commit.timestamp".into(),
302            Value::variant(Type::U64, Value::U64(1_700_000_000u64.swap_bytes())),
303        ])]);
304        let refs = Value::Array(vec![Value::Tuple(vec![
305            "test/main".into(),
306            Value::Tuple(vec![Value::U64(431), checksum_bytes(0x30), ref_meta]),
307        ])]);
308        let global = Value::Array(vec![Value::Tuple(vec![
309            "ostree.summary.mode".into(),
310            Value::variant(Type::Str, "bare".into()),
311        ])]);
312        round_trip("(a(s(taya{sv}))a{sv})", &Value::Tuple(vec![refs, global]));
313    }
314
315    #[test]
316    fn round_trips_delta_shaped_values() {
317        let meta_entry = Value::Tuple(vec![
318            Value::U32(0),
319            checksum_bytes(0x60),
320            Value::U64(4096),
321            Value::U64(8192),
322            Value::Bytes(vec![1; 33]),
323        ]);
324        round_trip("(uayttay)", &meta_entry);
325
326        let fallback = Value::Tuple(vec![
327            Value::Byte(1),
328            checksum_bytes(0x70),
329            Value::U64(100),
330            Value::U64(200),
331        ]);
332        round_trip("(yaytt)", &fallback);
333
334        let modes = Value::Array(vec![Value::Tuple(vec![
335            Value::U32(0o100644u32.swap_bytes()),
336            Value::U32(0),
337            Value::U32(0),
338        ])]);
339        let xattrs = Value::Array(vec![Value::Array(vec![])]);
340        let part = Value::Tuple(vec![
341            modes,
342            xattrs,
343            Value::Bytes(vec![0xaa; 40]),
344            Value::Bytes(vec![b'S', 0x01]),
345        ]);
346        round_trip("(a(uuu)aa(ayay)ayay)", &part);
347    }
348
349    #[test]
350    fn round_trips_offset_size_boundaries() {
351        for n in [250usize, 255, 256, 300, 70_000] {
352            let value = Value::Array(vec![Value::Bytes(vec![0x5a; n])]);
353            round_trip("aay", &value);
354        }
355    }
356
357    #[test]
358    fn array_length_does_not_drive_preallocation() {
359        // A large all-0xFF `ab` buffer names one bool element per byte. The
360        // first element fails to decode, so parsing returns an error; the
361        // untrusted element count must not drive a preallocation proportional
362        // to it before any element is validated (bound checked in
363        // `parse_array`; the ratio is enforced by inspection there).
364        let data = vec![0xffu8; 1 << 20];
365        assert_eq!(
366            from_bytes(&Type::parse("ab").unwrap(), &data),
367            Err(Error::NotNormal("boolean is not 0 or 1"))
368        );
369    }
370
371    #[test]
372    fn rejects_bad_scalars() {
373        let u = Type::parse("u").unwrap();
374        assert!(from_bytes(&u, &[1, 2, 3]).is_err());
375        assert!(from_bytes(&u, &[1, 2, 3, 4, 5]).is_err());
376        let b = Type::parse("b").unwrap();
377        assert_eq!(
378            from_bytes(&b, &[2]),
379            Err(Error::NotNormal("boolean is not 0 or 1"))
380        );
381    }
382
383    #[test]
384    fn rejects_bad_strings() {
385        let s = Type::parse("s").unwrap();
386        assert!(from_bytes(&s, b"abc").is_err()); // no terminator
387        assert!(from_bytes(&s, b"a\0b\0").is_err()); // interior NUL
388        assert!(from_bytes(&s, &[0xff, 0xfe, 0]).is_err()); // not UTF-8
389        assert!(from_bytes(&s, b"").is_err()); // empty
390    }
391
392    #[test]
393    fn rejects_nonzero_padding() {
394        // (su) with "abcd": bytes 5..8 are alignment padding for the u32.
395        let ty = Type::parse("(su)").unwrap();
396        let good = to_bytes(&ty, &Value::Tuple(vec!["abcd".into(), Value::U32(9)])).unwrap();
397        assert!(from_bytes(&ty, &good).is_ok());
398        let mut bad = good.clone();
399        bad[6] = 1;
400        assert_eq!(
401            from_bytes(&ty, &bad),
402            Err(Error::NotNormal("padding bytes are not zero"))
403        );
404    }
405
406    #[test]
407    fn rejects_malformed_array_framing() {
408        let ty = Type::parse("as").unwrap();
409        // Framing offset points past the framing area.
410        assert!(from_bytes(&ty, &[b'a', 0, 3]).is_err());
411        // Element without a NUL terminator carved out by the offsets.
412        assert!(from_bytes(&ty, &[b'a', 0, 1, 2]).is_err());
413        // Fixed-element array with a partial element.
414        let au = Type::parse("au").unwrap();
415        assert!(from_bytes(&au, &[0; 6]).is_err());
416    }
417
418    #[test]
419    fn rejects_malformed_tuples() {
420        let empty = Type::parse("()").unwrap();
421        assert!(from_bytes(&empty, &[0]).is_ok());
422        assert!(from_bytes(&empty, &[1]).is_err());
423        assert!(from_bytes(&empty, &[]).is_err());
424        assert!(from_bytes(&empty, &[0, 0]).is_err());
425        // Fixed-size tuple with trailing garbage.
426        let uuu = Type::parse("(uuu)").unwrap();
427        assert!(from_bytes(&uuu, &[0; 13]).is_err());
428        // Variable tuple whose members do not reach the framing area.
429        let su = Type::parse("(su)").unwrap();
430        assert!(from_bytes(&su, b"a\0\0\0\x05\0\0\0\0\0\x02").is_err());
431    }
432
433    #[test]
434    fn rejects_malformed_variants() {
435        let v = Type::parse("v").unwrap();
436        assert!(from_bytes(&v, b"").is_err()); // empty
437        assert!(from_bytes(&v, b"ab").is_err()); // no separator
438        assert!(from_bytes(&v, b"a\0d").is_err()); // unsupported child type
439        assert!(from_bytes(&v, b"\0").is_err()); // empty signature
440    }
441
442    #[test]
443    fn rejects_variant_depth_bomb() {
444        // 129 nested variants, built by hand since the serializer rejects
445        // values this deep: innermost byte, then one signature per wrapper.
446        let ty = Type::parse("v").unwrap();
447        let mut bytes = vec![1u8, 0, b'y'];
448        for _ in 0..128 {
449            bytes.push(0);
450            bytes.push(b'v');
451        }
452        assert_eq!(from_bytes(&ty, &bytes), Err(Error::DepthExceeded));
453
454        // 128 nested variants sit exactly at the limit and round-trip; one
455        // more wrapper fails identically on the encode path.
456        let mut value = Value::variant(Type::Byte, Value::Byte(1));
457        for _ in 0..127 {
458            value = Value::variant(Type::Variant, value);
459        }
460        let ok = to_bytes(&ty, &value).unwrap();
461        assert_eq!(from_bytes(&ty, &ok).unwrap(), value);
462        let bomb = Value::variant(Type::Variant, value);
463        assert_eq!(to_bytes(&ty, &bomb), Err(Error::DepthExceeded));
464    }
465}