Skip to main content

day_platform_linux/dbus/
mod.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-platform-linux: a std-only client for the freedesktop session bus.
5//!
6//! The crate speaks the D-Bus wire protocol directly: little-endian marshaling (and reading of
7//! both byte orders), SASL `EXTERNAL` authentication over a unix socket, `Hello`, and one
8//! background reader thread per [`Connection`] that routes replies to blocked callers, signals to
9//! subscribers and method calls to exported objects. There is no async runtime, no libdbus and no
10//! zbus; everything is `std`.
11//!
12//! On top of the connection sit two small servers the Linux backends share:
13//!
14//! - [`sni`]: a `StatusNotifierItem` with its `com.canonical.dbusmenu` menu, the tray icon that
15//!   GNOME (through the AppIndicator extension), KDE, and most panels show.
16//! - [`launcher`]: the Unity `LauncherEntry` signal that docks read for a badge count, progress,
17//!   and urgency.
18//!
19//! Only unix transports exist (`unix:path=` and, on Linux, `unix:abstract=`). Elsewhere the crate
20//! still compiles, and [`Connection::session`] returns [`Error::Unsupported`].
21//!
22//! # Threads
23//!
24//! Exported handlers and signal callbacks run on the connection's reader thread. A blocking
25//! [`Connection::call`] made from that thread would wait for a reply only that thread can read,
26//! so it returns [`Error::ReaderThread`] instead; use [`Connection::call_no_reply`] or hand the
27//! work to another thread.
28
29use std::collections::{BTreeSet, HashMap};
30use std::fmt;
31use std::io::{self, Read, Write};
32use std::sync::atomic::{AtomicU32, Ordering};
33use std::sync::mpsc;
34use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
35use std::thread::{self, ThreadId};
36use std::time::Duration;
37
38pub mod sni;
39
40/// How long [`Connection::call`] waits for a reply.
41pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2);
42
43/// The bus daemon's own name, object path and interface.
44pub const BUS_NAME: &str = "org.freedesktop.DBus";
45/// The bus daemon's object path.
46pub const BUS_PATH: &str = "/org/freedesktop/DBus";
47/// The bus daemon's interface (`Hello`, `RequestName`, `AddMatch`, …).
48pub const BUS_INTERFACE: &str = "org.freedesktop.DBus";
49/// The standard properties interface (`Get`, `GetAll`, `Set`).
50pub const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
51/// The standard introspection interface (`Introspect`).
52pub const INTROSPECTABLE_INTERFACE: &str = "org.freedesktop.DBus.Introspectable";
53/// The standard peer interface (`Ping`, `GetMachineId`), answered by every connection.
54pub const PEER_INTERFACE: &str = "org.freedesktop.DBus.Peer";
55
56/// `RequestName` flag: let another connection take the name over.
57pub const NAME_FLAG_ALLOW_REPLACEMENT: u32 = 0x1;
58/// `RequestName` flag: take the name over from an owner that allows replacement.
59pub const NAME_FLAG_REPLACE_EXISTING: u32 = 0x2;
60/// `RequestName` flag: fail instead of waiting in the queue for the name.
61pub const NAME_FLAG_DO_NOT_QUEUE: u32 = 0x4;
62/// `RequestName` reply: the caller now owns the name.
63pub const NAME_REPLY_PRIMARY_OWNER: u32 = 1;
64/// `RequestName` reply: the caller waits in the queue for the name.
65pub const NAME_REPLY_IN_QUEUE: u32 = 2;
66/// `RequestName` reply: someone else owns the name and the caller did not queue.
67pub const NAME_REPLY_EXISTS: u32 = 3;
68/// `RequestName` reply: the caller already owned the name.
69pub const NAME_REPLY_ALREADY_OWNER: u32 = 4;
70
71/// Message flag: the sender does not want a reply.
72pub const FLAG_NO_REPLY_EXPECTED: u8 = 0x1;
73/// Message flag: the bus must not start a service to deliver the message.
74pub const FLAG_NO_AUTO_START: u8 = 0x2;
75
76/// The spec's limit on a whole message.
77const MAX_MESSAGE: usize = 128 * 1024 * 1024;
78/// The spec's limit on one array's payload.
79const MAX_ARRAY: usize = 64 * 1024 * 1024;
80/// Nesting limit for values and signatures (the spec allows 32 arrays plus 32 structs).
81const MAX_DEPTH: u32 = 64;
82
83// ---------------------------------------------------------------------------
84// Errors
85// ---------------------------------------------------------------------------
86
87/// What can go wrong talking to the bus.
88#[derive(Debug)]
89pub enum Error {
90    /// This platform has no D-Bus transport (it is not unix).
91    Unsupported,
92    /// No session bus address was found, or none of its transports could be used.
93    NoBus(String),
94    /// Reading or writing the socket failed.
95    Io(io::Error),
96    /// The bus refused authentication.
97    Auth(String),
98    /// A malformed message, signature, or name, ours or the peer's.
99    Protocol(String),
100    /// The connection is closed; no reply will come.
101    Disconnected,
102    /// No reply arrived within the timeout.
103    Timeout,
104    /// A blocking call was made from the reader thread (a handler or signal callback), where it
105    /// could never receive its reply.
106    ReaderThread,
107    /// The peer answered with a D-Bus error.
108    Remote {
109        /// The error name, such as `org.freedesktop.DBus.Error.ServiceUnknown`.
110        name: String,
111        /// The error's message argument, or empty.
112        message: String,
113    },
114}
115
116impl fmt::Display for Error {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        match self {
119            Error::Unsupported => f.write_str("D-Bus is not available on this platform"),
120            Error::NoBus(why) => write!(f, "no session bus: {why}"),
121            Error::Io(e) => write!(f, "D-Bus socket error: {e}"),
122            Error::Auth(why) => write!(f, "D-Bus authentication failed: {why}"),
123            Error::Protocol(why) => write!(f, "D-Bus protocol error: {why}"),
124            Error::Disconnected => f.write_str("D-Bus connection closed"),
125            Error::Timeout => f.write_str("D-Bus call timed out"),
126            Error::ReaderThread => {
127                f.write_str("blocking D-Bus call made from the connection's reader thread")
128            }
129            Error::Remote { name, message } if message.is_empty() => f.write_str(name),
130            Error::Remote { name, message } => write!(f, "{name}: {message}"),
131        }
132    }
133}
134
135impl std::error::Error for Error {
136    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
137        match self {
138            Error::Io(e) => Some(e),
139            _ => None,
140        }
141    }
142}
143
144impl From<io::Error> for Error {
145    fn from(e: io::Error) -> Self {
146        Error::Io(e)
147    }
148}
149
150fn protocol(why: impl Into<String>) -> Error {
151    Error::Protocol(why.into())
152}
153
154// ---------------------------------------------------------------------------
155// Values and signatures
156// ---------------------------------------------------------------------------
157
158/// One D-Bus value. Containers carry enough type information to marshal even when empty: an
159/// array names its element signature.
160#[derive(Clone, Debug, PartialEq)]
161pub enum Value {
162    /// `y`
163    Byte(u8),
164    /// `b`
165    Bool(bool),
166    /// `n`
167    I16(i16),
168    /// `q`
169    U16(u16),
170    /// `i`
171    I32(i32),
172    /// `u`
173    U32(u32),
174    /// `x`
175    I64(i64),
176    /// `t`
177    U64(u64),
178    /// `d`
179    Double(f64),
180    /// `s`
181    Str(String),
182    /// `o`
183    ObjectPath(String),
184    /// `g`
185    Signature(String),
186    /// `a…`: an array whose items all have the single complete type `elem`. A dictionary is an
187    /// array of [`Value::DictEntry`] items with an `elem` such as `{sv}`.
188    Array {
189        /// The element signature, such as `s`, `(iiay)` or `{sv}`.
190        elem: String,
191        /// The items; each must have signature `elem`.
192        items: Vec<Value>,
193    },
194    /// `(…)`: a struct of one or more fields.
195    Struct(Vec<Value>),
196    /// `{kv}`: a dictionary entry; only valid as an array item, with a basic-typed key.
197    DictEntry(Box<Value>, Box<Value>),
198    /// `v`: a value that carries its own signature.
199    Variant(Box<Value>),
200}
201
202impl Value {
203    /// A string value.
204    pub fn str(s: impl Into<String>) -> Value {
205        Value::Str(s.into())
206    }
207
208    /// An object path value.
209    pub fn path(p: impl Into<String>) -> Value {
210        Value::ObjectPath(p.into())
211    }
212
213    /// A variant wrapping `v`.
214    #[must_use]
215    pub fn variant(v: Value) -> Value {
216        Value::Variant(Box::new(v))
217    }
218
219    /// An array with element signature `elem`.
220    pub fn array(elem: impl Into<String>, items: Vec<Value>) -> Value {
221        Value::Array {
222            elem: elem.into(),
223            items,
224        }
225    }
226
227    /// A byte array (`ay`).
228    #[must_use]
229    pub fn bytes(bytes: &[u8]) -> Value {
230        Value::array("y", bytes.iter().map(|b| Value::Byte(*b)).collect())
231    }
232
233    /// A string array (`as`).
234    pub fn strings<S: AsRef<str>>(items: &[S]) -> Value {
235        Value::array("s", items.iter().map(|s| Value::str(s.as_ref())).collect())
236    }
237
238    /// A dictionary `a{kv}` from key and value signatures and its entries.
239    pub fn dict(
240        key: &str,
241        value: &str,
242        entries: impl IntoIterator<Item = (Value, Value)>,
243    ) -> Value {
244        Value::array(
245            format!("{{{key}{value}}}"),
246            entries
247                .into_iter()
248                .map(|(k, v)| Value::DictEntry(Box::new(k), Box::new(v)))
249                .collect(),
250        )
251    }
252
253    /// The `a{sv}` property dictionary most interfaces use.
254    pub fn props<K: Into<String>>(entries: impl IntoIterator<Item = (K, Value)>) -> Value {
255        Value::dict(
256            "s",
257            "v",
258            entries
259                .into_iter()
260                .map(|(k, v)| (Value::Str(k.into()), Value::variant(v))),
261        )
262    }
263
264    /// This value's D-Bus signature, such as `s`, `a{sv}` or `(iiay)`.
265    #[must_use]
266    pub fn signature(&self) -> String {
267        let mut s = String::new();
268        self.write_signature(&mut s);
269        s
270    }
271
272    fn write_signature(&self, out: &mut String) {
273        match self {
274            Value::Array { elem, .. } => {
275                out.push('a');
276                out.push_str(elem);
277            }
278            Value::Struct(fields) => {
279                out.push('(');
280                for f in fields {
281                    f.write_signature(out);
282                }
283                out.push(')');
284            }
285            Value::DictEntry(k, v) => {
286                out.push('{');
287                k.write_signature(out);
288                v.write_signature(out);
289                out.push('}');
290            }
291            other => out.push(other.basic_code().unwrap_or('v')),
292        }
293    }
294
295    /// The one-character code of a basic type or variant, `None` for a container.
296    fn basic_code(&self) -> Option<char> {
297        Some(match self {
298            Value::Byte(_) => 'y',
299            Value::Bool(_) => 'b',
300            Value::I16(_) => 'n',
301            Value::U16(_) => 'q',
302            Value::I32(_) => 'i',
303            Value::U32(_) => 'u',
304            Value::I64(_) => 'x',
305            Value::U64(_) => 't',
306            Value::Double(_) => 'd',
307            Value::Str(_) => 's',
308            Value::ObjectPath(_) => 'o',
309            Value::Signature(_) => 'g',
310            Value::Variant(_) => 'v',
311            Value::Array { .. } | Value::Struct(_) | Value::DictEntry(..) => return None,
312        })
313    }
314
315    /// Whether this value has the single complete type `sig`, without allocating.
316    fn conforms(&self, sig: &str) -> bool {
317        match self {
318            Value::Array { elem, .. } => sig.strip_prefix('a') == Some(elem.as_str()),
319            Value::Struct(fields) => {
320                let Some(mut inner) = sig.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
321                else {
322                    return false;
323                };
324                for f in fields {
325                    match split_first_type(inner) {
326                        Ok((first, rest)) if f.conforms(first) => inner = rest,
327                        _ => return false,
328                    }
329                }
330                inner.is_empty() && !fields.is_empty()
331            }
332            Value::DictEntry(k, v) => {
333                let Some(inner) = sig.strip_prefix('{').and_then(|s| s.strip_suffix('}')) else {
334                    return false;
335                };
336                match split_first_type(inner) {
337                    Ok((first, rest)) => k.conforms(first) && v.conforms(rest),
338                    Err(_) => false,
339                }
340            }
341            basic => {
342                let mut chars = sig.chars();
343                basic.basic_code() == chars.next() && chars.next().is_none()
344            }
345        }
346    }
347
348    /// The string inside a `Str`, `ObjectPath` or `Signature` (looking through variants).
349    #[must_use]
350    pub fn as_str(&self) -> Option<&str> {
351        match self {
352            Value::Str(s) | Value::ObjectPath(s) | Value::Signature(s) => Some(s),
353            Value::Variant(v) => v.as_str(),
354            _ => None,
355        }
356    }
357
358    /// The boolean inside a `Bool` (looking through variants).
359    #[must_use]
360    pub fn as_bool(&self) -> Option<bool> {
361        match self {
362            Value::Bool(b) => Some(*b),
363            Value::Variant(v) => v.as_bool(),
364            _ => None,
365        }
366    }
367
368    /// Any integer value widened to `i64` (looking through variants); `None` for a `U64` above
369    /// `i64::MAX` or a non-integer.
370    #[must_use]
371    pub fn as_i64(&self) -> Option<i64> {
372        match self {
373            Value::Byte(n) => Some(i64::from(*n)),
374            Value::I16(n) => Some(i64::from(*n)),
375            Value::U16(n) => Some(i64::from(*n)),
376            Value::I32(n) => Some(i64::from(*n)),
377            Value::U32(n) => Some(i64::from(*n)),
378            Value::I64(n) => Some(*n),
379            Value::U64(n) => i64::try_from(*n).ok(),
380            Value::Variant(v) => v.as_i64(),
381            _ => None,
382        }
383    }
384
385    /// The number inside a `Double`, or any integer converted (looking through variants).
386    #[must_use]
387    pub fn as_f64(&self) -> Option<f64> {
388        match self {
389            Value::Double(d) => Some(*d),
390            Value::Variant(v) => v.as_f64(),
391            other => other.as_i64().map(|n| n as f64),
392        }
393    }
394
395    /// The items of an array (looking through variants).
396    #[must_use]
397    pub fn as_array(&self) -> Option<&[Value]> {
398        match self {
399            Value::Array { items, .. } => Some(items),
400            Value::Variant(v) => v.as_array(),
401            _ => None,
402        }
403    }
404
405    /// The fields of a struct (looking through variants).
406    #[must_use]
407    pub fn as_struct(&self) -> Option<&[Value]> {
408        match self {
409            Value::Struct(fields) => Some(fields),
410            Value::Variant(v) => v.as_struct(),
411            _ => None,
412        }
413    }
414
415    /// The value inside a variant, or the value itself when it is not one.
416    #[must_use]
417    pub fn unwrap_variant(&self) -> &Value {
418        match self {
419            Value::Variant(v) => v.unwrap_variant(),
420            other => other,
421        }
422    }
423
424    /// Looks `key` up in a string-keyed dictionary such as `a{sv}`; the result is the entry's
425    /// value with any variant unwrapped.
426    #[must_use]
427    pub fn dict_get(&self, key: &str) -> Option<&Value> {
428        self.as_array()?.iter().find_map(|item| match item {
429            Value::DictEntry(k, v) if k.as_str() == Some(key) => Some(v.unwrap_variant()),
430            _ => None,
431        })
432    }
433}
434
435/// Splits `sig` into its first single complete type and the rest.
436fn split_first_type(sig: &str) -> Result<(&str, &str), Error> {
437    let len = complete_type_len(sig.as_bytes(), 0)?;
438    Ok(sig.split_at(len))
439}
440
441fn complete_type_len(sig: &[u8], depth: u32) -> Result<usize, Error> {
442    if depth > MAX_DEPTH {
443        return Err(protocol("signature nests too deeply"));
444    }
445    match sig.first() {
446        None => Err(protocol("empty signature")),
447        Some(
448            b'y' | b'b' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'd' | b's' | b'o' | b'g'
449            | b'v',
450        ) => Ok(1),
451        Some(b'a') => Ok(1 + complete_type_len(&sig[1..], depth + 1)?),
452        Some(b'(') => {
453            let mut at = 1;
454            while sig.get(at) != Some(&b')') {
455                if at >= sig.len() {
456                    return Err(protocol("unterminated struct in signature"));
457                }
458                at += complete_type_len(&sig[at..], depth + 1)?;
459            }
460            if at == 1 {
461                return Err(protocol("empty struct in signature"));
462            }
463            Ok(at + 1)
464        }
465        Some(b'{') => {
466            let key = sig.get(1).copied();
467            if !matches!(
468                key,
469                Some(
470                    b'y' | b'b'
471                        | b'n'
472                        | b'q'
473                        | b'i'
474                        | b'u'
475                        | b'x'
476                        | b't'
477                        | b'd'
478                        | b's'
479                        | b'o'
480                        | b'g'
481                )
482            ) {
483                return Err(protocol("dict entry key must be a basic type"));
484            }
485            let value = complete_type_len(&sig[2..], depth + 1)?;
486            if sig.get(2 + value) != Some(&b'}') {
487                return Err(protocol("dict entry must hold exactly two types"));
488            }
489            Ok(value + 3)
490        }
491        Some(c) => Err(protocol(format!(
492            "unsupported type code {:?} in signature",
493            char::from(*c)
494        ))),
495    }
496}
497
498/// Checks a whole signature (zero or more complete types, at most 255 bytes).
499fn validate_signature(sig: &str) -> Result<(), Error> {
500    if sig.len() > 255 {
501        return Err(protocol("signature longer than 255 bytes"));
502    }
503    let mut rest = sig;
504    while !rest.is_empty() {
505        rest = split_first_type(rest)?.1;
506    }
507    Ok(())
508}
509
510/// The marshaling alignment of a type, by its first signature character.
511fn alignment(sig: &str) -> usize {
512    match sig.as_bytes().first() {
513        Some(b'n' | b'q') => 2,
514        Some(b'b' | b'i' | b'u' | b's' | b'o' | b'a' | b'h') => 4,
515        Some(b'x' | b't' | b'd' | b'(' | b'{') => 8,
516        _ => 1,
517    }
518}
519
520/// Whether `p` is a valid object path: `/`, or `/`-separated non-empty `[A-Za-z0-9_]` segments.
521#[must_use]
522pub fn is_valid_object_path(p: &str) -> bool {
523    if p == "/" {
524        return true;
525    }
526    let Some(rest) = p.strip_prefix('/') else {
527        return false;
528    };
529    rest.split('/')
530        .all(|seg| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'))
531}
532
533/// Whether `name` is a valid interface or error name: two or more dot-separated elements of
534/// `[A-Za-z0-9_]`, none starting with a digit, at most 255 bytes.
535fn is_valid_interface(name: &str) -> bool {
536    name.len() <= 255
537        && name.split('.').count() >= 2
538        && name.split('.').all(|el| {
539            !el.is_empty()
540                && !el.starts_with(|c: char| c.is_ascii_digit())
541                && el.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
542        })
543}
544
545/// Whether `name` is a valid member name.
546fn is_valid_member(name: &str) -> bool {
547    !name.is_empty()
548        && name.len() <= 255
549        && !name.starts_with(|c: char| c.is_ascii_digit())
550        && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
551}
552
553/// Whether `name` is a plausible bus name (unique `:1.42` or well-known `org.example.App`).
554fn is_valid_bus_name(name: &str) -> bool {
555    let (unique, body) = match name.strip_prefix(':') {
556        Some(rest) => (true, rest),
557        None => (false, name),
558    };
559    name.len() <= 255
560        && body.split('.').count() >= 2
561        && body.split('.').all(|el| {
562            !el.is_empty()
563                && (unique || !el.starts_with(|c: char| c.is_ascii_digit()))
564                && el
565                    .bytes()
566                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
567        })
568}
569
570// ---------------------------------------------------------------------------
571// Marshaling
572// ---------------------------------------------------------------------------
573
574/// Writes values at offsets relative to the start of the buffer, which is the start of the
575/// message (the body starts 8-aligned, so a body marshaled alone lines up the same way).
576struct Encoder {
577    buf: Vec<u8>,
578    big: bool,
579}
580
581impl Encoder {
582    fn new(big: bool) -> Self {
583        Encoder {
584            buf: Vec::new(),
585            big,
586        }
587    }
588
589    fn pad(&mut self, align: usize) {
590        let padded = self.buf.len().next_multiple_of(align);
591        self.buf.resize(padded, 0);
592    }
593
594    fn put(&mut self, le: &[u8], be: &[u8]) {
595        self.pad(le.len());
596        self.buf.extend_from_slice(if self.big { be } else { le });
597    }
598
599    fn u32(&mut self, v: u32) {
600        self.put(&v.to_le_bytes(), &v.to_be_bytes());
601    }
602
603    fn string(&mut self, s: &str) -> Result<(), Error> {
604        if s.contains('\0') {
605            return Err(protocol("string contains a NUL byte"));
606        }
607        let len = u32::try_from(s.len()).map_err(|_| protocol("string too long"))?;
608        self.u32(len);
609        self.buf.extend_from_slice(s.as_bytes());
610        self.buf.push(0);
611        Ok(())
612    }
613
614    fn signature(&mut self, s: &str) -> Result<(), Error> {
615        validate_signature(s)?;
616        // validate_signature bounds the length at 255.
617        self.buf.push(s.len() as u8);
618        self.buf.extend_from_slice(s.as_bytes());
619        self.buf.push(0);
620        Ok(())
621    }
622
623    fn value(&mut self, v: &Value, depth: u32) -> Result<(), Error> {
624        if depth > MAX_DEPTH {
625            return Err(protocol("value nests too deeply"));
626        }
627        match v {
628            Value::Byte(b) => self.buf.push(*b),
629            Value::Bool(b) => self.u32(u32::from(*b)),
630            Value::I16(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
631            Value::U16(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
632            Value::I32(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
633            Value::U32(n) => self.u32(*n),
634            Value::I64(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
635            Value::U64(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
636            Value::Double(d) => self.put(&d.to_le_bytes(), &d.to_be_bytes()),
637            Value::Str(s) => self.string(s)?,
638            Value::ObjectPath(p) => {
639                if !is_valid_object_path(p) {
640                    return Err(protocol(format!("invalid object path {p:?}")));
641                }
642                self.string(p)?;
643            }
644            Value::Signature(s) => self.signature(s)?,
645            Value::Array { elem, items } => {
646                let (_, rest) = split_first_type(elem)?;
647                if !rest.is_empty() {
648                    return Err(protocol(format!(
649                        "array element signature {elem:?} is not a single complete type"
650                    )));
651                }
652                self.pad(4);
653                let len_at = self.buf.len();
654                self.buf.extend_from_slice(&[0; 4]);
655                // The padding before the first element is not part of the array's length, and
656                // is present even when the array is empty.
657                self.pad(alignment(elem));
658                let start = self.buf.len();
659                for item in items {
660                    if !item.conforms(elem) {
661                        return Err(protocol(format!(
662                            "array item {} does not match element signature {elem}",
663                            item.signature()
664                        )));
665                    }
666                    self.value(item, depth + 1)?;
667                }
668                let len = self.buf.len() - start;
669                if len > MAX_ARRAY {
670                    return Err(protocol("array longer than 64 MiB"));
671                }
672                // MAX_ARRAY fits in u32.
673                let len = len as u32;
674                let bytes = if self.big {
675                    len.to_be_bytes()
676                } else {
677                    len.to_le_bytes()
678                };
679                self.buf[len_at..len_at + 4].copy_from_slice(&bytes);
680            }
681            Value::Struct(fields) => {
682                if fields.is_empty() {
683                    return Err(protocol("a struct needs at least one field"));
684                }
685                self.pad(8);
686                for f in fields {
687                    self.value(f, depth + 1)?;
688                }
689            }
690            Value::DictEntry(k, val) => {
691                if matches!(
692                    **k,
693                    Value::Variant(_)
694                        | Value::Array { .. }
695                        | Value::Struct(_)
696                        | Value::DictEntry(..)
697                ) {
698                    return Err(protocol("dict entry key must be a basic type"));
699                }
700                self.pad(8);
701                self.value(k, depth + 1)?;
702                self.value(val, depth + 1)?;
703            }
704            Value::Variant(inner) => {
705                let sig = inner.signature();
706                self.signature(&sig)?;
707                self.value(inner, depth + 1)?;
708            }
709        }
710        Ok(())
711    }
712}
713
714/// Reads values from a whole message, honoring its byte order.
715struct Decoder<'a> {
716    data: &'a [u8],
717    pos: usize,
718    big: bool,
719}
720
721impl<'a> Decoder<'a> {
722    fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
723        let end = self
724            .pos
725            .checked_add(n)
726            .filter(|end| *end <= self.data.len())
727            .ok_or_else(|| protocol("message truncated"))?;
728        let bytes = &self.data[self.pos..end];
729        self.pos = end;
730        Ok(bytes)
731    }
732
733    fn align(&mut self, a: usize) -> Result<(), Error> {
734        let to = self.pos.next_multiple_of(a);
735        if to > self.data.len() {
736            return Err(protocol("message truncated in padding"));
737        }
738        self.pos = to;
739        Ok(())
740    }
741
742    fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Error> {
743        self.align(N)?;
744        let mut out = [0; N];
745        out.copy_from_slice(self.take(N)?);
746        Ok(out)
747    }
748
749    fn u32(&mut self) -> Result<u32, Error> {
750        let b = self.fixed::<4>()?;
751        Ok(if self.big {
752            u32::from_be_bytes(b)
753        } else {
754            u32::from_le_bytes(b)
755        })
756    }
757
758    fn string(&mut self) -> Result<String, Error> {
759        let len = self.u32()? as usize;
760        let bytes = self.take(len)?;
761        if self.take(1)? != [0] || bytes.contains(&0) {
762            return Err(protocol("string is not NUL-terminated"));
763        }
764        String::from_utf8(bytes.to_vec()).map_err(|_| protocol("string is not UTF-8"))
765    }
766
767    fn signature(&mut self) -> Result<String, Error> {
768        let len = usize::from(self.take(1)?[0]);
769        let bytes = self.take(len)?;
770        if self.take(1)? != [0] {
771            return Err(protocol("signature is not NUL-terminated"));
772        }
773        let sig = std::str::from_utf8(bytes).map_err(|_| protocol("signature is not ASCII"))?;
774        validate_signature(sig)?;
775        Ok(sig.to_owned())
776    }
777
778    /// Reads one value of the single complete type `sig`.
779    fn value(&mut self, sig: &str, depth: u32) -> Result<Value, Error> {
780        if depth > MAX_DEPTH {
781            return Err(protocol("value nests too deeply"));
782        }
783        let big = self.big;
784        macro_rules! num {
785            ($t:ty, $n:literal, $variant:ident) => {{
786                let b = self.fixed::<$n>()?;
787                Value::$variant(if big {
788                    <$t>::from_be_bytes(b)
789                } else {
790                    <$t>::from_le_bytes(b)
791                })
792            }};
793        }
794        Ok(match sig.as_bytes().first() {
795            Some(b'y') => Value::Byte(self.take(1)?[0]),
796            Some(b'b') => match self.u32()? {
797                0 => Value::Bool(false),
798                1 => Value::Bool(true),
799                n => return Err(protocol(format!("boolean holds {n}"))),
800            },
801            Some(b'n') => num!(i16, 2, I16),
802            Some(b'q') => num!(u16, 2, U16),
803            Some(b'i') => num!(i32, 4, I32),
804            Some(b'u') => num!(u32, 4, U32),
805            Some(b'x') => num!(i64, 8, I64),
806            Some(b't') => num!(u64, 8, U64),
807            Some(b'd') => num!(f64, 8, Double),
808            Some(b's') => Value::Str(self.string()?),
809            Some(b'o') => {
810                let p = self.string()?;
811                if !is_valid_object_path(&p) {
812                    return Err(protocol(format!("invalid object path {p:?}")));
813                }
814                Value::ObjectPath(p)
815            }
816            Some(b'g') => Value::Signature(self.signature()?),
817            Some(b'v') => {
818                let inner = self.signature()?;
819                let (first, rest) = split_first_type(&inner)?;
820                if !rest.is_empty() {
821                    return Err(protocol("variant signature is not a single complete type"));
822                }
823                Value::Variant(Box::new(self.value(first, depth + 1)?))
824            }
825            Some(b'a') => {
826                let elem = &sig[1..];
827                let len = self.u32()? as usize;
828                if len > MAX_ARRAY {
829                    return Err(protocol("array longer than 64 MiB"));
830                }
831                self.align(alignment(elem))?;
832                let end = self
833                    .pos
834                    .checked_add(len)
835                    .filter(|end| *end <= self.data.len())
836                    .ok_or_else(|| protocol("array runs past the message"))?;
837                let mut items = Vec::new();
838                while self.pos < end {
839                    items.push(self.value(elem, depth + 1)?);
840                }
841                if self.pos != end {
842                    return Err(protocol("array items overrun the array length"));
843                }
844                Value::Array {
845                    elem: elem.to_owned(),
846                    items,
847                }
848            }
849            Some(b'(') => {
850                self.align(8)?;
851                let mut inner = &sig[1..sig.len() - 1];
852                let mut fields = Vec::new();
853                while !inner.is_empty() {
854                    let (first, rest) = split_first_type(inner)?;
855                    fields.push(self.value(first, depth + 1)?);
856                    inner = rest;
857                }
858                Value::Struct(fields)
859            }
860            Some(b'{') => {
861                self.align(8)?;
862                let (key, rest) = split_first_type(&sig[1..sig.len() - 1])?;
863                let k = self.value(key, depth + 1)?;
864                let v = self.value(rest, depth + 1)?;
865                Value::DictEntry(Box::new(k), Box::new(v))
866            }
867            _ => return Err(protocol(format!("cannot read type {sig:?}"))),
868        })
869    }
870}
871
872/// Marshals `values` as a little-endian body (offsets relative to an 8-aligned start).
873///
874/// # Errors
875///
876/// Returns [`Error::Protocol`] when a value cannot be marshaled, such as an invalid object
877/// path or containers nested too deeply.
878pub fn marshal(values: &[Value]) -> Result<Vec<u8>, Error> {
879    let mut e = Encoder::new(false);
880    for v in values {
881        e.value(v, 0)?;
882    }
883    Ok(e.buf)
884}
885
886/// Unmarshals a body with signature `signature` from `bytes` (little-endian unless
887/// `big_endian`), requiring every byte to be consumed.
888///
889/// # Errors
890///
891/// Returns [`Error::Protocol`] when `signature` is invalid, when `bytes` does not hold the
892/// values it describes, or when bytes are left over.
893pub fn unmarshal(bytes: &[u8], signature: &str, big_endian: bool) -> Result<Vec<Value>, Error> {
894    validate_signature(signature)?;
895    let mut d = Decoder {
896        data: bytes,
897        pos: 0,
898        big: big_endian,
899    };
900    let mut out = Vec::new();
901    let mut rest = signature;
902    while !rest.is_empty() {
903        let (first, tail) = split_first_type(rest)?;
904        out.push(d.value(first, 0)?);
905        rest = tail;
906    }
907    if d.pos != bytes.len() {
908        return Err(protocol("trailing bytes after the body"));
909    }
910    Ok(out)
911}
912
913// ---------------------------------------------------------------------------
914// Messages
915// ---------------------------------------------------------------------------
916
917/// The four kinds of D-Bus message.
918#[derive(Clone, Copy, Debug, PartialEq, Eq)]
919pub enum MessageType {
920    /// A method call.
921    MethodCall,
922    /// A successful reply.
923    MethodReturn,
924    /// An error reply.
925    Error,
926    /// A signal.
927    Signal,
928}
929
930impl MessageType {
931    fn code(self) -> u8 {
932        match self {
933            MessageType::MethodCall => 1,
934            MessageType::MethodReturn => 2,
935            MessageType::Error => 3,
936            MessageType::Signal => 4,
937        }
938    }
939}
940
941/// One D-Bus message: the header fields this crate understands plus the body. The body's
942/// signature is the concatenation of its values' signatures.
943#[derive(Clone, Debug, PartialEq)]
944pub struct Message {
945    /// The message kind.
946    pub message_type: MessageType,
947    /// `FLAG_*` bits.
948    pub flags: u8,
949    /// The sender-assigned serial, never zero once sent.
950    pub serial: u32,
951    /// `PATH`: the object a call targets or a signal comes from.
952    pub path: Option<String>,
953    /// `INTERFACE`.
954    pub interface: Option<String>,
955    /// `MEMBER`: the method or signal name.
956    pub member: Option<String>,
957    /// `ERROR_NAME`, on error replies.
958    pub error_name: Option<String>,
959    /// `REPLY_SERIAL`, on replies.
960    pub reply_serial: Option<u32>,
961    /// `DESTINATION`.
962    pub destination: Option<String>,
963    /// `SENDER`, filled in by the bus.
964    pub sender: Option<String>,
965    /// The arguments.
966    pub body: Vec<Value>,
967}
968
969impl Message {
970    fn empty(message_type: MessageType) -> Message {
971        Message {
972            message_type,
973            flags: 0,
974            serial: 0,
975            path: None,
976            interface: None,
977            member: None,
978            error_name: None,
979            reply_serial: None,
980            destination: None,
981            sender: None,
982            body: Vec::new(),
983        }
984    }
985
986    /// A method call to `member` of `interface` on object `path` of `destination`.
987    #[must_use]
988    pub fn method_call(
989        destination: &str,
990        path: &str,
991        interface: &str,
992        member: &str,
993        body: Vec<Value>,
994    ) -> Message {
995        Message {
996            path: Some(path.to_owned()),
997            interface: Some(interface.to_owned()),
998            member: Some(member.to_owned()),
999            destination: Some(destination.to_owned()),
1000            body,
1001            ..Message::empty(MessageType::MethodCall)
1002        }
1003    }
1004
1005    /// A broadcast signal `member` of `interface` from object `path`.
1006    #[must_use]
1007    pub fn signal(path: &str, interface: &str, member: &str, body: Vec<Value>) -> Message {
1008        Message {
1009            path: Some(path.to_owned()),
1010            interface: Some(interface.to_owned()),
1011            member: Some(member.to_owned()),
1012            body,
1013            ..Message::empty(MessageType::Signal)
1014        }
1015    }
1016
1017    fn reply_to(call: &Message, body: Vec<Value>) -> Message {
1018        Message {
1019            reply_serial: Some(call.serial),
1020            destination: call.sender.clone(),
1021            flags: FLAG_NO_REPLY_EXPECTED,
1022            body,
1023            ..Message::empty(MessageType::MethodReturn)
1024        }
1025    }
1026
1027    fn error_to(call: &Message, name: &str, text: &str) -> Message {
1028        Message {
1029            reply_serial: Some(call.serial),
1030            destination: call.sender.clone(),
1031            error_name: Some(name.to_owned()),
1032            flags: FLAG_NO_REPLY_EXPECTED,
1033            body: vec![Value::str(text)],
1034            ..Message::empty(MessageType::Error)
1035        }
1036    }
1037
1038    /// The body signature.
1039    #[must_use]
1040    pub fn signature(&self) -> String {
1041        let mut s = String::new();
1042        for v in &self.body {
1043            v.write_signature(&mut s);
1044        }
1045        s
1046    }
1047
1048    /// Serializes the message in little-endian byte order.
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns [`Error::Protocol`] when a header field the message type requires is missing or
1053    /// invalid, or when the body cannot be marshaled.
1054    pub fn encode(&self) -> Result<Vec<u8>, Error> {
1055        self.encode_with(false)
1056    }
1057
1058    fn encode_with(&self, big: bool) -> Result<Vec<u8>, Error> {
1059        self.check_fields()?;
1060        let mut body = Encoder::new(big);
1061        for v in &self.body {
1062            body.value(v, 0)?;
1063        }
1064        let sig = self.signature();
1065        validate_signature(&sig)?;
1066
1067        let field = |code: u8, v: Value| Value::Struct(vec![Value::Byte(code), Value::variant(v)]);
1068        let mut fields = Vec::new();
1069        if let Some(p) = &self.path {
1070            fields.push(field(1, Value::path(p)));
1071        }
1072        if let Some(s) = &self.interface {
1073            fields.push(field(2, Value::str(s)));
1074        }
1075        if let Some(s) = &self.member {
1076            fields.push(field(3, Value::str(s)));
1077        }
1078        if let Some(s) = &self.error_name {
1079            fields.push(field(4, Value::str(s)));
1080        }
1081        if let Some(n) = self.reply_serial {
1082            fields.push(field(5, Value::U32(n)));
1083        }
1084        if let Some(s) = &self.destination {
1085            fields.push(field(6, Value::str(s)));
1086        }
1087        if let Some(s) = &self.sender {
1088            fields.push(field(7, Value::str(s)));
1089        }
1090        if !sig.is_empty() {
1091            fields.push(field(8, Value::Signature(sig)));
1092        }
1093
1094        let mut e = Encoder::new(big);
1095        e.buf.extend_from_slice(&[
1096            if big { b'B' } else { b'l' },
1097            self.message_type.code(),
1098            self.flags,
1099            1,
1100        ]);
1101        let body_len = u32::try_from(body.buf.len()).map_err(|_| protocol("body too long"))?;
1102        e.u32(body_len);
1103        e.u32(self.serial);
1104        e.value(&Value::array("(yv)", fields), 0)?;
1105        e.pad(8);
1106        e.buf.extend_from_slice(&body.buf);
1107        if e.buf.len() > MAX_MESSAGE {
1108            return Err(protocol("message longer than 128 MiB"));
1109        }
1110        Ok(e.buf)
1111    }
1112
1113    fn check_fields(&self) -> Result<(), Error> {
1114        let missing = |what: &str| protocol(format!("{:?} without {what}", self.message_type));
1115        match self.message_type {
1116            MessageType::MethodCall => {
1117                if self.path.is_none() {
1118                    return Err(missing("a path"));
1119                }
1120                if self.member.is_none() {
1121                    return Err(missing("a member"));
1122                }
1123            }
1124            MessageType::Signal => {
1125                if self.path.is_none() || self.interface.is_none() || self.member.is_none() {
1126                    return Err(missing("a path, interface and member"));
1127                }
1128            }
1129            MessageType::Error => {
1130                if self.error_name.is_none() || self.reply_serial.is_none() {
1131                    return Err(missing("an error name and reply serial"));
1132                }
1133            }
1134            MessageType::MethodReturn => {
1135                if self.reply_serial.is_none() {
1136                    return Err(missing("a reply serial"));
1137                }
1138            }
1139        }
1140        if let Some(p) = &self.path
1141            && !is_valid_object_path(p)
1142        {
1143            return Err(protocol(format!("invalid object path {p:?}")));
1144        }
1145        if let Some(i) = &self.interface
1146            && !is_valid_interface(i)
1147        {
1148            return Err(protocol(format!("invalid interface name {i:?}")));
1149        }
1150        if let Some(e) = &self.error_name
1151            && !is_valid_interface(e)
1152        {
1153            return Err(protocol(format!("invalid error name {e:?}")));
1154        }
1155        if let Some(m) = &self.member
1156            && !is_valid_member(m)
1157        {
1158            return Err(protocol(format!("invalid member name {m:?}")));
1159        }
1160        if let Some(d) = &self.destination
1161            && !is_valid_bus_name(d)
1162        {
1163            return Err(protocol(format!("invalid bus name {d:?}")));
1164        }
1165        Ok(())
1166    }
1167
1168    /// Parses one complete message of either byte order. `bytes` must hold exactly that one
1169    /// message, with no trailing data.
1170    ///
1171    /// # Errors
1172    ///
1173    /// Returns [`Error::Protocol`] when `bytes` is not one well-formed message.
1174    pub fn decode(bytes: &[u8]) -> Result<Message, Error> {
1175        let big = match bytes.first() {
1176            Some(b'l') => false,
1177            Some(b'B') => true,
1178            _ => return Err(protocol("unknown byte order mark")),
1179        };
1180        let mut d = Decoder {
1181            data: bytes,
1182            pos: 0,
1183            big,
1184        };
1185        let head = d.take(4)?;
1186        let message_type = match head[1] {
1187            1 => MessageType::MethodCall,
1188            2 => MessageType::MethodReturn,
1189            3 => MessageType::Error,
1190            4 => MessageType::Signal,
1191            n => return Err(protocol(format!("unknown message type {n}"))),
1192        };
1193        if head[3] != 1 {
1194            return Err(protocol(format!(
1195                "unsupported protocol version {}",
1196                head[3]
1197            )));
1198        }
1199        let mut msg = Message::empty(message_type);
1200        msg.flags = head[2];
1201        let body_len = d.u32()? as usize;
1202        msg.serial = d.u32()?;
1203        let fields = d.value("a(yv)", 0)?;
1204        let mut signature = String::new();
1205        for field in fields.as_array().unwrap_or_default() {
1206            let Some([Value::Byte(code), Value::Variant(v)]) = field.as_struct() else {
1207                continue;
1208            };
1209            let text = || v.as_str().map(str::to_owned);
1210            match code {
1211                1 => msg.path = text(),
1212                2 => msg.interface = text(),
1213                3 => msg.member = text(),
1214                4 => msg.error_name = text(),
1215                5 => {
1216                    if let Value::U32(n) = **v {
1217                        msg.reply_serial = Some(n);
1218                    }
1219                }
1220                6 => msg.destination = text(),
1221                7 => msg.sender = text(),
1222                8 => signature = text().unwrap_or_default(),
1223                9 => {
1224                    if matches!(**v, Value::U32(n) if n > 0) {
1225                        return Err(protocol("unix fds were not negotiated"));
1226                    }
1227                }
1228                _ => {}
1229            }
1230        }
1231        d.align(8)?;
1232        if d.data.len() - d.pos != body_len {
1233            return Err(protocol("body length does not match the header"));
1234        }
1235        let mut rest = signature.as_str();
1236        while !rest.is_empty() {
1237            let (first, tail) = split_first_type(rest)?;
1238            msg.body.push(d.value(first, 0)?);
1239            rest = tail;
1240        }
1241        if d.pos != bytes.len() {
1242            return Err(protocol("body shorter than its length"));
1243        }
1244        Ok(msg)
1245    }
1246}
1247
1248/// Reads one whole message's bytes from `r` using the fixed header's lengths.
1249fn read_frame(r: &mut dyn Read) -> io::Result<Vec<u8>> {
1250    let mut buf = vec![0u8; 16];
1251    r.read_exact(&mut buf)?;
1252    let word = |at: usize| {
1253        let b = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]];
1254        match buf[0] {
1255            b'l' => Ok(u32::from_le_bytes(b) as usize),
1256            b'B' => Ok(u32::from_be_bytes(b) as usize),
1257            _ => Err(io::Error::new(
1258                io::ErrorKind::InvalidData,
1259                "unknown byte order mark",
1260            )),
1261        }
1262    };
1263    let body_len = word(4)?;
1264    let fields_len = word(12)?;
1265    if fields_len > MAX_MESSAGE || body_len > MAX_MESSAGE {
1266        return Err(io::Error::new(
1267            io::ErrorKind::InvalidData,
1268            "message too long",
1269        ));
1270    }
1271    let total = (16 + fields_len).next_multiple_of(8) + body_len;
1272    if total > MAX_MESSAGE {
1273        return Err(io::Error::new(
1274            io::ErrorKind::InvalidData,
1275            "message too long",
1276        ));
1277    }
1278    buf.resize(total, 0);
1279    r.read_exact(&mut buf[16..])?;
1280    Ok(buf)
1281}
1282
1283// ---------------------------------------------------------------------------
1284// Authentication and Hello
1285// ---------------------------------------------------------------------------
1286
1287fn read_line(s: &mut dyn Read) -> Result<String, Error> {
1288    let mut line = Vec::new();
1289    let mut byte = [0u8; 1];
1290    while !line.ends_with(b"\r\n") {
1291        if line.len() > 1024 {
1292            return Err(Error::Auth("overlong reply line".into()));
1293        }
1294        if s.read(&mut byte)? == 0 {
1295            return Err(Error::Disconnected);
1296        }
1297        line.push(byte[0]);
1298    }
1299    line.truncate(line.len() - 2);
1300    String::from_utf8(line).map_err(|_| Error::Auth("reply is not text".into()))
1301}
1302
1303/// The SASL `EXTERNAL` handshake. With a uid the client names itself; without one (where the uid
1304/// cannot be read without libc) it sends empty data and lets the server use the socket
1305/// credentials, which every bus implementation accepts.
1306#[cfg_attr(
1307    not(unix),
1308    allow(dead_code, reason = "only unix transports authenticate")
1309)]
1310fn authenticate<S: Read + Write>(s: &mut S, uid: Option<u32>) -> Result<(), Error> {
1311    use std::fmt::Write as _;
1312    s.write_all(b"\0")?;
1313    match uid {
1314        Some(uid) => {
1315            let hex = uid.to_string().bytes().fold(String::new(), |mut hex, b| {
1316                let _ = write!(hex, "{b:02x}");
1317                hex
1318            });
1319            s.write_all(format!("AUTH EXTERNAL {hex}\r\n").as_bytes())?;
1320        }
1321        None => s.write_all(b"AUTH EXTERNAL\r\n")?,
1322    }
1323    let mut reply = read_line(s)?;
1324    if reply == "DATA" || reply.starts_with("DATA ") {
1325        s.write_all(b"DATA\r\n")?;
1326        reply = read_line(s)?;
1327    }
1328    if !(reply == "OK" || reply.starts_with("OK ")) {
1329        let _ = s.write_all(b"CANCEL\r\n");
1330        return Err(Error::Auth(reply));
1331    }
1332    s.write_all(b"BEGIN\r\n")?;
1333    s.flush()?;
1334    Ok(())
1335}
1336
1337/// The calling user's uid, read without libc where `/proc` offers it.
1338#[cfg_attr(
1339    not(unix),
1340    allow(dead_code, reason = "only unix transports authenticate")
1341)]
1342fn current_uid() -> Option<u32> {
1343    #[cfg(any(target_os = "linux", target_os = "android"))]
1344    {
1345        use std::os::unix::fs::MetadataExt;
1346        std::fs::metadata("/proc/self").ok().map(|m| m.uid())
1347    }
1348    #[cfg(not(any(target_os = "linux", target_os = "android")))]
1349    {
1350        None
1351    }
1352}
1353
1354// ---------------------------------------------------------------------------
1355// Connection
1356// ---------------------------------------------------------------------------
1357
1358/// A method call delivered to an exported object.
1359#[derive(Clone, Debug)]
1360pub struct MethodCall {
1361    /// The connection the call arrived on, for emitting signals from a handler.
1362    pub connection: Connection,
1363    /// The object path called.
1364    pub path: String,
1365    /// The interface named by the caller, if any (it is optional in the protocol).
1366    pub interface: Option<String>,
1367    /// The method name.
1368    pub member: String,
1369    /// The arguments.
1370    pub args: Vec<Value>,
1371    /// The caller's unique bus name.
1372    pub sender: Option<String>,
1373}
1374
1375/// A D-Bus error a handler answers with.
1376#[derive(Clone, Debug, PartialEq, Eq)]
1377pub struct MethodError {
1378    /// The error name, such as `org.freedesktop.DBus.Error.InvalidArgs`.
1379    pub name: String,
1380    /// A human-readable message.
1381    pub message: String,
1382}
1383
1384impl MethodError {
1385    /// An error with any valid error name.
1386    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
1387        MethodError {
1388            name: name.into(),
1389            message: message.into(),
1390        }
1391    }
1392
1393    /// `org.freedesktop.DBus.Error.UnknownMethod`.
1394    #[must_use]
1395    pub fn unknown_method(call: &MethodCall) -> Self {
1396        MethodError::new(
1397            "org.freedesktop.DBus.Error.UnknownMethod",
1398            format!(
1399                "no method {}.{} on {}",
1400                call.interface.as_deref().unwrap_or("*"),
1401                call.member,
1402                call.path
1403            ),
1404        )
1405    }
1406
1407    /// `org.freedesktop.DBus.Error.InvalidArgs`.
1408    pub fn invalid_args(message: impl Into<String>) -> Self {
1409        MethodError::new("org.freedesktop.DBus.Error.InvalidArgs", message)
1410    }
1411
1412    /// `org.freedesktop.DBus.Error.UnknownProperty`.
1413    #[must_use]
1414    pub fn unknown_property(name: &str) -> Self {
1415        MethodError::new(
1416            "org.freedesktop.DBus.Error.UnknownProperty",
1417            format!("no property {name}"),
1418        )
1419    }
1420
1421    /// `org.freedesktop.DBus.Error.Failed`.
1422    pub fn failed(message: impl Into<String>) -> Self {
1423        MethodError::new("org.freedesktop.DBus.Error.Failed", message)
1424    }
1425
1426    fn is_unknown_method(&self) -> bool {
1427        self.name == "org.freedesktop.DBus.Error.UnknownMethod"
1428    }
1429}
1430
1431/// Which signals a callback registered with [`Connection::on_signal`] receives. Unset fields
1432/// match anything. This filters locally; the bus only sends signals a match rule asked for
1433/// ([`Connection::add_match`]).
1434#[derive(Clone, Debug, Default, PartialEq, Eq)]
1435#[must_use]
1436pub struct SignalFilter {
1437    /// The sender's bus name, compared literally (signals carry the unique name, except the
1438    /// bus's own, which carry `org.freedesktop.DBus`).
1439    pub sender: Option<String>,
1440    /// The emitting object path.
1441    pub path: Option<String>,
1442    /// The signal's interface.
1443    pub interface: Option<String>,
1444    /// The signal's name.
1445    pub member: Option<String>,
1446}
1447
1448impl SignalFilter {
1449    /// A filter matching every signal.
1450    pub fn new() -> Self {
1451        Self::default()
1452    }
1453
1454    /// Restricts to one sender.
1455    pub fn sender(mut self, sender: &str) -> Self {
1456        self.sender = Some(sender.to_owned());
1457        self
1458    }
1459
1460    /// Restricts to one object path.
1461    pub fn path(mut self, path: &str) -> Self {
1462        self.path = Some(path.to_owned());
1463        self
1464    }
1465
1466    /// Restricts to one interface.
1467    pub fn interface(mut self, interface: &str) -> Self {
1468        self.interface = Some(interface.to_owned());
1469        self
1470    }
1471
1472    /// Restricts to one signal name.
1473    pub fn member(mut self, member: &str) -> Self {
1474        self.member = Some(member.to_owned());
1475        self
1476    }
1477
1478    fn matches(&self, m: &Message) -> bool {
1479        let field = |want: &Option<String>, have: &Option<String>| {
1480            want.as_ref().is_none_or(|w| have.as_ref() == Some(w))
1481        };
1482        field(&self.sender, &m.sender)
1483            && field(&self.path, &m.path)
1484            && field(&self.interface, &m.interface)
1485            && field(&self.member, &m.member)
1486    }
1487}
1488
1489/// Identifies a signal subscription for [`Connection::remove_signal_handler`].
1490#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1491pub struct SubscriptionId(u64);
1492
1493type HandlerFn = dyn Fn(&MethodCall) -> Result<Vec<Value>, MethodError> + Send + Sync;
1494type SignalFn = dyn Fn(&Connection, &Message) + Send + Sync;
1495
1496struct State {
1497    closed: bool,
1498    pending: HashMap<u32, mpsc::Sender<Message>>,
1499    objects: HashMap<String, Arc<HandlerFn>>,
1500    signals: Vec<(SubscriptionId, SignalFilter, Arc<SignalFn>)>,
1501    next_subscription: u64,
1502}
1503
1504struct Inner {
1505    writer: Mutex<Box<dyn Write + Send>>,
1506    /// Shuts the socket down, which ends the reader thread's blocking read.
1507    close: Box<dyn Fn() + Send + Sync>,
1508    serial: AtomicU32,
1509    unique_name: String,
1510    state: Mutex<State>,
1511    reader: OnceLock<ThreadId>,
1512}
1513
1514impl Drop for Inner {
1515    fn drop(&mut self) {
1516        (self.close)();
1517    }
1518}
1519
1520fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
1521    // A handler that panicked while another thread held a lock leaves plain data behind; the
1522    // connection keeps working rather than spreading the panic.
1523    m.lock().unwrap_or_else(PoisonError::into_inner)
1524}
1525
1526/// A connection to a message bus. Cloning is cheap and every clone shares the socket and the
1527/// reader thread; the socket closes when the last clone drops (or on [`close`](Self::close)).
1528///
1529/// Exported handlers and signal callbacks that capture a clone keep the connection alive, so a
1530/// long-lived owner calls [`unexport`](Self::unexport) / [`remove_signal_handler`](Self::remove_signal_handler)
1531/// or [`close`](Self::close) when done. Handlers receive the connection in [`MethodCall`] and
1532/// signal callbacks as an argument, so they rarely need to capture one.
1533#[derive(Clone)]
1534pub struct Connection {
1535    inner: Arc<Inner>,
1536}
1537
1538impl fmt::Debug for Connection {
1539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1540        f.debug_struct("Connection")
1541            .field("unique_name", &self.inner.unique_name)
1542            .field("closed", &self.is_closed())
1543            .finish()
1544    }
1545}
1546
1547impl Connection {
1548    /// Connects to the session bus named by `DBUS_SESSION_BUS_ADDRESS`, or to
1549    /// `$XDG_RUNTIME_DIR/bus` when the variable is unset.
1550    ///
1551    /// # Errors
1552    ///
1553    /// Returns [`Error::NoBus`] when neither variable names a usable address, and otherwise the
1554    /// errors of [`connect`](Self::connect).
1555    pub fn session() -> Result<Connection, Error> {
1556        if let Some(address) = std::env::var_os("DBUS_SESSION_BUS_ADDRESS")
1557            && !address.is_empty()
1558        {
1559            let address = address
1560                .into_string()
1561                .map_err(|_| Error::NoBus("DBUS_SESSION_BUS_ADDRESS is not UTF-8".into()))?;
1562            return Connection::connect(&address);
1563        }
1564        let runtime = std::env::var_os("XDG_RUNTIME_DIR")
1565            .filter(|d| !d.is_empty())
1566            .ok_or_else(|| {
1567                Error::NoBus("neither DBUS_SESSION_BUS_ADDRESS nor XDG_RUNTIME_DIR is set".into())
1568            })?;
1569        let path = std::path::Path::new(&runtime).join("bus");
1570        let path = path
1571            .to_str()
1572            .ok_or_else(|| Error::NoBus("XDG_RUNTIME_DIR is not UTF-8".into()))?;
1573        Connection::connect(&format!("unix:path={}", escape_address(path)))
1574    }
1575
1576    /// Connects to a bus at a D-Bus server address such as `unix:path=/run/user/1000/bus`.
1577    /// Several `;`-separated addresses are tried in order.
1578    ///
1579    /// # Errors
1580    ///
1581    /// Returns [`Error::Unsupported`] off unix, [`Error::NoBus`] or [`Error::Io`] when no
1582    /// address can be connected to, [`Error::Auth`] when the bus refuses authentication, and
1583    /// [`Error::Io`] or [`Error::Protocol`] when the opening exchange fails.
1584    pub fn connect(address: &str) -> Result<Connection, Error> {
1585        #[cfg(unix)]
1586        {
1587            let stream = unix::connect_address(address)?;
1588            Connection::from_unix_stream(stream)
1589        }
1590        #[cfg(not(unix))]
1591        {
1592            let _ = address;
1593            Err(Error::Unsupported)
1594        }
1595    }
1596
1597    #[cfg(unix)]
1598    fn from_unix_stream(mut stream: std::os::unix::net::UnixStream) -> Result<Connection, Error> {
1599        use std::net::Shutdown;
1600        // The handshake is bounded; the reader thread later blocks without a timeout.
1601        stream.set_read_timeout(Some(Duration::from_secs(10)))?;
1602        authenticate(&mut stream, current_uid())?;
1603        let reader = stream.try_clone()?;
1604        let closer = stream.try_clone()?;
1605        let mut hello_reader = stream.try_clone()?;
1606        let unique_name = hello(&mut stream, &mut hello_reader)?;
1607        stream.set_read_timeout(None)?;
1608        Connection::start(
1609            Box::new(reader),
1610            Box::new(stream),
1611            Box::new(move || {
1612                let _ = closer.shutdown(Shutdown::Both);
1613            }),
1614            unique_name,
1615        )
1616    }
1617
1618    /// Wraps an authenticated, `Hello`-ed transport and starts its reader thread.
1619    #[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
1620    fn start(
1621        reader: Box<dyn Read + Send>,
1622        writer: Box<dyn Write + Send>,
1623        close: Box<dyn Fn() + Send + Sync>,
1624        unique_name: String,
1625    ) -> Result<Connection, Error> {
1626        let inner = Arc::new(Inner {
1627            writer: Mutex::new(writer),
1628            close,
1629            // Serial 1 was the Hello.
1630            serial: AtomicU32::new(2),
1631            unique_name,
1632            state: Mutex::new(State {
1633                closed: false,
1634                pending: HashMap::new(),
1635                objects: HashMap::new(),
1636                signals: Vec::new(),
1637                next_subscription: 1,
1638            }),
1639            reader: OnceLock::new(),
1640        });
1641        let weak = Arc::downgrade(&inner);
1642        let handle = thread::Builder::new()
1643            .name("day-platform-linux".into())
1644            .spawn(move || reader_loop(reader, &weak))?;
1645        let _ = inner.reader.set(handle.thread().id());
1646        Ok(Connection { inner })
1647    }
1648
1649    /// This connection's unique bus name, such as `:1.42`.
1650    #[must_use]
1651    pub fn unique_name(&self) -> &str {
1652        &self.inner.unique_name
1653    }
1654
1655    /// Whether the connection has closed (the bus went away, or [`close`](Self::close)).
1656    #[must_use]
1657    pub fn is_closed(&self) -> bool {
1658        lock(&self.inner.state).closed
1659    }
1660
1661    /// Closes the socket. Pending and later calls fail with [`Error::Disconnected`], and the
1662    /// reader thread exits.
1663    pub fn close(&self) {
1664        mark_closed(&self.inner);
1665        (self.inner.close)();
1666    }
1667
1668    fn next_serial(&self) -> u32 {
1669        loop {
1670            let s = self.inner.serial.fetch_add(1, Ordering::Relaxed);
1671            if s != 0 {
1672                return s;
1673            }
1674        }
1675    }
1676
1677    /// Sends `msg` with a fresh serial, returning that serial.
1678    ///
1679    /// # Errors
1680    ///
1681    /// Returns [`Error::Disconnected`] when the connection is closed, [`Error::Protocol`] when
1682    /// `msg` cannot be encoded, and [`Error::Io`] when the write fails.
1683    pub fn send(&self, mut msg: Message) -> Result<u32, Error> {
1684        if self.is_closed() {
1685            return Err(Error::Disconnected);
1686        }
1687        msg.serial = self.next_serial();
1688        let bytes = msg.encode()?;
1689        self.write(&bytes)?;
1690        Ok(msg.serial)
1691    }
1692
1693    fn write(&self, bytes: &[u8]) -> Result<(), Error> {
1694        let mut w = lock(&self.inner.writer);
1695        w.write_all(bytes)?;
1696        w.flush()?;
1697        Ok(())
1698    }
1699
1700    /// Calls a method and waits up to [`DEFAULT_TIMEOUT`] for its reply's arguments.
1701    ///
1702    /// # Errors
1703    ///
1704    /// Returns the errors of [`call_with_timeout`](Self::call_with_timeout).
1705    pub fn call(
1706        &self,
1707        destination: &str,
1708        path: &str,
1709        interface: &str,
1710        member: &str,
1711        args: &[Value],
1712    ) -> Result<Vec<Value>, Error> {
1713        self.call_with_timeout(destination, path, interface, member, args, DEFAULT_TIMEOUT)
1714    }
1715
1716    /// [`call`](Self::call) with an explicit timeout.
1717    ///
1718    /// # Errors
1719    ///
1720    /// Returns [`Error::ReaderThread`] when called from the reader thread, [`Error::Remote`]
1721    /// when the peer answers with an error, [`Error::Timeout`] when no reply arrives in time,
1722    /// [`Error::Disconnected`] when the connection closes first, and [`Error::Protocol`] or
1723    /// [`Error::Io`] when the call cannot be encoded or written.
1724    pub fn call_with_timeout(
1725        &self,
1726        destination: &str,
1727        path: &str,
1728        interface: &str,
1729        member: &str,
1730        args: &[Value],
1731        timeout: Duration,
1732    ) -> Result<Vec<Value>, Error> {
1733        if self.inner.reader.get() == Some(&thread::current().id()) {
1734            return Err(Error::ReaderThread);
1735        }
1736        let mut msg = Message::method_call(destination, path, interface, member, args.to_vec());
1737        msg.serial = self.next_serial();
1738        let bytes = msg.encode()?;
1739        let (tx, rx) = mpsc::channel();
1740        {
1741            let mut state = lock(&self.inner.state);
1742            if state.closed {
1743                return Err(Error::Disconnected);
1744            }
1745            state.pending.insert(msg.serial, tx);
1746        }
1747        if let Err(e) = self.write(&bytes) {
1748            lock(&self.inner.state).pending.remove(&msg.serial);
1749            return Err(e);
1750        }
1751        match rx.recv_timeout(timeout) {
1752            Ok(reply) if reply.message_type == MessageType::Error => Err(Error::Remote {
1753                name: reply.error_name.unwrap_or_default(),
1754                message: reply
1755                    .body
1756                    .first()
1757                    .and_then(Value::as_str)
1758                    .unwrap_or_default()
1759                    .to_owned(),
1760            }),
1761            Ok(reply) => Ok(reply.body),
1762            Err(mpsc::RecvTimeoutError::Timeout) => {
1763                lock(&self.inner.state).pending.remove(&msg.serial);
1764                Err(Error::Timeout)
1765            }
1766            Err(mpsc::RecvTimeoutError::Disconnected) => Err(Error::Disconnected),
1767        }
1768    }
1769
1770    /// Calls a method without waiting, asking the peer not to reply. Safe from handlers.
1771    ///
1772    /// # Errors
1773    ///
1774    /// Returns the errors of [`send`](Self::send).
1775    pub fn call_no_reply(
1776        &self,
1777        destination: &str,
1778        path: &str,
1779        interface: &str,
1780        member: &str,
1781        args: &[Value],
1782    ) -> Result<(), Error> {
1783        let mut msg = Message::method_call(destination, path, interface, member, args.to_vec());
1784        msg.flags |= FLAG_NO_REPLY_EXPECTED;
1785        self.send(msg).map(|_| ())
1786    }
1787
1788    /// Broadcasts a signal.
1789    ///
1790    /// # Errors
1791    ///
1792    /// Returns the errors of [`send`](Self::send).
1793    pub fn emit_signal(
1794        &self,
1795        path: &str,
1796        interface: &str,
1797        member: &str,
1798        args: &[Value],
1799    ) -> Result<(), Error> {
1800        self.send(Message::signal(path, interface, member, args.to_vec()))
1801            .map(|_| ())
1802    }
1803
1804    fn bus_call(&self, member: &str, args: &[Value]) -> Result<Vec<Value>, Error> {
1805        self.call(BUS_NAME, BUS_PATH, BUS_INTERFACE, member, args)
1806    }
1807
1808    /// Asks the bus for a well-known name; returns a `NAME_REPLY_*` code.
1809    ///
1810    /// # Errors
1811    ///
1812    /// Returns the errors of [`call`](Self::call), and [`Error::Protocol`] when the bus's reply
1813    /// carries no code.
1814    pub fn request_name(&self, name: &str, flags: u32) -> Result<u32, Error> {
1815        let reply = self.bus_call("RequestName", &[Value::str(name), Value::U32(flags)])?;
1816        match reply.first() {
1817            Some(Value::U32(code)) => Ok(*code),
1818            _ => Err(protocol("RequestName returned no code")),
1819        }
1820    }
1821
1822    /// Gives a well-known name back without waiting for the bus's answer.
1823    ///
1824    /// # Errors
1825    ///
1826    /// Returns the errors of [`send`](Self::send).
1827    pub fn release_name(&self, name: &str) -> Result<(), Error> {
1828        self.call_no_reply(
1829            BUS_NAME,
1830            BUS_PATH,
1831            BUS_INTERFACE,
1832            "ReleaseName",
1833            &[Value::str(name)],
1834        )
1835    }
1836
1837    /// Whether some connection owns `name`; `false` when the bus cannot be asked.
1838    #[must_use]
1839    pub fn name_has_owner(&self, name: &str) -> bool {
1840        matches!(
1841            self.bus_call("NameHasOwner", &[Value::str(name)])
1842                .as_deref(),
1843            Ok([Value::Bool(true)])
1844        )
1845    }
1846
1847    /// Asks the bus to route messages matching `rule` (such as
1848    /// `type='signal',interface='org.example.Iface'`) to this connection.
1849    ///
1850    /// # Errors
1851    ///
1852    /// Returns the errors of [`call`](Self::call).
1853    pub fn add_match(&self, rule: &str) -> Result<(), Error> {
1854        self.bus_call("AddMatch", &[Value::str(rule)]).map(|_| ())
1855    }
1856
1857    /// Withdraws a rule added with [`add_match`](Self::add_match), without waiting.
1858    ///
1859    /// # Errors
1860    ///
1861    /// Returns the errors of [`send`](Self::send).
1862    pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
1863        self.call_no_reply(
1864            BUS_NAME,
1865            BUS_PATH,
1866            BUS_INTERFACE,
1867            "RemoveMatch",
1868            &[Value::str(rule)],
1869        )
1870    }
1871
1872    /// Calls `callback` on the reader thread for every incoming signal that `filter` matches.
1873    pub fn on_signal<F>(&self, filter: SignalFilter, callback: F) -> SubscriptionId
1874    where
1875        F: Fn(&Connection, &Message) + Send + Sync + 'static,
1876    {
1877        let mut state = lock(&self.inner.state);
1878        let id = SubscriptionId(state.next_subscription);
1879        state.next_subscription += 1;
1880        state.signals.push((id, filter, Arc::new(callback)));
1881        id
1882    }
1883
1884    /// Removes a subscription made with [`on_signal`](Self::on_signal).
1885    pub fn remove_signal_handler(&self, id: SubscriptionId) {
1886        lock(&self.inner.state).signals.retain(|(s, ..)| *s != id);
1887    }
1888
1889    /// Answers method calls on object `path` with `handler`, which runs on the reader thread.
1890    ///
1891    /// The connection answers `org.freedesktop.DBus.Peer` itself. For
1892    /// `org.freedesktop.DBus.Introspectable.Introspect` it asks the handler first and, when the
1893    /// handler answers `UnknownMethod`, replies with a minimal document listing the standard
1894    /// interfaces and any exported child objects ([`introspection_xml`] builds a handler's own).
1895    ///
1896    /// # Errors
1897    ///
1898    /// Returns [`Error::Protocol`] when `path` is not a valid object path or is already
1899    /// exported.
1900    pub fn export<F>(&self, path: &str, handler: F) -> Result<(), Error>
1901    where
1902        F: Fn(&MethodCall) -> Result<Vec<Value>, MethodError> + Send + Sync + 'static,
1903    {
1904        if !is_valid_object_path(path) {
1905            return Err(protocol(format!("invalid object path {path:?}")));
1906        }
1907        let mut state = lock(&self.inner.state);
1908        if state.objects.contains_key(path) {
1909            return Err(protocol(format!("{path} is already exported")));
1910        }
1911        state.objects.insert(path.to_owned(), Arc::new(handler));
1912        Ok(())
1913    }
1914
1915    /// Stops answering calls on `path`.
1916    pub fn unexport(&self, path: &str) {
1917        lock(&self.inner.state).objects.remove(path);
1918    }
1919}
1920
1921#[cfg(unix)]
1922mod unix {
1923    use super::Error;
1924    use std::io;
1925    use std::os::unix::net::UnixStream;
1926
1927    /// Decodes a D-Bus address value's `%XX` escapes.
1928    fn unescape(value: &str) -> Vec<u8> {
1929        let bytes = value.as_bytes();
1930        let mut out = Vec::with_capacity(bytes.len());
1931        let mut i = 0;
1932        while i < bytes.len() {
1933            let hex = bytes
1934                .get(i + 1..i + 3)
1935                .and_then(|h| std::str::from_utf8(h).ok())
1936                .and_then(|h| u8::from_str_radix(h, 16).ok());
1937            match (bytes[i], hex) {
1938                (b'%', Some(b)) => {
1939                    out.push(b);
1940                    i += 3;
1941                }
1942                (b, _) => {
1943                    out.push(b);
1944                    i += 1;
1945                }
1946            }
1947        }
1948        out
1949    }
1950
1951    pub(super) fn connect_address(address: &str) -> Result<UnixStream, Error> {
1952        use std::ffi::OsStr;
1953        use std::os::unix::ffi::OsStrExt;
1954
1955        let mut last = Error::NoBus(format!("no unix transport in {address:?}"));
1956        for entry in address.split(';').filter(|e| !e.is_empty()) {
1957            let Some(("unix", params)) = entry.split_once(':') else {
1958                continue;
1959            };
1960            let param = |key: &str| {
1961                params.split(',').find_map(|kv| {
1962                    kv.split_once('=')
1963                        .filter(|(k, _)| *k == key)
1964                        .map(|(_, v)| unescape(v))
1965                })
1966            };
1967            let result = if let Some(path) = param("path") {
1968                UnixStream::connect(OsStr::from_bytes(&path))
1969            } else if let Some(name) = param("abstract") {
1970                connect_abstract(&name)
1971            } else {
1972                continue;
1973            };
1974            match result {
1975                Ok(stream) => return Ok(stream),
1976                Err(e) => last = Error::Io(e),
1977            }
1978        }
1979        Err(last)
1980    }
1981
1982    #[cfg(any(target_os = "linux", target_os = "android"))]
1983    fn connect_abstract(name: &[u8]) -> io::Result<UnixStream> {
1984        #[cfg(target_os = "android")]
1985        use std::os::android::net::SocketAddrExt;
1986        #[cfg(target_os = "linux")]
1987        use std::os::linux::net::SocketAddrExt;
1988        let addr = std::os::unix::net::SocketAddr::from_abstract_name(name)?;
1989        UnixStream::connect_addr(&addr)
1990    }
1991
1992    #[cfg(not(any(target_os = "linux", target_os = "android")))]
1993    fn connect_abstract(_name: &[u8]) -> io::Result<UnixStream> {
1994        Err(io::Error::new(
1995            io::ErrorKind::Unsupported,
1996            "abstract unix sockets exist only on Linux",
1997        ))
1998    }
1999}
2000
2001/// Escapes a path for a D-Bus address value.
2002fn escape_address(value: &str) -> String {
2003    value
2004        .bytes()
2005        .map(|b| {
2006            if b.is_ascii_alphanumeric() || b"-_/.\\*".contains(&b) {
2007                char::from(b).to_string()
2008            } else {
2009                format!("%{b:02x}")
2010            }
2011        })
2012        .collect()
2013}
2014
2015/// Sends `Hello` (serial 1) and waits for the unique name it returns.
2016#[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
2017fn hello(w: &mut dyn Write, r: &mut dyn Read) -> Result<String, Error> {
2018    let mut msg = Message::method_call(BUS_NAME, BUS_PATH, BUS_INTERFACE, "Hello", Vec::new());
2019    msg.serial = 1;
2020    w.write_all(&msg.encode()?)?;
2021    w.flush()?;
2022    loop {
2023        let reply = Message::decode(&read_frame(r)?)?;
2024        if reply.reply_serial != Some(1) {
2025            continue;
2026        }
2027        if reply.message_type == MessageType::Error {
2028            return Err(Error::Remote {
2029                name: reply.error_name.unwrap_or_default(),
2030                message: String::new(),
2031            });
2032        }
2033        return match reply.body.first() {
2034            Some(Value::Str(name)) => Ok(name.clone()),
2035            _ => Err(protocol("Hello returned no name")),
2036        };
2037    }
2038}
2039
2040fn mark_closed(inner: &Inner) {
2041    let mut state = lock(&inner.state);
2042    state.closed = true;
2043    // Dropping the senders wakes every waiting call with `Disconnected`.
2044    state.pending.clear();
2045}
2046
2047#[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
2048fn reader_loop(mut reader: Box<dyn Read + Send>, weak: &Weak<Inner>) {
2049    loop {
2050        let frame = read_frame(&mut *reader);
2051        let Some(inner) = weak.upgrade() else {
2052            return;
2053        };
2054        let Ok(bytes) = frame else {
2055            mark_closed(&inner);
2056            return;
2057        };
2058        let conn = Connection { inner };
2059        // A message that frames correctly but does not parse is dropped; the stream stays in
2060        // step because framing only needs the fixed header.
2061        if let Ok(msg) = Message::decode(&bytes) {
2062            dispatch(&conn, msg);
2063        }
2064    }
2065}
2066
2067fn dispatch(conn: &Connection, msg: Message) {
2068    match msg.message_type {
2069        MessageType::MethodReturn | MessageType::Error => {
2070            let Some(serial) = msg.reply_serial else {
2071                return;
2072            };
2073            let waiter = lock(&conn.inner.state).pending.remove(&serial);
2074            if let Some(tx) = waiter {
2075                let _ = tx.send(msg);
2076            }
2077        }
2078        MessageType::Signal => {
2079            let callbacks: Vec<Arc<SignalFn>> = lock(&conn.inner.state)
2080                .signals
2081                .iter()
2082                .filter(|(_, filter, _)| filter.matches(&msg))
2083                .map(|(_, _, cb)| cb.clone())
2084                .collect();
2085            for cb in callbacks {
2086                cb(conn, &msg);
2087            }
2088        }
2089        MessageType::MethodCall => {
2090            let reply = answer(conn, &msg);
2091            if msg.flags & FLAG_NO_REPLY_EXPECTED != 0 {
2092                return;
2093            }
2094            let out = match reply {
2095                Ok(body) => Message::reply_to(&msg, body),
2096                Err(e) => Message::error_to(&msg, &e.name, &e.message),
2097            };
2098            let out = match out.encode() {
2099                Ok(_) => out,
2100                // A handler's reply that cannot be marshaled becomes an error reply, so the
2101                // caller is not left waiting.
2102                Err(e) => Message::error_to(
2103                    &msg,
2104                    "org.freedesktop.DBus.Error.Failed",
2105                    &format!("reply could not be sent: {e}"),
2106                ),
2107            };
2108            let _ = conn.send(out);
2109        }
2110    }
2111}
2112
2113fn answer(conn: &Connection, msg: &Message) -> Result<Vec<Value>, MethodError> {
2114    let path = msg.path.clone().unwrap_or_default();
2115    let member = msg.member.clone().unwrap_or_default();
2116    let interface = msg.interface.as_deref();
2117    if interface == Some(PEER_INTERFACE) {
2118        return match member.as_str() {
2119            "Ping" => Ok(Vec::new()),
2120            "GetMachineId" => machine_id()
2121                .map(|id| vec![Value::Str(id)])
2122                .ok_or_else(|| MethodError::failed("no machine id")),
2123            _ => Err(MethodError::new(
2124                "org.freedesktop.DBus.Error.UnknownMethod",
2125                format!("no method {PEER_INTERFACE}.{member}"),
2126            )),
2127        };
2128    }
2129    let introspect =
2130        member == "Introspect" && interface.is_none_or(|i| i == INTROSPECTABLE_INTERFACE);
2131    let handler = lock(&conn.inner.state).objects.get(&path).cloned();
2132    let call = MethodCall {
2133        connection: conn.clone(),
2134        path: path.clone(),
2135        interface: msg.interface.clone(),
2136        member,
2137        args: msg.body.clone(),
2138        sender: msg.sender.clone(),
2139    };
2140    if let Some(handler) = handler {
2141        match handler(&call) {
2142            Err(e) if introspect && e.is_unknown_method() => Ok(vec![Value::Str(
2143                introspection_xml("", &children(conn, &path)),
2144            )]),
2145            other => other,
2146        }
2147    } else {
2148        let kids = children(conn, &path);
2149        if introspect && !kids.is_empty() {
2150            Ok(vec![Value::Str(introspection_xml("", &kids))])
2151        } else {
2152            Err(MethodError::new(
2153                "org.freedesktop.DBus.Error.UnknownObject",
2154                format!("no object at {path}"),
2155            ))
2156        }
2157    }
2158}
2159
2160/// The names of exported objects directly or indirectly below `path`, one segment deep.
2161fn children(conn: &Connection, path: &str) -> Vec<String> {
2162    let prefix = if path == "/" {
2163        "/".to_owned()
2164    } else {
2165        format!("{path}/")
2166    };
2167    let names: BTreeSet<String> = lock(&conn.inner.state)
2168        .objects
2169        .keys()
2170        .filter_map(|p| p.strip_prefix(&prefix))
2171        .filter_map(|rest| rest.split('/').next())
2172        .filter(|seg| !seg.is_empty())
2173        .map(str::to_owned)
2174        .collect();
2175    names.into_iter().collect()
2176}
2177
2178fn machine_id() -> Option<String> {
2179    ["/etc/machine-id", "/var/lib/dbus/machine-id"]
2180        .iter()
2181        .find_map(|p| std::fs::read_to_string(p).ok())
2182        .map(|s| s.trim().to_owned())
2183        .filter(|s| !s.is_empty())
2184}
2185
2186/// An introspection document: the standard `Peer` and `Introspectable` interfaces, then
2187/// `interfaces` (raw `<interface>` elements), then a `<node>` per child name.
2188#[must_use]
2189pub fn introspection_xml(interfaces: &str, children: &[String]) -> String {
2190    use std::fmt::Write as _;
2191    let mut xml = String::from(
2192        "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n \
2193         \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n<node>\n \
2194         <interface name=\"org.freedesktop.DBus.Peer\">\n  <method name=\"Ping\"/>\n  \
2195         <method name=\"GetMachineId\"><arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/></method>\n \
2196         </interface>\n <interface name=\"org.freedesktop.DBus.Introspectable\">\n  \
2197         <method name=\"Introspect\"><arg type=\"s\" name=\"xml_data\" direction=\"out\"/></method>\n \
2198         </interface>\n",
2199    );
2200    xml.push_str(interfaces);
2201    for child in children {
2202        let _ = writeln!(xml, " <node name=\"{child}\"/>");
2203    }
2204    xml.push_str("</node>\n");
2205    xml
2206}
2207
2208// ---------------------------------------------------------------------------
2209// Unity launcher entry
2210// ---------------------------------------------------------------------------
2211
2212/// The Unity `LauncherEntry` protocol: a badge count, a progress bar and an urgency flag on the
2213/// app's dock or launcher icon. Docks (Ubuntu Dock, Dash to Dock, Plasma's task manager,
2214/// Latte, Plank) listen for the `Update` signal and match it to the app by its desktop id.
2215pub mod launcher {
2216    use super::{Connection, Error, Value};
2217
2218    /// The interface the signal belongs to.
2219    pub const INTERFACE: &str = "com.canonical.Unity.LauncherEntry";
2220
2221    /// The launcher state to show. Each update states all of it: `None` hides the count or the
2222    /// progress bar and clears urgency.
2223    #[derive(Clone, Copy, Debug, Default, PartialEq)]
2224    pub struct LauncherProps {
2225        /// The badge number.
2226        pub count: Option<i64>,
2227        /// Progress from 0.0 to 1.0 (clamped).
2228        pub progress: Option<f64>,
2229        /// Whether the icon asks for attention.
2230        pub urgent: Option<bool>,
2231    }
2232
2233    /// The object path the signal is sent from: one per desktop id, as libunity does.
2234    #[must_use]
2235    pub fn object_path(desktop_id: &str) -> String {
2236        // FNV-1a, so the path is stable and valid whatever characters the id holds.
2237        let hash = desktop_id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
2238            (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
2239        });
2240        format!("/com/canonical/unity/launcherentry/{hash}")
2241    }
2242
2243    /// Emits `com.canonical.Unity.LauncherEntry.Update` for `desktop_id` (the desktop file's
2244    /// name, with or without `.desktop`).
2245    ///
2246    /// # Errors
2247    ///
2248    /// Returns the errors of [`Connection::emit_signal`].
2249    pub fn update(conn: &Connection, desktop_id: &str, props: LauncherProps) -> Result<(), Error> {
2250        let id = desktop_id.strip_suffix(".desktop").unwrap_or(desktop_id);
2251        let uri = format!("application://{id}.desktop");
2252        let entries = vec![
2253            ("count", Value::I64(props.count.unwrap_or(0))),
2254            ("count-visible", Value::Bool(props.count.is_some())),
2255            (
2256                "progress",
2257                Value::Double(props.progress.unwrap_or(0.0).clamp(0.0, 1.0)),
2258            ),
2259            ("progress-visible", Value::Bool(props.progress.is_some())),
2260            ("urgent", Value::Bool(props.urgent.unwrap_or(false))),
2261        ];
2262        conn.emit_signal(
2263            &object_path(id),
2264            INTERFACE,
2265            "Update",
2266            &[Value::Str(uri), Value::props(entries)],
2267        )
2268    }
2269}
2270
2271// ---------------------------------------------------------------------------
2272// Single-instance forwarding
2273// ---------------------------------------------------------------------------
2274
2275/// Single-instance apps over the session bus, for backends whose toolkit does not provide it
2276/// (GTK has `GApplication`; Qt has nothing).
2277///
2278/// The first process to [`claim`](instance::claim) an app id owns a bus name derived from it and
2279/// exports `/dev/daybrite/Instance`. A later launch finds the name taken, forwards its
2280/// command-line arguments to the owner through `dev.daybrite.Instance.Forward(as)`, and gets
2281/// [`Claimed::Forwarded`](instance::Claimed::Forwarded) back, at which point it exits. Reusing
2282/// the app id as the bus name is safe because a process runs one toolkit, so it never also holds
2283/// GTK's `GApplication` name.
2284pub mod instance {
2285    use super::{
2286        Connection, Error, INTROSPECTABLE_INTERFACE, MethodError, NAME_FLAG_DO_NOT_QUEUE,
2287        NAME_REPLY_ALREADY_OWNER, NAME_REPLY_EXISTS, NAME_REPLY_PRIMARY_OWNER, Value,
2288        introspection_xml,
2289    };
2290    use std::fmt;
2291
2292    /// The object the owning instance exports.
2293    pub const PATH: &str = "/dev/daybrite/Instance";
2294    /// The interface of [`PATH`], with the one method `Forward(as)`.
2295    pub const INTERFACE: &str = "dev.daybrite.Instance";
2296
2297    const XML: &str = " <interface name=\"dev.daybrite.Instance\">\n  \
2298        <method name=\"Forward\"><arg type=\"as\" name=\"args\" direction=\"in\"/></method>\n \
2299        </interface>\n";
2300
2301    /// Why [`claim`] did not make this process the owner.
2302    #[derive(Debug)]
2303    pub enum Claimed {
2304        /// Another instance owns the app id and received this launch's arguments; this process
2305        /// should exit.
2306        Forwarded,
2307        /// There is no usable session bus, or the owner did not take the arguments (it hung, or
2308        /// it is not a Day instance). This process runs as an ordinary, unclaimed instance.
2309        NoBus(Error),
2310    }
2311
2312    impl fmt::Display for Claimed {
2313        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2314            match self {
2315                Claimed::Forwarded => f.write_str("forwarded to the running instance"),
2316                Claimed::NoBus(e) => write!(f, "single-instance claim unavailable: {e}"),
2317            }
2318        }
2319    }
2320
2321    impl std::error::Error for Claimed {
2322        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2323            match self {
2324                Claimed::Forwarded => None,
2325                Claimed::NoBus(e) => Some(e),
2326            }
2327        }
2328    }
2329
2330    /// This process's ownership of an app id. Dropping it releases the name, so the next
2331    /// launch becomes the owner.
2332    #[derive(Debug)]
2333    pub struct Claim {
2334        conn: Connection,
2335        name: String,
2336    }
2337
2338    impl Claim {
2339        /// The bus name owned.
2340        #[must_use]
2341        pub fn name(&self) -> &str {
2342            &self.name
2343        }
2344
2345        /// The connection holding the name.
2346        #[must_use]
2347        pub fn connection(&self) -> &Connection {
2348            &self.conn
2349        }
2350    }
2351
2352    impl Drop for Claim {
2353        fn drop(&mut self) {
2354            self.conn.unexport(PATH);
2355            let _ = self.conn.release_name(&self.name);
2356        }
2357    }
2358
2359    /// Turns an app id into a legal well-known bus name: characters outside `[A-Za-z0-9_-]`
2360    /// become `_`, an element that is empty or starts with a digit gains a leading `_`, an id
2361    /// with a single element is put under `dev.daybrite.instance.`, and an overlong one is
2362    /// replaced by a hash under that prefix.
2363    #[must_use]
2364    pub fn bus_name(app_id: &str) -> String {
2365        let elements: Vec<String> = app_id
2366            .split('.')
2367            .map(|el| {
2368                let mut out: String = el
2369                    .chars()
2370                    .map(|c| {
2371                        if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
2372                            c
2373                        } else {
2374                            '_'
2375                        }
2376                    })
2377                    .collect();
2378                if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
2379                    out.insert(0, '_');
2380                }
2381                out
2382            })
2383            .collect();
2384        let name = if elements.len() < 2 {
2385            format!("dev.daybrite.instance.{}", elements.join("."))
2386        } else {
2387            elements.join(".")
2388        };
2389        if name.len() <= 255 {
2390            return name;
2391        }
2392        let hash = app_id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
2393            (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
2394        });
2395        format!("dev.daybrite.instance.h{hash:016x}")
2396    }
2397
2398    /// Whether a failed `Forward` means the owner went away between `RequestName` and the call.
2399    fn owner_vanished(e: &Error) -> bool {
2400        match e {
2401            Error::Remote { name, .. } => matches!(
2402                name.as_str(),
2403                "org.freedesktop.DBus.Error.ServiceUnknown"
2404                    | "org.freedesktop.DBus.Error.NameHasNoOwner"
2405                    | "org.freedesktop.DBus.Error.NoReply"
2406            ),
2407            _ => false,
2408        }
2409    }
2410
2411    /// Claims `app_id` for this process, or forwards `args` (normally
2412    /// `std::env::args().skip(1)`) to the process that already holds it.
2413    ///
2414    /// `on_forward` receives each later launch's arguments **on the connection's reader
2415    /// thread**; the caller hands them to its UI thread (for example through its platform's
2416    /// post-to-main mechanism) rather than touching UI state there. It must not block for long:
2417    /// the forwarding process waits for it to return.
2418    ///
2419    /// # Errors
2420    ///
2421    /// Returns [`Claimed::Forwarded`] when a running instance took `args`, and
2422    /// [`Claimed::NoBus`] when the session bus cannot be used or the owner did not take them.
2423    #[expect(
2424        clippy::needless_pass_by_value,
2425        reason = "public signature; callers pass the argument list they collected for this launch"
2426    )]
2427    pub fn claim<F>(app_id: &str, args: Vec<String>, on_forward: F) -> Result<Claim, Claimed>
2428    where
2429        F: Fn(Vec<String>) + Send + Sync + 'static,
2430    {
2431        let conn = Connection::session().map_err(Claimed::NoBus)?;
2432        let name = bus_name(app_id);
2433        // Export before owning the name, so a launch that sees the name always finds the
2434        // object behind it.
2435        conn.export(PATH, move |call| {
2436            match (call.interface.as_deref(), call.member.as_str()) {
2437                (Some(INTERFACE) | None, "Forward") => {
2438                    let [Value::Array { elem, items }] = call.args.as_slice() else {
2439                        return Err(MethodError::invalid_args("expected (as)"));
2440                    };
2441                    if elem != "s" {
2442                        return Err(MethodError::invalid_args("expected (as)"));
2443                    }
2444                    on_forward(
2445                        items
2446                            .iter()
2447                            .filter_map(|v| v.as_str().map(str::to_owned))
2448                            .collect(),
2449                    );
2450                    Ok(Vec::new())
2451                }
2452                (Some(INTROSPECTABLE_INTERFACE) | None, "Introspect") => {
2453                    Ok(vec![Value::Str(introspection_xml(XML, &[]))])
2454                }
2455                _ => Err(MethodError::unknown_method(call)),
2456            }
2457        })
2458        .map_err(Claimed::NoBus)?;
2459        let forwarded = Value::strings(&args);
2460        let mut last = Error::Disconnected;
2461        // One retry: the owner can exit between our RequestName and our Forward.
2462        for _ in 0..2 {
2463            match conn.request_name(&name, NAME_FLAG_DO_NOT_QUEUE) {
2464                Ok(NAME_REPLY_PRIMARY_OWNER | NAME_REPLY_ALREADY_OWNER) => {
2465                    return Ok(Claim { conn, name });
2466                }
2467                Ok(NAME_REPLY_EXISTS) => {}
2468                Ok(code) => {
2469                    last = Error::Protocol(format!("RequestName answered {code}"));
2470                    break;
2471                }
2472                Err(e) => {
2473                    last = e;
2474                    break;
2475                }
2476            }
2477            match conn.call(
2478                &name,
2479                PATH,
2480                INTERFACE,
2481                "Forward",
2482                std::slice::from_ref(&forwarded),
2483            ) {
2484                Ok(_) => {
2485                    conn.unexport(PATH);
2486                    return Err(Claimed::Forwarded);
2487                }
2488                Err(e) if owner_vanished(&e) => last = e,
2489                Err(e) => {
2490                    last = e;
2491                    break;
2492                }
2493            }
2494        }
2495        conn.unexport(PATH);
2496        Err(Claimed::NoBus(last))
2497    }
2498}
2499
2500// ---------------------------------------------------------------------------
2501// Tests
2502// ---------------------------------------------------------------------------
2503
2504#[cfg(test)]
2505mod tests {
2506    use super::*;
2507
2508    fn round_trip(values: &[Value]) {
2509        let sig: String = values.iter().map(Value::signature).collect();
2510        let bytes = marshal(values).expect("marshal");
2511        assert_eq!(unmarshal(&bytes, &sig, false).expect("unmarshal"), values);
2512        let mut e = Encoder::new(true);
2513        for v in values {
2514            e.value(v, 0).expect("marshal big-endian");
2515        }
2516        assert_eq!(unmarshal(&e.buf, &sig, true).expect("unmarshal BE"), values);
2517    }
2518
2519    #[test]
2520    fn every_basic_type_round_trips() {
2521        round_trip(&[
2522            Value::Byte(0xab),
2523            Value::Bool(true),
2524            Value::Bool(false),
2525            Value::I16(-2),
2526            Value::U16(65535),
2527            Value::I32(-70000),
2528            Value::U32(0xdead_beef),
2529            Value::I64(i64::MIN),
2530            Value::U64(u64::MAX),
2531            Value::Double(-1.5),
2532            Value::str("héllo"),
2533            Value::str(""),
2534            Value::path("/org/example/Obj_1"),
2535            Value::Signature("a{sv}(iiay)".into()),
2536        ]);
2537    }
2538
2539    #[test]
2540    fn containers_round_trip() {
2541        round_trip(&[
2542            Value::Struct(vec![
2543                Value::I32(1),
2544                Value::str("x"),
2545                Value::bytes(&[1, 2, 3]),
2546            ]),
2547            Value::props([("a", Value::U32(7)), ("b", Value::strings(&["p", "q"]))]),
2548            Value::dict("i", "s", [(Value::I32(3), Value::str("three"))]),
2549            Value::array(
2550                "(iiay)",
2551                vec![Value::Struct(vec![
2552                    Value::I32(2),
2553                    Value::I32(2),
2554                    Value::bytes(&[0; 16]),
2555                ])],
2556            ),
2557        ]);
2558    }
2559
2560    #[test]
2561    fn struct_after_a_byte_is_padded_to_eight() {
2562        let values = vec![Value::Byte(1), Value::Struct(vec![Value::Byte(2)])];
2563        let bytes = marshal(&values).expect("marshal");
2564        assert_eq!(bytes, [1, 0, 0, 0, 0, 0, 0, 0, 2]);
2565        round_trip(&values);
2566    }
2567
2568    #[test]
2569    fn empty_arrays_still_pad_to_their_element_alignment() {
2570        // y, then a(ii): length at 4, padding to 8, no elements.
2571        let values = vec![Value::Byte(9), Value::array("(ii)", Vec::new())];
2572        let bytes = marshal(&values).expect("marshal");
2573        assert_eq!(bytes, [9, 0, 0, 0, 0, 0, 0, 0]);
2574        round_trip(&values);
2575        // a{sv} after a u32 lands its length at 4 and is padded to 8 too.
2576        let values = vec![Value::U32(1), Value::props(Vec::<(&str, Value)>::new())];
2577        assert_eq!(marshal(&values).expect("marshal").len(), 8);
2578        round_trip(&values);
2579        // An empty array of bytes needs no padding after its length.
2580        let values = vec![Value::Byte(1), Value::bytes(&[]), Value::Byte(2)];
2581        assert_eq!(
2582            marshal(&values).expect("marshal"),
2583            [1, 0, 0, 0, 0, 0, 0, 0, 2]
2584        );
2585        round_trip(&values);
2586    }
2587
2588    #[test]
2589    fn array_length_excludes_the_leading_padding() {
2590        // a(i) holding one struct: length 4, padding to 8, then the i32.
2591        let bytes = marshal(&[Value::array(
2592            "(i)",
2593            vec![Value::Struct(vec![Value::I32(5)])],
2594        )])
2595        .expect("marshal");
2596        assert_eq!(bytes, [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0]);
2597    }
2598
2599    #[test]
2600    fn nested_variants_round_trip() {
2601        let deep = Value::variant(Value::variant(Value::variant(Value::Struct(vec![
2602            Value::Byte(1),
2603            Value::variant(Value::array("v", vec![Value::variant(Value::I64(-1))])),
2604        ]))));
2605        assert_eq!(deep.signature(), "v");
2606        round_trip(&[Value::Byte(7), deep]);
2607    }
2608
2609    #[test]
2610    fn mismatched_array_items_are_rejected() {
2611        let bad = Value::array("s", vec![Value::I32(1)]);
2612        assert!(marshal(&[bad]).is_err());
2613        assert!(marshal(&[Value::path("no/slash")]).is_err());
2614        assert!(marshal(&[Value::Struct(Vec::new())]).is_err());
2615    }
2616
2617    #[test]
2618    fn malformed_input_is_an_error_not_a_panic() {
2619        assert!(unmarshal(&[1, 0, 0, 0], "b", false).is_ok());
2620        assert!(unmarshal(&[2, 0, 0, 0], "b", false).is_err());
2621        assert!(unmarshal(&[0xff, 0xff, 0xff, 0x0f], "ay", false).is_err());
2622        assert!(unmarshal(&[3, 0, 0, 0, b'a', b'b'], "s", false).is_err());
2623        assert!(unmarshal(&[], "a{vs}", false).is_err());
2624        assert!(Message::decode(b"x").is_err());
2625        for len in 0..40 {
2626            let _ = Message::decode(&vec![b'l'; len]);
2627        }
2628    }
2629
2630    #[test]
2631    fn signatures_parse() {
2632        assert_eq!(split_first_type("a{sv}i").expect("split"), ("a{sv}", "i"));
2633        assert_eq!(
2634            split_first_type("(ia(s))x").expect("split"),
2635            ("(ia(s))", "x")
2636        );
2637        for bad in ["(", "()", "a", "a{vs}", "a{s}", "a{sss}", "z", "(i"] {
2638            assert!(validate_signature(bad).is_err(), "{bad}");
2639        }
2640    }
2641
2642    /// `Hello` (serial 1), assembled by hand from the specification's marshaling rules: the
2643    /// path, interface, member and destination header fields each 8-aligned, an empty body, no
2644    /// signature field, and the header padded to 128 bytes.
2645    #[test]
2646    fn hello_matches_the_spec_bytes() {
2647        let mut hello =
2648            Message::method_call(BUS_NAME, BUS_PATH, BUS_INTERFACE, "Hello", Vec::new());
2649        hello.serial = 1;
2650        let mut want: Vec<u8> = Vec::new();
2651        // l, METHOD_CALL, no flags, version 1; body length 0; serial 1; fields length 0x6d.
2652        want.extend_from_slice(&[b'l', 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0x6d, 0, 0, 0]);
2653        // PATH (1) 'o' "/org/freedesktop/DBus" (21 bytes) at 16.
2654        want.extend_from_slice(&[1, 1, b'o', 0, 21, 0, 0, 0]);
2655        want.extend_from_slice(b"/org/freedesktop/DBus\0");
2656        want.extend_from_slice(&[0, 0]); // to 48
2657        // INTERFACE (2) 's' "org.freedesktop.DBus" (20 bytes) at 48.
2658        want.extend_from_slice(&[2, 1, b's', 0, 20, 0, 0, 0]);
2659        want.extend_from_slice(b"org.freedesktop.DBus\0");
2660        want.extend_from_slice(&[0, 0, 0]); // to 80
2661        // MEMBER (3) 's' "Hello" at 80.
2662        want.extend_from_slice(&[3, 1, b's', 0, 5, 0, 0, 0]);
2663        want.extend_from_slice(b"Hello\0");
2664        want.extend_from_slice(&[0, 0]); // to 96
2665        // DESTINATION (6) 's' "org.freedesktop.DBus" at 96, ending at 125.
2666        want.extend_from_slice(&[6, 1, b's', 0, 20, 0, 0, 0]);
2667        want.extend_from_slice(b"org.freedesktop.DBus\0");
2668        want.extend_from_slice(&[0, 0, 0]); // header padded to 128
2669        assert_eq!(want.len(), 128);
2670        assert_eq!(hello.encode().expect("encode"), want);
2671        assert_eq!(Message::decode(&want).expect("decode"), hello);
2672    }
2673
2674    #[test]
2675    fn big_endian_header_parses() {
2676        // A signal written by hand in big-endian order:
2677        // B, SIGNAL, flags 0, version 1; body length 4; serial 7.
2678        let mut m: Vec<u8> = vec![b'B', 4, 0, 1, 0, 0, 0, 4, 0, 0, 0, 7];
2679        let mut fields: Vec<u8> = Vec::new();
2680        // PATH "/a" at 16.
2681        fields.extend_from_slice(&[1, 1, b'o', 0, 0, 0, 0, 2, b'/', b'a', 0]);
2682        fields.extend_from_slice(&[0, 0, 0, 0, 0]); // 27 → 32
2683        // INTERFACE "x.y" at 32.
2684        fields.extend_from_slice(&[2, 1, b's', 0, 0, 0, 0, 3, b'x', b'.', b'y', 0]);
2685        fields.extend_from_slice(&[0, 0, 0, 0]); // 44 → 48
2686        // MEMBER "Z" at 48.
2687        fields.extend_from_slice(&[3, 1, b's', 0, 0, 0, 0, 1, b'Z', 0]);
2688        fields.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // 58 → 64
2689        // SENDER ":1.5" at 64, then SIGNATURE "u" at 80.
2690        fields.extend_from_slice(&[7, 1, b's', 0, 0, 0, 0, 4, b':', b'1', b'.', b'5', 0]);
2691        fields.extend_from_slice(&[0, 0, 0]); // 77 → 80
2692        fields.extend_from_slice(&[8, 1, b'g', 0, 1, b'u', 0]); // ends at 87
2693        let fields_len = fields.len() as u32;
2694        m.extend_from_slice(&fields_len.to_be_bytes());
2695        m.extend_from_slice(&fields);
2696        m.resize(88, 0); // header padded to 8
2697        m.extend_from_slice(&[1, 2, 3, 4]); // body: u32 0x01020304
2698        let msg = Message::decode(&m).expect("decode big-endian");
2699        assert_eq!(msg.message_type, MessageType::Signal);
2700        assert_eq!(msg.serial, 7);
2701        assert_eq!(msg.path.as_deref(), Some("/a"));
2702        assert_eq!(msg.interface.as_deref(), Some("x.y"));
2703        assert_eq!(msg.member.as_deref(), Some("Z"));
2704        assert_eq!(msg.sender.as_deref(), Some(":1.5"));
2705        assert_eq!(msg.body, vec![Value::U32(0x0102_0304)]);
2706        // Framing reads the big-endian lengths too.
2707        let framed = read_frame(&mut &m[..]).expect("frame");
2708        assert_eq!(framed.len(), m.len());
2709        // And our own big-endian encoder agrees byte for byte with the hand-built message.
2710        let mut ours = Message::signal("/a", "x.y", "Z", vec![Value::U32(0x0102_0304)]);
2711        ours.serial = 7;
2712        ours.sender = Some(":1.5".into());
2713        let decoded = Message::decode(&ours.encode_with(true).expect("encode BE")).expect("BE");
2714        assert_eq!(decoded, msg);
2715    }
2716
2717    #[test]
2718    fn auth_sends_uid_as_hex_ascii() {
2719        struct Script {
2720            replies: io::Cursor<Vec<u8>>,
2721            sent: Vec<u8>,
2722        }
2723        impl Read for Script {
2724            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2725                self.replies.read(buf)
2726            }
2727        }
2728        impl Write for Script {
2729            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2730                self.sent.extend_from_slice(buf);
2731                Ok(buf.len())
2732            }
2733            fn flush(&mut self) -> io::Result<()> {
2734                Ok(())
2735            }
2736        }
2737        let mut s = Script {
2738            replies: io::Cursor::new(b"OK 1234deadbeef\r\n".to_vec()),
2739            sent: Vec::new(),
2740        };
2741        authenticate(&mut s, Some(1000)).expect("auth");
2742        assert_eq!(s.sent, b"\0AUTH EXTERNAL 31303030\r\nBEGIN\r\n");
2743
2744        let mut s = Script {
2745            replies: io::Cursor::new(b"DATA\r\nOK 1234\r\n".to_vec()),
2746            sent: Vec::new(),
2747        };
2748        authenticate(&mut s, None).expect("auth without uid");
2749        assert_eq!(s.sent, b"\0AUTH EXTERNAL\r\nDATA\r\nBEGIN\r\n");
2750
2751        let mut s = Script {
2752            replies: io::Cursor::new(b"REJECTED EXTERNAL\r\n".to_vec()),
2753            sent: Vec::new(),
2754        };
2755        std::assert_matches!(authenticate(&mut s, Some(0)), Err(Error::Auth(_)));
2756    }
2757
2758    #[test]
2759    fn instance_bus_names_are_legal() {
2760        use instance::bus_name;
2761        for (id, want) in [
2762            ("dev.daybrite.Notes", "dev.daybrite.Notes"),
2763            ("com.example.my-app", "com.example.my-app"),
2764            ("org.7zip.App", "org._7zip.App"),
2765            ("io.github.user.2048", "io.github.user._2048"),
2766            ("notes", "dev.daybrite.instance.notes"),
2767            ("a..b", "a._.b"),
2768            ("dev.sun rise/x.é", "dev.sun_rise_x._"),
2769            ("", "dev.daybrite.instance._"),
2770        ] {
2771            let name = bus_name(id);
2772            assert_eq!(name, want, "{id:?}");
2773            assert!(is_valid_bus_name(&name), "{name}");
2774        }
2775        let long = format!("dev.daybrite.{}", "x".repeat(300));
2776        let name = bus_name(&long);
2777        assert!(name.len() <= 255 && is_valid_bus_name(&name), "{name}");
2778        assert_eq!(name, bus_name(&long));
2779    }
2780
2781    #[test]
2782    fn launcher_path_is_valid() {
2783        assert!(is_valid_object_path(&launcher::object_path(
2784            "dev.daybrite.Some-App"
2785        )));
2786    }
2787
2788    /// A fake bus on a socket pair: it authenticates, answers `Hello`, echoes one method call,
2789    /// then hangs up, after which calls fail instead of hanging.
2790    #[cfg(unix)]
2791    #[test]
2792    fn connection_calls_and_disconnects() {
2793        use std::os::unix::net::UnixStream;
2794        let (client, mut bus) = UnixStream::pair().expect("pair");
2795        let peer = thread::spawn(move || {
2796            // NUL, then one request per line: AUTH (with or without a uid), DATA, BEGIN.
2797            let mut nul = [0u8];
2798            bus.read_exact(&mut nul).expect("read NUL");
2799            loop {
2800                let line = read_line(&mut bus).expect("read auth line");
2801                match line.as_str() {
2802                    "AUTH EXTERNAL" => bus.write_all(b"DATA\r\n").expect("write"),
2803                    "BEGIN" => break,
2804                    _ => bus.write_all(b"OK 0123456789abcdef\r\n").expect("write"),
2805                }
2806            }
2807            for _ in 0..2 {
2808                let call = Message::decode(&read_frame(&mut bus).expect("frame")).expect("msg");
2809                let name = if call.member.as_deref() == Some("Hello") {
2810                    vec![Value::str(":1.7")]
2811                } else {
2812                    call.body.clone()
2813                };
2814                let mut reply = Message::reply_to(&call, name);
2815                reply.serial = 100 + call.serial;
2816                bus.write_all(&reply.encode().expect("encode"))
2817                    .expect("write");
2818            }
2819            // Leave the third call unanswered and hang up.
2820            let _ = read_frame(&mut bus);
2821        });
2822        let conn = Connection::from_unix_stream(client).expect("connect");
2823        assert_eq!(conn.unique_name(), ":1.7");
2824        let echoed = conn
2825            .call("x.y", "/", "x.y", "Echo", &[Value::str("ping")])
2826            .expect("echo");
2827        assert_eq!(echoed, vec![Value::str("ping")]);
2828        let err = conn.call("x.y", "/", "x.y", "Never", &[]);
2829        std::assert_matches!(err, Err(Error::Disconnected), "{err:?}");
2830        peer.join().expect("peer");
2831        assert!(conn.is_closed());
2832        std::assert_matches!(
2833            conn.emit_signal("/", "x.y", "Z", &[]),
2834            Err(Error::Disconnected)
2835        );
2836    }
2837}