Skip to main content

webbluetooth_linux/dbus/
codec.rs

1//! Marshalling values to and from the D-Bus wire format.
2//!
3//! Two rules account for nearly all of the difficulty:
4//!
5//! 1. **Every value is padded to its natural alignment**, and the offset that
6//!    alignment is measured against is the start of the *message*, not the
7//!    start of the value being written. An encoder therefore has to carry a
8//!    position, not just a buffer. (The body may be encoded from zero, because
9//!    it always begins on an 8-byte boundary and every alignment divides 8.)
10//!
11//! 2. **The bytes carry no type tags.** A `u32` on the wire is four bytes and
12//!    nothing else; only the signature says what it is. Decoding is therefore
13//!    signature-directed, and a signature that disagrees with the bytes yields
14//!    silent nonsense rather than an error — which is why [`Decoder`] bounds-
15//!    checks every read instead of trusting lengths from the peer.
16//!
17//! The exception is `v`, a variant, which carries its own signature inline.
18//! BlueZ wraps every property in one, so most real payloads are variants all
19//! the way down.
20
21use super::value::{alignment, complete_types, type_length, Value};
22use std::fmt;
23
24/// A malformed or unexpected message.
25#[derive(Debug, Clone, PartialEq)]
26pub enum CodecError {
27    /// The peer's length field ran past the end of the buffer.
28    Truncated { wanted: usize, available: usize },
29    /// A type code that is not in the specification.
30    BadTypeCode(char),
31    /// A signature that does not parse.
32    BadSignature(String),
33    /// A string field that was not valid UTF-8.
34    BadUtf8,
35    /// An array claimed a length that is not a whole number of elements.
36    BadArrayLength(usize),
37}
38
39impl fmt::Display for CodecError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            Self::Truncated { wanted, available } => {
43                write!(
44                    f,
45                    "message truncated: wanted {wanted} bytes, {available} available"
46                )
47            }
48            Self::BadTypeCode(c) => write!(f, "unknown D-Bus type code {c:?}"),
49            Self::BadSignature(s) => write!(f, "malformed signature {s:?}"),
50            Self::BadUtf8 => f.write_str("string field was not valid UTF-8"),
51            Self::BadArrayLength(n) => {
52                write!(f, "array length {n} is not a whole number of elements")
53            }
54        }
55    }
56}
57
58impl std::error::Error for CodecError {}
59
60type Result<T> = std::result::Result<T, CodecError>;
61
62// ── Encoding ────────────────────────────────────────────────────────────────
63
64/// Writes values in little-endian, tracking position so padding is correct.
65#[derive(Debug, Default)]
66pub struct Encoder {
67    buf: Vec<u8>,
68}
69
70impl Encoder {
71    pub fn new() -> Self {
72        Self { buf: Vec::new() }
73    }
74
75    /// Start encoding at a non-zero offset, for a buffer that continues one
76    /// that has already been written.
77    pub fn at_offset(offset: usize) -> Self {
78        Self {
79            buf: vec![0; offset],
80        }
81    }
82
83    pub fn len(&self) -> usize {
84        self.buf.len()
85    }
86    pub fn is_empty(&self) -> bool {
87        self.buf.is_empty()
88    }
89
90    /// The bytes written, discarding `skip` leading bytes of offset padding.
91    pub fn finish_from(self, skip: usize) -> Vec<u8> {
92        self.buf[skip.min(self.buf.len())..].to_vec()
93    }
94
95    pub fn finish(self) -> Vec<u8> {
96        self.buf
97    }
98
99    /// Pad with zeroes until the position is a multiple of `n`.
100    pub fn align(&mut self, n: usize) {
101        while !self.buf.len().is_multiple_of(n) {
102            self.buf.push(0);
103        }
104    }
105
106    pub fn byte(&mut self, v: u8) {
107        self.buf.push(v)
108    }
109
110    pub fn u16(&mut self, v: u16) {
111        self.align(2);
112        self.buf.extend_from_slice(&v.to_le_bytes());
113    }
114
115    pub fn u32(&mut self, v: u32) {
116        self.align(4);
117        self.buf.extend_from_slice(&v.to_le_bytes());
118    }
119
120    pub fn u64(&mut self, v: u64) {
121        self.align(8);
122        self.buf.extend_from_slice(&v.to_le_bytes());
123    }
124
125    /// `s` / `o`: 32-bit length, bytes, then a NUL that is not counted.
126    pub fn string(&mut self, s: &str) {
127        self.u32(s.len() as u32);
128        self.buf.extend_from_slice(s.as_bytes());
129        self.buf.push(0);
130    }
131
132    /// `g`: 8-bit length, bytes, NUL. Signatures are short by definition.
133    pub fn signature(&mut self, s: &str) {
134        self.buf.push(s.len() as u8);
135        self.buf.extend_from_slice(s.as_bytes());
136        self.buf.push(0);
137    }
138
139    /// Write one value.
140    pub fn value(&mut self, v: &Value) {
141        match v {
142            Value::Byte(b) => self.byte(*b),
143            Value::Bool(b) => self.u32(u32::from(*b)),
144            Value::Int16(n) => self.u16(*n as u16),
145            Value::Uint16(n) => self.u16(*n),
146            Value::Int32(n) => self.u32(*n as u32),
147            Value::Uint32(n) => self.u32(*n),
148            Value::UnixFd(n) => self.u32(*n),
149            Value::Int64(n) => self.u64(*n as u64),
150            Value::Uint64(n) => self.u64(*n),
151            Value::Double(d) => self.u64(d.to_bits()),
152            Value::Str(s) | Value::ObjectPath(s) => self.string(s),
153            Value::Signature(s) => self.signature(s),
154
155            Value::Array { element, items } => {
156                // The length counts the element bytes only, so it cannot be
157                // written until the padding that follows it is known. Reserve
158                // four bytes, write the elements, then backfill.
159                self.align(4);
160                let length_at = self.buf.len();
161                self.buf.extend_from_slice(&0u32.to_le_bytes());
162                let elem_align = element.as_bytes().first().map_or(1, |c| alignment(*c));
163                self.align(elem_align);
164                let body_start = self.buf.len();
165                for item in items {
166                    self.value(item);
167                }
168                let length = (self.buf.len() - body_start) as u32;
169                self.buf[length_at..length_at + 4].copy_from_slice(&length.to_le_bytes());
170            }
171
172            Value::Struct(fields) => {
173                self.align(8);
174                for f in fields {
175                    self.value(f);
176                }
177            }
178
179            Value::DictEntry(k, val) => {
180                self.align(8);
181                self.value(k);
182                self.value(val);
183            }
184
185            Value::Variant(inner) => {
186                self.signature(&inner.signature());
187                self.value(inner);
188            }
189        }
190    }
191
192    /// Write a sequence of values, as a message body.
193    pub fn body(&mut self, values: &[Value]) {
194        for v in values {
195            self.value(v);
196        }
197    }
198}
199
200// ── Decoding ────────────────────────────────────────────────────────────────
201
202/// Reads values, signature-directed, bounds-checking every access.
203pub struct Decoder<'a> {
204    buf: &'a [u8],
205    pos: usize,
206    little_endian: bool,
207}
208
209impl<'a> Decoder<'a> {
210    /// Decode a buffer whose position 0 is the alignment origin.
211    pub fn new(buf: &'a [u8], little_endian: bool) -> Self {
212        Self {
213            buf,
214            pos: 0,
215            little_endian,
216        }
217    }
218
219    /// Decode starting at `pos`, keeping the same alignment origin — needed for
220    /// a header array, whose padding is measured from the start of the message.
221    pub fn at(buf: &'a [u8], pos: usize, little_endian: bool) -> Self {
222        Self {
223            buf,
224            pos,
225            little_endian,
226        }
227    }
228
229    pub fn position(&self) -> usize {
230        self.pos
231    }
232    pub fn remaining(&self) -> usize {
233        self.buf.len().saturating_sub(self.pos)
234    }
235
236    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
237        if self.pos + n > self.buf.len() {
238            return Err(CodecError::Truncated {
239                wanted: n,
240                available: self.remaining(),
241            });
242        }
243        let out = &self.buf[self.pos..self.pos + n];
244        self.pos += n;
245        Ok(out)
246    }
247
248    pub fn align(&mut self, n: usize) -> Result<()> {
249        while !self.pos.is_multiple_of(n) {
250            // Padding must exist; running off the end here means a bad length.
251            if self.pos >= self.buf.len() {
252                return Err(CodecError::Truncated {
253                    wanted: 1,
254                    available: 0,
255                });
256            }
257            self.pos += 1;
258        }
259        Ok(())
260    }
261
262    pub fn byte(&mut self) -> Result<u8> {
263        Ok(self.take(1)?[0])
264    }
265
266    pub fn u16(&mut self) -> Result<u16> {
267        self.align(2)?;
268        let b = self.take(2)?;
269        let a = [b[0], b[1]];
270        Ok(if self.little_endian {
271            u16::from_le_bytes(a)
272        } else {
273            u16::from_be_bytes(a)
274        })
275    }
276
277    pub fn u32(&mut self) -> Result<u32> {
278        self.align(4)?;
279        let b = self.take(4)?;
280        let a = [b[0], b[1], b[2], b[3]];
281        Ok(if self.little_endian {
282            u32::from_le_bytes(a)
283        } else {
284            u32::from_be_bytes(a)
285        })
286    }
287
288    pub fn u64(&mut self) -> Result<u64> {
289        self.align(8)?;
290        let b = self.take(8)?;
291        let a = [b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]];
292        Ok(if self.little_endian {
293            u64::from_le_bytes(a)
294        } else {
295            u64::from_be_bytes(a)
296        })
297    }
298
299    pub fn string(&mut self) -> Result<String> {
300        let len = self.u32()? as usize;
301        let bytes = self.take(len)?;
302        let s = std::str::from_utf8(bytes)
303            .map_err(|_| CodecError::BadUtf8)?
304            .to_owned();
305        self.take(1)?; // trailing NUL
306        Ok(s)
307    }
308
309    pub fn signature(&mut self) -> Result<String> {
310        let len = self.byte()? as usize;
311        let bytes = self.take(len)?;
312        let s = std::str::from_utf8(bytes)
313            .map_err(|_| CodecError::BadUtf8)?
314            .to_owned();
315        self.take(1)?;
316        Ok(s)
317    }
318
319    /// Read one value of the type named by `signature`.
320    pub fn value(&mut self, signature: &str) -> Result<Value> {
321        let code = *signature
322            .as_bytes()
323            .first()
324            .ok_or_else(|| CodecError::BadSignature(signature.into()))?;
325        Ok(match code {
326            b'y' => Value::Byte(self.byte()?),
327            b'b' => Value::Bool(self.u32()? != 0),
328            b'n' => Value::Int16(self.u16()? as i16),
329            b'q' => Value::Uint16(self.u16()?),
330            b'i' => Value::Int32(self.u32()? as i32),
331            b'u' => Value::Uint32(self.u32()?),
332            b'h' => Value::UnixFd(self.u32()?),
333            b'x' => Value::Int64(self.u64()? as i64),
334            b't' => Value::Uint64(self.u64()?),
335            b'd' => Value::Double(f64::from_bits(self.u64()?)),
336            b's' => Value::Str(self.string()?),
337            b'o' => Value::ObjectPath(self.string()?),
338            b'g' => Value::Signature(self.signature()?),
339
340            b'a' => {
341                let element = signature[1..].to_string();
342                if element.is_empty() {
343                    return Err(CodecError::BadSignature(signature.into()));
344                }
345                let byte_len = self.u32()? as usize;
346                let elem_align = element.as_bytes().first().map_or(1, |c| alignment(*c));
347                self.align(elem_align)?;
348                let end = self.pos + byte_len;
349                if end > self.buf.len() {
350                    return Err(CodecError::Truncated {
351                        wanted: byte_len,
352                        available: self.remaining(),
353                    });
354                }
355                let mut items = Vec::new();
356                while self.pos < end {
357                    items.push(self.value(&element)?);
358                }
359                // A decode that overshot means the signature and bytes disagree.
360                if self.pos != end {
361                    return Err(CodecError::BadArrayLength(byte_len));
362                }
363                Value::Array { element, items }
364            }
365
366            b'(' => {
367                self.align(8)?;
368                let inner = signature
369                    .get(1..signature.len().saturating_sub(1))
370                    .ok_or_else(|| CodecError::BadSignature(signature.into()))?;
371                let mut fields = Vec::new();
372                for t in complete_types(inner) {
373                    fields.push(self.value(&t)?);
374                }
375                Value::Struct(fields)
376            }
377
378            b'{' => {
379                self.align(8)?;
380                let inner = signature
381                    .get(1..signature.len().saturating_sub(1))
382                    .ok_or_else(|| CodecError::BadSignature(signature.into()))?;
383                let parts = complete_types(inner);
384                let (Some(kt), Some(vt)) = (parts.first(), parts.get(1)) else {
385                    return Err(CodecError::BadSignature(signature.into()));
386                };
387                let k = self.value(kt)?;
388                let v = self.value(vt)?;
389                Value::DictEntry(Box::new(k), Box::new(v))
390            }
391
392            b'v' => {
393                let inner_sig = self.signature()?;
394                if type_length(inner_sig.as_bytes()) != Some(inner_sig.len()) {
395                    return Err(CodecError::BadSignature(inner_sig));
396                }
397                Value::Variant(Box::new(self.value(&inner_sig)?))
398            }
399
400            other => return Err(CodecError::BadTypeCode(other as char)),
401        })
402    }
403
404    /// Read a whole message body described by `signature`.
405    pub fn body(&mut self, signature: &str) -> Result<Vec<Value>> {
406        complete_types(signature)
407            .iter()
408            .map(|t| self.value(t))
409            .collect()
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    /// Encode then decode, and require the value to survive unchanged.
418    fn round_trip(v: Value) {
419        let sig = v.signature();
420        let mut enc = Encoder::new();
421        enc.value(&v);
422        let bytes = enc.finish();
423        let mut dec = Decoder::new(&bytes, true);
424        let got = dec.value(&sig).expect("decode failed");
425        assert_eq!(got, v, "round trip changed the value (signature {sig})");
426        assert_eq!(
427            dec.remaining(),
428            0,
429            "decoder left {} bytes unread",
430            dec.remaining()
431        );
432    }
433
434    #[test]
435    fn scalars_round_trip() {
436        round_trip(Value::Byte(0xAB));
437        round_trip(Value::Bool(true));
438        round_trip(Value::Bool(false));
439        round_trip(Value::Int16(-2));
440        round_trip(Value::Uint16(65535));
441        round_trip(Value::Int32(-70000));
442        round_trip(Value::Uint32(4_000_000_000));
443        round_trip(Value::Int64(-1));
444        round_trip(Value::Uint64(u64::MAX));
445        round_trip(Value::Double(-0.5));
446    }
447
448    #[test]
449    fn strings_round_trip_including_empty_and_utf8() {
450        round_trip(Value::Str(String::new()));
451        round_trip(Value::Str("org.bluez".into()));
452        round_trip(Value::Str("naïve ☕".into()));
453        round_trip(Value::ObjectPath("/org/bluez/hci0".into()));
454        round_trip(Value::Signature("a{sv}".into()));
455    }
456
457    #[test]
458    fn containers_round_trip() {
459        round_trip(Value::bytes(&[]));
460        round_trip(Value::bytes(&[1, 2, 3]));
461        round_trip(Value::string_array(["a".into(), "bb".into()]));
462        round_trip(Value::Struct(vec![
463            Value::Uint32(1),
464            Value::Str("x".into()),
465        ]));
466        round_trip(Value::Variant(Box::new(Value::Str("v".into()))));
467        round_trip(Value::dict([
468            ("Powered".into(), Value::Bool(true)),
469            ("Address".into(), Value::Str("AA:BB:CC:DD:EE:FF".into())),
470        ]));
471    }
472
473    #[test]
474    fn the_get_managed_objects_shape_round_trips() {
475        // `a{oa{sa{sv}}}` is the reply this crate leans on hardest.
476        let managed = Value::Array {
477            element: "{oa{sa{sv}}}".into(),
478            items: vec![Value::DictEntry(
479                Box::new(Value::ObjectPath("/org/bluez/hci0/dev_AA_BB".into())),
480                Box::new(Value::Array {
481                    element: "{sa{sv}}".into(),
482                    items: vec![Value::DictEntry(
483                        Box::new(Value::Str("org.bluez.Device1".into())),
484                        Box::new(Value::dict([
485                            ("Name".into(), Value::Str("Pixel".into())),
486                            ("RSSI".into(), Value::Int16(-42)),
487                            (
488                                "UUIDs".into(),
489                                Value::string_array(
490                                    ["0000180f-0000-1000-8000-00805f9b34fb".into()],
491                                ),
492                            ),
493                        ])),
494                    )],
495                }),
496            )],
497        };
498        round_trip(managed.clone());
499
500        // …and navigating it gives the values back.
501        let by_path = managed.as_map();
502        let ifaces = by_path.get("/org/bluez/hci0/dev_AA_BB").unwrap().as_map();
503        let props = ifaces.get("org.bluez.Device1").unwrap();
504        assert_eq!(props.get("Name").unwrap().as_str(), Some("Pixel"));
505        assert_eq!(props.get("RSSI").unwrap().as_i64(), Some(-42));
506    }
507
508    #[test]
509    fn alignment_padding_is_inserted_between_values() {
510        // byte then uint32: the u32 must start at offset 4, not 1.
511        let mut enc = Encoder::new();
512        enc.body(&[Value::Byte(1), Value::Uint32(2)]);
513        let bytes = enc.finish();
514        assert_eq!(bytes.len(), 8, "expected 1 byte + 3 pad + 4");
515        assert_eq!(&bytes[1..4], &[0, 0, 0], "padding must be zero");
516
517        let mut dec = Decoder::new(&bytes, true);
518        assert_eq!(
519            dec.body("yu").unwrap(),
520            vec![Value::Byte(1), Value::Uint32(2)]
521        );
522    }
523
524    #[test]
525    fn struct_elements_are_eight_aligned() {
526        // A byte then a struct: the struct starts at 8.
527        let mut enc = Encoder::new();
528        enc.body(&[Value::Byte(1), Value::Struct(vec![Value::Byte(2)])]);
529        let bytes = enc.finish();
530        assert_eq!(bytes.len(), 9);
531        assert_eq!(bytes[8], 2);
532    }
533
534    #[test]
535    fn empty_arrays_keep_their_element_type() {
536        let empty = Value::Array {
537            element: "{sv}".into(),
538            items: vec![],
539        };
540        round_trip(empty.clone());
541        assert_eq!(empty.signature(), "a{sv}");
542    }
543
544    #[test]
545    fn big_endian_messages_decode() {
546        // The bus may speak either byte order; only the decoder must cope.
547        let bytes = [0x00, 0x00, 0x00, 0x2A];
548        let mut dec = Decoder::new(&bytes, false);
549        assert_eq!(dec.value("u").unwrap(), Value::Uint32(42));
550    }
551
552    // ── Hostile input ───────────────────────────────────────────────────────
553    // Lengths come from the peer, so every one of these is reachable from the
554    // network and must be an error rather than a panic.
555
556    #[test]
557    fn a_truncated_buffer_errors_rather_than_panicking() {
558        let mut dec = Decoder::new(&[1, 2], true);
559        assert!(matches!(dec.value("u"), Err(CodecError::Truncated { .. })));
560    }
561
562    #[test]
563    fn an_oversized_string_length_errors() {
564        // Claims 0xFFFFFFFF bytes of string in a 4-byte buffer.
565        let bytes = [0xFF, 0xFF, 0xFF, 0xFF];
566        let mut dec = Decoder::new(&bytes, true);
567        assert!(matches!(dec.value("s"), Err(CodecError::Truncated { .. })));
568    }
569
570    #[test]
571    fn an_oversized_array_length_errors() {
572        let bytes = [0xFF, 0xFF, 0xFF, 0x7F];
573        let mut dec = Decoder::new(&bytes, true);
574        assert!(matches!(dec.value("ay"), Err(CodecError::Truncated { .. })));
575    }
576
577    #[test]
578    fn a_bad_type_code_errors() {
579        let mut dec = Decoder::new(&[0], true);
580        assert!(matches!(dec.value("Z"), Err(CodecError::BadTypeCode('Z'))));
581        assert!(matches!(
582            Decoder::new(&[0], true).value(""),
583            Err(CodecError::BadSignature(_))
584        ));
585    }
586
587    #[test]
588    fn a_variant_carrying_a_bad_signature_errors() {
589        let mut enc = Encoder::new();
590        enc.signature("a"); // "a" alone is not a complete type
591        let bytes = enc.finish();
592        let mut dec = Decoder::new(&bytes, true);
593        assert!(matches!(dec.value("v"), Err(CodecError::BadSignature(_))));
594    }
595
596    #[test]
597    fn invalid_utf8_in_a_string_errors() {
598        let mut bytes = vec![2, 0, 0, 0, 0xFF, 0xFE, 0];
599        bytes.truncate(7);
600        let mut dec = Decoder::new(&bytes, true);
601        assert!(matches!(dec.value("s"), Err(CodecError::BadUtf8)));
602    }
603}