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    /// File descriptors received alongside an inbound method call.
82    ///
83    /// Profile APIs such as BlueZ `Profile1.NewConnection` pass an already
84    /// connected socket this way. The object handler owns these descriptors
85    /// and must either adopt or close them.
86    pub received_fds: Vec<std::os::fd::RawFd>,
87}
88
89impl Message {
90    fn empty(message_type: MessageType) -> Self {
91        Self {
92            message_type,
93            flags: 0,
94            serial: 0,
95            path: None,
96            interface: None,
97            member: None,
98            error_name: None,
99            reply_serial: None,
100            destination: None,
101            sender: None,
102            body: Vec::new(),
103            unix_fds: 0,
104            received_fds: Vec::new(),
105        }
106    }
107
108    /// A method call.
109    pub fn call(destination: &str, path: &str, interface: &str, member: &str) -> Self {
110        let mut m = Self::empty(MessageType::MethodCall);
111        m.destination = Some(destination.into());
112        m.path = Some(path.into());
113        m.interface = Some(interface.into());
114        m.member = Some(member.into());
115        m
116    }
117
118    /// A signal.
119    pub fn signal(path: &str, interface: &str, member: &str) -> Self {
120        let mut m = Self::empty(MessageType::Signal);
121        m.path = Some(path.into());
122        m.interface = Some(interface.into());
123        m.member = Some(member.into());
124        m
125    }
126
127    /// A successful reply to `call`.
128    pub fn reply_to(call: &Message) -> Self {
129        let mut m = Self::empty(MessageType::MethodReturn);
130        m.reply_serial = Some(call.serial);
131        m.destination = call.sender.clone();
132        m
133    }
134
135    /// An error reply to `call`.
136    pub fn error_to(call: &Message, name: &str, text: &str) -> Self {
137        let mut m = Self::empty(MessageType::Error);
138        m.reply_serial = Some(call.serial);
139        m.destination = call.sender.clone();
140        m.error_name = Some(name.into());
141        m.body = vec![Value::Str(text.into())];
142        m
143    }
144
145    /// Attach a body.
146    pub fn with_body(mut self, body: Vec<Value>) -> Self {
147        self.body = body;
148        self
149    }
150
151    /// The body's signature, derived from the values themselves.
152    pub fn signature(&self) -> String {
153        self.body.iter().map(Value::signature).collect()
154    }
155
156    /// `body[i]`, if present.
157    pub fn arg(&self, i: usize) -> Option<&Value> {
158        self.body.get(i)
159    }
160
161    /// The text of an error reply.
162    pub fn error_text(&self) -> Option<String> {
163        self.body
164            .first()
165            .and_then(|v| v.as_str())
166            .map(str::to_owned)
167    }
168
169    /// Encode to the wire.
170    pub fn serialize(&self, serial: u32) -> Vec<u8> {
171        let mut body_encoder = Encoder::new();
172        body_encoder.body(&self.body);
173        let body = body_encoder.finish();
174
175        let mut fields: Vec<Value> = Vec::new();
176        let mut push = |code: u8, v: Value| {
177            fields.push(Value::Struct(vec![
178                Value::Byte(code),
179                Value::Variant(Box::new(v)),
180            ]));
181        };
182        if let Some(p) = &self.path {
183            push(field::PATH, Value::ObjectPath(p.clone()));
184        }
185        if let Some(i) = &self.interface {
186            push(field::INTERFACE, Value::Str(i.clone()));
187        }
188        if let Some(m) = &self.member {
189            push(field::MEMBER, Value::Str(m.clone()));
190        }
191        if let Some(e) = &self.error_name {
192            push(field::ERROR_NAME, Value::Str(e.clone()));
193        }
194        if let Some(r) = self.reply_serial {
195            push(field::REPLY_SERIAL, Value::Uint32(r));
196        }
197        if let Some(d) = &self.destination {
198            push(field::DESTINATION, Value::Str(d.clone()));
199        }
200        if let Some(s) = &self.sender {
201            push(field::SENDER, Value::Str(s.clone()));
202        }
203        if !self.body.is_empty() {
204            push(field::SIGNATURE, Value::Signature(self.signature()));
205        }
206
207        let mut encoder = Encoder::new();
208        encoder.byte(b'l');
209        encoder.byte(self.message_type as u8);
210        encoder.byte(self.flags);
211        encoder.byte(1);
212        encoder.u32(body.len() as u32);
213        encoder.u32(serial);
214        encoder.value(&Value::Array {
215            element: "(yv)".into(),
216            items: fields,
217        });
218        encoder.align(8);
219
220        let mut out = encoder.finish();
221        out.extend_from_slice(&body);
222        out
223    }
224
225    /// How long a message starting at `buf` is, or `None` if the fixed header
226    /// has not arrived yet. Used to know how much more to read.
227    pub fn framed_length(buf: &[u8]) -> Option<usize> {
228        if buf.len() < 16 {
229            return None;
230        }
231        let little_endian = buf[0] == b'l';
232        let read_u32 = |at: usize| {
233            let a = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]];
234            (if little_endian {
235                u32::from_le_bytes(a)
236            } else {
237                u32::from_be_bytes(a)
238            }) as usize
239        };
240        let body_len = read_u32(4);
241        let fields_len = read_u32(12);
242        // 12 fixed + 4 array length + fields, padded to 8, then body.
243        let header_end = 16 + fields_len;
244        let padded = header_end.div_ceil(8) * 8;
245        Some(padded + body_len)
246    }
247
248    /// Decode one complete message.
249    pub fn parse(buf: &[u8]) -> Result<Self, CodecError> {
250        if buf.len() < 16 {
251            return Err(CodecError::Truncated {
252                wanted: 16,
253                available: buf.len(),
254            });
255        }
256        let little_endian = buf[0] == b'l';
257        let message_type =
258            MessageType::from_u8(buf[1]).ok_or(CodecError::BadTypeCode(buf[1] as char))?;
259        let flags = buf[2];
260
261        let mut decoder = Decoder::at(buf, 4, little_endian);
262        let body_len = decoder.u32()? as usize;
263        let serial = decoder.u32()?;
264        let fields = decoder.value("a(yv)")?;
265
266        let mut message = Self::empty(message_type);
267        message.flags = flags;
268        message.serial = serial;
269        let mut signature = String::new();
270
271        for entry in fields.as_array().unwrap_or(&[]) {
272            let Some(parts) = entry.as_array() else {
273                continue;
274            };
275            let (Some(code), Some(v)) = (parts.first().and_then(Value::as_u64), parts.get(1))
276            else {
277                continue;
278            };
279            match code as u8 {
280                field::PATH => message.path = v.as_str().map(str::to_owned),
281                field::INTERFACE => message.interface = v.as_str().map(str::to_owned),
282                field::MEMBER => message.member = v.as_str().map(str::to_owned),
283                field::ERROR_NAME => message.error_name = v.as_str().map(str::to_owned),
284                field::REPLY_SERIAL => message.reply_serial = v.as_u64().map(|n| n as u32),
285                field::DESTINATION => message.destination = v.as_str().map(str::to_owned),
286                field::SENDER => message.sender = v.as_str().map(str::to_owned),
287                field::SIGNATURE => signature = v.as_str().unwrap_or_default().to_owned(),
288                field::UNIX_FDS => message.unix_fds = v.as_u64().unwrap_or(0) as u32,
289                _ => {}
290            }
291        }
292
293        // The body starts at the next multiple of 8 after the header array.
294        let body_start = decoder.position().div_ceil(8) * 8;
295        if !signature.is_empty() {
296            let end = body_start + body_len;
297            if end > buf.len() {
298                return Err(CodecError::Truncated {
299                    wanted: body_len,
300                    available: buf.len().saturating_sub(body_start),
301                });
302            }
303            let mut body_decoder = Decoder::new(&buf[body_start..end], little_endian);
304            message.body = body_decoder.body(&signature)?;
305        }
306        Ok(message)
307    }
308}
309
310impl Drop for Message {
311    fn drop(&mut self) {
312        for fd in self.received_fds.drain(..) {
313            unsafe { crate::dbus::fds::close_raw(fd) };
314        }
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn a_method_call_round_trips() {
324        let call = Message::call(
325            "org.bluez",
326            "/org/bluez/hci0",
327            "org.freedesktop.DBus.Properties",
328            "Get",
329        )
330        .with_body(vec![
331            Value::Str("org.bluez.Adapter1".into()),
332            Value::Str("Powered".into()),
333        ]);
334
335        let bytes = call.serialize(7);
336        assert_eq!(
337            Message::framed_length(&bytes),
338            Some(bytes.len()),
339            "framing disagrees"
340        );
341
342        let back = Message::parse(&bytes).unwrap();
343        assert_eq!(back.message_type, MessageType::MethodCall);
344        assert_eq!(back.serial, 7);
345        assert_eq!(back.destination.as_deref(), Some("org.bluez"));
346        assert_eq!(back.path.as_deref(), Some("/org/bluez/hci0"));
347        assert_eq!(
348            back.interface.as_deref(),
349            Some("org.freedesktop.DBus.Properties")
350        );
351        assert_eq!(back.member.as_deref(), Some("Get"));
352        assert_eq!(back.body.len(), 2);
353        assert_eq!(back.arg(1).unwrap().as_str(), Some("Powered"));
354    }
355
356    #[test]
357    fn a_body_less_message_round_trips() {
358        let m = Message::call(
359            "org.freedesktop.DBus",
360            "/org/freedesktop/DBus",
361            "org.freedesktop.DBus",
362            "Hello",
363        );
364        let bytes = m.serialize(1);
365        assert_eq!(Message::framed_length(&bytes), Some(bytes.len()));
366        let back = Message::parse(&bytes).unwrap();
367        assert!(back.body.is_empty());
368        assert_eq!(back.member.as_deref(), Some("Hello"));
369    }
370
371    #[test]
372    fn an_error_reply_round_trips() {
373        let call = Message::call("org.bluez", "/", "org.bluez.Adapter1", "StartDiscovery");
374        let mut call = call;
375        call.serial = 42;
376        call.sender = Some(":1.5".into());
377
378        let err = Message::error_to(&call, "org.bluez.Error.NotReady", "adapter is down");
379        let bytes = err.serialize(9);
380        let back = Message::parse(&bytes).unwrap();
381        assert_eq!(back.message_type, MessageType::Error);
382        assert_eq!(back.reply_serial, Some(42));
383        assert_eq!(back.error_name.as_deref(), Some("org.bluez.Error.NotReady"));
384        assert_eq!(back.error_text().as_deref(), Some("adapter is down"));
385        assert_eq!(back.destination.as_deref(), Some(":1.5"));
386    }
387
388    #[test]
389    fn a_signal_with_a_nested_body_round_trips() {
390        // PropertiesChanged is the shape every notification arrives in.
391        let sig = Message::signal(
392            "/org/bluez/hci0/dev_AA/service0001/char0002",
393            "org.freedesktop.DBus.Properties",
394            "PropertiesChanged",
395        )
396        .with_body(vec![
397            Value::Str("org.bluez.GattCharacteristic1".into()),
398            Value::dict([("Value".into(), Value::bytes(&[0x5B]))]),
399            Value::string_array([]),
400        ]);
401
402        let bytes = sig.serialize(3);
403        assert_eq!(Message::framed_length(&bytes), Some(bytes.len()));
404        let back = Message::parse(&bytes).unwrap();
405        assert_eq!(back.message_type, MessageType::Signal);
406        let changed = back.arg(1).unwrap();
407        assert_eq!(changed.get("Value").unwrap().as_bytes(), Some(vec![0x5B]));
408    }
409
410    #[test]
411    fn framing_needs_the_whole_fixed_header() {
412        assert_eq!(Message::framed_length(&[]), None);
413        assert_eq!(Message::framed_length(&[b'l', 1, 0, 1]), None);
414    }
415
416    #[test]
417    fn a_truncated_message_errors_rather_than_panicking() {
418        let m = Message::call("a", "/b", "c", "d").with_body(vec![Value::Str("x".into())]);
419        let bytes = m.serialize(1);
420        for cut in 0..bytes.len() {
421            // Every prefix must be an error, never a panic.
422            let _ = Message::parse(&bytes[..cut]);
423        }
424    }
425
426    #[test]
427    fn serial_is_taken_from_the_argument_not_the_struct() {
428        // The connection assigns serials, so the field on the struct is ignored.
429        let m = Message::call("a", "/b", "c", "d");
430        assert_eq!(Message::parse(&m.serialize(99)).unwrap().serial, 99);
431    }
432}