Skip to main content

webbluetooth_linux/dbus/
message.rs

1//! D-Bus message framing.
2//!
3//! ```text
4//!   byte   endianness ('l' little, 'B' big)
5//!   byte   message type
6//!   byte   flags
7//!   byte   protocol version (1)
8//!   u32    body length
9//!   u32    serial
10//!   a(yv)  header fields — path, interface, member, signature, …
11//!   ---- padded to 8 ----
12//!   body
13//! ```
14//!
15//! The header array's padding is measured from the start of the *message*, so
16//! it is encoded into the same buffer as the fixed part rather than separately.
17//! The body may be encoded on its own, because it always begins at a multiple
18//! of 8 and every D-Bus alignment divides 8.
19
20use super::codec::{CodecError, Decoder, Encoder};
21use super::value::Value;
22
23/// Header field codes.
24mod field {
25    pub const PATH: u8 = 1;
26    pub const INTERFACE: u8 = 2;
27    pub const MEMBER: u8 = 3;
28    pub const ERROR_NAME: u8 = 4;
29    pub const REPLY_SERIAL: u8 = 5;
30    pub const DESTINATION: u8 = 6;
31    pub const SENDER: u8 = 7;
32    pub const SIGNATURE: u8 = 8;
33    pub const UNIX_FDS: u8 = 9;
34}
35
36/// `NO_REPLY_EXPECTED`.
37pub const FLAG_NO_REPLY_EXPECTED: u8 = 0x01;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[repr(u8)]
41/// The four kinds of D-Bus message, as the header's type byte encodes them.
42pub enum MessageType {
43    MethodCall = 1,
44    MethodReturn = 2,
45    Error = 3,
46    Signal = 4,
47}
48
49impl MessageType {
50    fn from_u8(v: u8) -> Option<Self> {
51        Some(match v {
52            1 => Self::MethodCall,
53            2 => Self::MethodReturn,
54            3 => Self::Error,
55            4 => Self::Signal,
56            _ => return None,
57        })
58    }
59}
60
61/// One D-Bus message.
62#[derive(Debug, Clone)]
63pub struct Message {
64    pub message_type: MessageType,
65    pub flags: u8,
66    pub serial: u32,
67    pub path: Option<String>,
68    pub interface: Option<String>,
69    pub member: Option<String>,
70    pub error_name: Option<String>,
71    pub reply_serial: Option<u32>,
72    pub destination: Option<String>,
73    pub sender: Option<String>,
74    pub body: Vec<Value>,
75    /// How many file descriptors travelled beside this message.
76    ///
77    /// A `h` value in the body is an index into them, not a descriptor, and
78    /// they arrive out of band — see [`super::fds`]. Declared here so the
79    /// transport knows how many to claim for this message and no more.
80    pub unix_fds: u32,
81}
82
83impl Message {
84    fn empty(message_type: MessageType) -> Self {
85        Self {
86            message_type,
87            flags: 0,
88            serial: 0,
89            path: None,
90            interface: None,
91            member: None,
92            error_name: None,
93            reply_serial: None,
94            destination: None,
95            sender: None,
96            body: Vec::new(),
97            unix_fds: 0,
98        }
99    }
100
101    /// A method call.
102    pub fn call(destination: &str, path: &str, interface: &str, member: &str) -> Self {
103        let mut m = Self::empty(MessageType::MethodCall);
104        m.destination = Some(destination.into());
105        m.path = Some(path.into());
106        m.interface = Some(interface.into());
107        m.member = Some(member.into());
108        m
109    }
110
111    /// A signal.
112    pub fn signal(path: &str, interface: &str, member: &str) -> Self {
113        let mut m = Self::empty(MessageType::Signal);
114        m.path = Some(path.into());
115        m.interface = Some(interface.into());
116        m.member = Some(member.into());
117        m
118    }
119
120    /// A successful reply to `call`.
121    pub fn reply_to(call: &Message) -> Self {
122        let mut m = Self::empty(MessageType::MethodReturn);
123        m.reply_serial = Some(call.serial);
124        m.destination = call.sender.clone();
125        m
126    }
127
128    /// An error reply to `call`.
129    pub fn error_to(call: &Message, name: &str, text: &str) -> Self {
130        let mut m = Self::empty(MessageType::Error);
131        m.reply_serial = Some(call.serial);
132        m.destination = call.sender.clone();
133        m.error_name = Some(name.into());
134        m.body = vec![Value::Str(text.into())];
135        m
136    }
137
138    /// Attach a body.
139    pub fn with_body(mut self, body: Vec<Value>) -> Self {
140        self.body = body;
141        self
142    }
143
144    /// The body's signature, derived from the values themselves.
145    pub fn signature(&self) -> String {
146        self.body.iter().map(Value::signature).collect()
147    }
148
149    /// `body[i]`, if present.
150    pub fn arg(&self, i: usize) -> Option<&Value> {
151        self.body.get(i)
152    }
153
154    /// The text of an error reply.
155    pub fn error_text(&self) -> Option<String> {
156        self.body
157            .first()
158            .and_then(|v| v.as_str())
159            .map(str::to_owned)
160    }
161
162    /// Encode to the wire.
163    pub fn serialize(&self, serial: u32) -> Vec<u8> {
164        let mut body_encoder = Encoder::new();
165        body_encoder.body(&self.body);
166        let body = body_encoder.finish();
167
168        let mut fields: Vec<Value> = Vec::new();
169        let mut push = |code: u8, v: Value| {
170            fields.push(Value::Struct(vec![
171                Value::Byte(code),
172                Value::Variant(Box::new(v)),
173            ]));
174        };
175        if let Some(p) = &self.path {
176            push(field::PATH, Value::ObjectPath(p.clone()));
177        }
178        if let Some(i) = &self.interface {
179            push(field::INTERFACE, Value::Str(i.clone()));
180        }
181        if let Some(m) = &self.member {
182            push(field::MEMBER, Value::Str(m.clone()));
183        }
184        if let Some(e) = &self.error_name {
185            push(field::ERROR_NAME, Value::Str(e.clone()));
186        }
187        if let Some(r) = self.reply_serial {
188            push(field::REPLY_SERIAL, Value::Uint32(r));
189        }
190        if let Some(d) = &self.destination {
191            push(field::DESTINATION, Value::Str(d.clone()));
192        }
193        if let Some(s) = &self.sender {
194            push(field::SENDER, Value::Str(s.clone()));
195        }
196        if !self.body.is_empty() {
197            push(field::SIGNATURE, Value::Signature(self.signature()));
198        }
199
200        let mut encoder = Encoder::new();
201        encoder.byte(b'l');
202        encoder.byte(self.message_type as u8);
203        encoder.byte(self.flags);
204        encoder.byte(1);
205        encoder.u32(body.len() as u32);
206        encoder.u32(serial);
207        encoder.value(&Value::Array {
208            element: "(yv)".into(),
209            items: fields,
210        });
211        encoder.align(8);
212
213        let mut out = encoder.finish();
214        out.extend_from_slice(&body);
215        out
216    }
217
218    /// How long a message starting at `buf` is, or `None` if the fixed header
219    /// has not arrived yet. Used to know how much more to read.
220    pub fn framed_length(buf: &[u8]) -> Option<usize> {
221        if buf.len() < 16 {
222            return None;
223        }
224        let little_endian = buf[0] == b'l';
225        let read_u32 = |at: usize| {
226            let a = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]];
227            (if little_endian {
228                u32::from_le_bytes(a)
229            } else {
230                u32::from_be_bytes(a)
231            }) as usize
232        };
233        let body_len = read_u32(4);
234        let fields_len = read_u32(12);
235        // 12 fixed + 4 array length + fields, padded to 8, then body.
236        let header_end = 16 + fields_len;
237        let padded = header_end.div_ceil(8) * 8;
238        Some(padded + body_len)
239    }
240
241    /// Decode one complete message.
242    pub fn parse(buf: &[u8]) -> Result<Self, CodecError> {
243        if buf.len() < 16 {
244            return Err(CodecError::Truncated {
245                wanted: 16,
246                available: buf.len(),
247            });
248        }
249        let little_endian = buf[0] == b'l';
250        let message_type =
251            MessageType::from_u8(buf[1]).ok_or(CodecError::BadTypeCode(buf[1] as char))?;
252        let flags = buf[2];
253
254        let mut decoder = Decoder::at(buf, 4, little_endian);
255        let body_len = decoder.u32()? as usize;
256        let serial = decoder.u32()?;
257        let fields = decoder.value("a(yv)")?;
258
259        let mut message = Self::empty(message_type);
260        message.flags = flags;
261        message.serial = serial;
262        let mut signature = String::new();
263
264        for entry in fields.as_array().unwrap_or(&[]) {
265            let Some(parts) = entry.as_array() else {
266                continue;
267            };
268            let (Some(code), Some(v)) = (parts.first().and_then(Value::as_u64), parts.get(1))
269            else {
270                continue;
271            };
272            match code as u8 {
273                field::PATH => message.path = v.as_str().map(str::to_owned),
274                field::INTERFACE => message.interface = v.as_str().map(str::to_owned),
275                field::MEMBER => message.member = v.as_str().map(str::to_owned),
276                field::ERROR_NAME => message.error_name = v.as_str().map(str::to_owned),
277                field::REPLY_SERIAL => message.reply_serial = v.as_u64().map(|n| n as u32),
278                field::DESTINATION => message.destination = v.as_str().map(str::to_owned),
279                field::SENDER => message.sender = v.as_str().map(str::to_owned),
280                field::SIGNATURE => signature = v.as_str().unwrap_or_default().to_owned(),
281                field::UNIX_FDS => message.unix_fds = v.as_u64().unwrap_or(0) as u32,
282                _ => {}
283            }
284        }
285
286        // The body starts at the next multiple of 8 after the header array.
287        let body_start = decoder.position().div_ceil(8) * 8;
288        if !signature.is_empty() {
289            let end = body_start + body_len;
290            if end > buf.len() {
291                return Err(CodecError::Truncated {
292                    wanted: body_len,
293                    available: buf.len().saturating_sub(body_start),
294                });
295            }
296            let mut body_decoder = Decoder::new(&buf[body_start..end], little_endian);
297            message.body = body_decoder.body(&signature)?;
298        }
299        Ok(message)
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn a_method_call_round_trips() {
309        let call = Message::call(
310            "org.bluez",
311            "/org/bluez/hci0",
312            "org.freedesktop.DBus.Properties",
313            "Get",
314        )
315        .with_body(vec![
316            Value::Str("org.bluez.Adapter1".into()),
317            Value::Str("Powered".into()),
318        ]);
319
320        let bytes = call.serialize(7);
321        assert_eq!(
322            Message::framed_length(&bytes),
323            Some(bytes.len()),
324            "framing disagrees"
325        );
326
327        let back = Message::parse(&bytes).unwrap();
328        assert_eq!(back.message_type, MessageType::MethodCall);
329        assert_eq!(back.serial, 7);
330        assert_eq!(back.destination.as_deref(), Some("org.bluez"));
331        assert_eq!(back.path.as_deref(), Some("/org/bluez/hci0"));
332        assert_eq!(
333            back.interface.as_deref(),
334            Some("org.freedesktop.DBus.Properties")
335        );
336        assert_eq!(back.member.as_deref(), Some("Get"));
337        assert_eq!(back.body.len(), 2);
338        assert_eq!(back.arg(1).unwrap().as_str(), Some("Powered"));
339    }
340
341    #[test]
342    fn a_body_less_message_round_trips() {
343        let m = Message::call(
344            "org.freedesktop.DBus",
345            "/org/freedesktop/DBus",
346            "org.freedesktop.DBus",
347            "Hello",
348        );
349        let bytes = m.serialize(1);
350        assert_eq!(Message::framed_length(&bytes), Some(bytes.len()));
351        let back = Message::parse(&bytes).unwrap();
352        assert!(back.body.is_empty());
353        assert_eq!(back.member.as_deref(), Some("Hello"));
354    }
355
356    #[test]
357    fn an_error_reply_round_trips() {
358        let call = Message::call("org.bluez", "/", "org.bluez.Adapter1", "StartDiscovery");
359        let mut call = call;
360        call.serial = 42;
361        call.sender = Some(":1.5".into());
362
363        let err = Message::error_to(&call, "org.bluez.Error.NotReady", "adapter is down");
364        let bytes = err.serialize(9);
365        let back = Message::parse(&bytes).unwrap();
366        assert_eq!(back.message_type, MessageType::Error);
367        assert_eq!(back.reply_serial, Some(42));
368        assert_eq!(back.error_name.as_deref(), Some("org.bluez.Error.NotReady"));
369        assert_eq!(back.error_text().as_deref(), Some("adapter is down"));
370        assert_eq!(back.destination.as_deref(), Some(":1.5"));
371    }
372
373    #[test]
374    fn a_signal_with_a_nested_body_round_trips() {
375        // PropertiesChanged is the shape every notification arrives in.
376        let sig = Message::signal(
377            "/org/bluez/hci0/dev_AA/service0001/char0002",
378            "org.freedesktop.DBus.Properties",
379            "PropertiesChanged",
380        )
381        .with_body(vec![
382            Value::Str("org.bluez.GattCharacteristic1".into()),
383            Value::dict([("Value".into(), Value::bytes(&[0x5B]))]),
384            Value::string_array([]),
385        ]);
386
387        let bytes = sig.serialize(3);
388        assert_eq!(Message::framed_length(&bytes), Some(bytes.len()));
389        let back = Message::parse(&bytes).unwrap();
390        assert_eq!(back.message_type, MessageType::Signal);
391        let changed = back.arg(1).unwrap();
392        assert_eq!(changed.get("Value").unwrap().as_bytes(), Some(vec![0x5B]));
393    }
394
395    #[test]
396    fn framing_needs_the_whole_fixed_header() {
397        assert_eq!(Message::framed_length(&[]), None);
398        assert_eq!(Message::framed_length(&[b'l', 1, 0, 1]), None);
399    }
400
401    #[test]
402    fn a_truncated_message_errors_rather_than_panicking() {
403        let m = Message::call("a", "/b", "c", "d").with_body(vec![Value::Str("x".into())]);
404        let bytes = m.serialize(1);
405        for cut in 0..bytes.len() {
406            // Every prefix must be an error, never a panic.
407            let _ = Message::parse(&bytes[..cut]);
408        }
409    }
410
411    #[test]
412    fn serial_is_taken_from_the_argument_not_the_struct() {
413        // The connection assigns serials, so the field on the struct is ignored.
414        let m = Message::call("a", "/b", "c", "d");
415        assert_eq!(Message::parse(&m.serialize(99)).unwrap().serial, 99);
416    }
417}