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