zbus 6.2.0

API for D-Bus communication and its wire format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::{convert::Infallible, error, fmt, io, sync::Arc};

use serde::{de, ser};

#[cfg(feature = "comms")]
use crate::{
    Address, fdo,
    message::{Message, Type},
    names::OwnedErrorName,
};
use crate::{ObjectPath, Signature, names::InterfaceName, wire};

/// The error type for `zbus`.
///
/// The various errors that can be reported by this crate.
#[derive(Clone, Debug)]
#[non_exhaustive]
#[allow(clippy::upper_case_acronyms)]
pub enum Error {
    /// Generic error. All serde errors get transformed into this variant.
    Failure(String),
    /// An I/O error.
    InputOutput(Arc<io::Error>),
    /// Type conversions errors.
    IncorrectType,
    /// Wrapper for [`std::str::Utf8Error`].
    Utf8(std::str::Utf8Error),
    /// Non-0 padding byte(s) encountered.
    PaddingNot0(u8),
    /// The deserialized file descriptor is not in the given FD index.
    UnknownFd,
    /// The provided signature (first argument) was not valid for reading as the requested type.
    /// Details on the expected signatures are in the second argument.
    SignatureMismatch(Signature, String),
    /// Out of bounds range specified.
    OutOfBounds,
    /// The maximum allowed depth for containers in encoding was exceeded.
    MaxDepthExceeded(MaxDepthExceeded),
    /// Error from parsing a signature.
    SignatureParse(wire::signature::Error),
    /// Attempted to create an empty structure (which is not allowed by the D-Bus specification).
    EmptyStructure,
    /// Invalid object path.
    InvalidObjectPath,
    /// An invalid name.
    InvalidName(&'static str),
    /// Invalid conversion from name type `from` to name type `to`.
    InvalidNameConversion {
        /// The name of the name type that was converted from, such as `UniqueName`.
        from: &'static str,
        /// The name of the name type that was converted to, such as `WellKnownName`.
        to: &'static str,
    },
    /// Interface not found.
    InterfaceNotFound,
    /// Invalid D-Bus address.
    Address(String),
    /// Invalid message field.
    InvalidField,
    /// Data too large.
    ExcessData,
    /// Endian signature invalid or doesn't match expectation.
    IncorrectEndian,
    /// Initial handshake error.
    Handshake(String),
    /// Unexpected or incorrect reply.
    InvalidReply,
    /// A D-Bus method error reply.
    ///
    /// An error reply whose name is defined by [`fdo::Error`] is reported as [`Error::FDO`]
    /// instead. This variant is for the names that are not.
    // According to the spec, there can be all kinds of details in D-Bus errors but nobody adds
    // anything more than a string description.
    #[cfg(feature = "comms")]
    MethodError(OwnedErrorName, Option<String>, Message),
    /// A required field is missing in the message headers.
    MissingField,
    /// Invalid D-Bus GUID.
    InvalidGUID,
    /// Unsupported function, or support currently lacking.
    Unsupported,
    /// A [`fdo::Error`] transformed into [`Error`].
    ///
    /// This includes the D-Bus error replies whose name is defined by [`fdo::Error`], such as
    /// `org.freedesktop.DBus.Error.ServiceUnknown`, which becomes [`fdo::Error::ServiceUnknown`].
    #[cfg(feature = "comms")]
    FDO(Box<fdo::Error>),
    /// A [`DBusError`](crate::DBusError) of any other type.
    ///
    /// This is how the failure of a property getter reaches the caller of the
    /// `PropertiesChanged` emission helper that `#[interface]` generates for the property.
    #[cfg(feature = "comms")]
    DBus(Arc<dyn crate::DBusError + Send + Sync>),
    /// The requested name was already claimed by another peer.
    NameTaken,
    /// Invalid [match rule][MR] string.
    ///
    /// [MR]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules
    InvalidMatchRule,
    /// A required parameter was missing.
    MissingParameter(&'static str),
    /// Serial number in the message header is 0 (which is invalid).
    InvalidSerial,
    /// The given interface already exists at the given path.
    InterfaceExists(InterfaceName<'static>, ObjectPath<'static>),
    /// Failed to connect to the D-Bus server at the given address.
    #[cfg(feature = "comms")]
    Connection(
        /// The I/O error that caused the failure.
        Arc<io::Error>,
        /// The address that could not be connected to.
        Box<Address>,
    ),
}

// The wire (de)serializers return this type by value out of deeply recursive calls, so its size
// is on a hot path.
const _: () = assert!(size_of::<Error>() <= 64);

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Failure(s1), Self::Failure(s2)) => s1 == s2,
            (Self::IncorrectType, Self::IncorrectType) => true,
            (Self::Utf8(s), Self::Utf8(o)) => s == o,
            (Self::PaddingNot0(s), Self::PaddingNot0(o)) => s == o,
            (Self::UnknownFd, Self::UnknownFd) => true,
            (Self::SignatureMismatch(p1, e1), Self::SignatureMismatch(p2, e2)) => {
                p1 == p2 && e1 == e2
            }
            (Self::OutOfBounds, Self::OutOfBounds) => true,
            (Self::MaxDepthExceeded(m1), Self::MaxDepthExceeded(m2)) => m1 == m2,
            (Self::SignatureParse(e1), Self::SignatureParse(e2)) => e1 == e2,
            (Self::EmptyStructure, Self::EmptyStructure) => true,
            (Self::InvalidObjectPath, Self::InvalidObjectPath) => true,
            (Self::InvalidName(_), Self::InvalidName(_)) => true,
            (Self::InvalidNameConversion { .. }, Self::InvalidNameConversion { .. }) => true,
            (Self::InterfaceNotFound, Self::InterfaceNotFound) => true,
            (Self::Address(_), Self::Address(_)) => true,
            (Self::InvalidField, Self::InvalidField) => true,
            (Self::ExcessData, Self::ExcessData) => true,
            (Self::IncorrectEndian, Self::IncorrectEndian) => true,
            (Self::Handshake(_), Self::Handshake(_)) => true,
            (Self::InvalidReply, Self::InvalidReply) => true,
            #[cfg(feature = "comms")]
            (Self::MethodError(_, _, _), Self::MethodError(_, _, _)) => true,
            (Self::MissingField, Self::MissingField) => true,
            (Self::InvalidGUID, Self::InvalidGUID) => true,
            (Self::Unsupported, Self::Unsupported) => true,
            #[cfg(feature = "comms")]
            (Self::FDO(s), Self::FDO(o)) => s == o,
            #[cfg(feature = "comms")]
            (Self::DBus(s), Self::DBus(o)) => {
                s.name() == o.name() && s.description() == o.description()
            }
            (Self::NameTaken, Self::NameTaken) => true,
            (Self::InvalidMatchRule, Self::InvalidMatchRule) => true,
            (Self::InvalidSerial, Self::InvalidSerial) => true,
            (Self::InterfaceExists(s1, s2), Self::InterfaceExists(o1, o2)) => s1 == o1 && s2 == o2,
            #[cfg(feature = "comms")]
            (Self::Connection(_, a1), Self::Connection(_, a2)) => a1 == a2,
            // `InputOutput` and `MissingParameter` deliberately fall through: two I/O errors are
            // never considered equal and the parameter name is not a discriminator.
            (_, _) => false,
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::InputOutput(e) => Some(e),
            Error::Utf8(e) => Some(e),
            #[cfg(feature = "comms")]
            Error::FDO(e) => Some(e),
            #[cfg(feature = "comms")]
            Error::DBus(_) => None,
            #[cfg(feature = "comms")]
            Error::Connection(e, _) => Some(e),
            Error::Failure(_) => None,
            Error::IncorrectType => None,
            Error::PaddingNot0(_) => None,
            Error::UnknownFd => None,
            Error::SignatureMismatch(_, _) => None,
            Error::OutOfBounds => None,
            Error::MaxDepthExceeded(_) => None,
            Error::SignatureParse(_) => None,
            Error::EmptyStructure => None,
            Error::InvalidObjectPath => None,
            Error::InvalidName(_) => None,
            Error::InvalidNameConversion { .. } => None,
            Error::InterfaceNotFound => None,
            Error::Address(_) => None,
            Error::InvalidField => None,
            Error::ExcessData => None,
            Error::IncorrectEndian => None,
            Error::Handshake(_) => None,
            Error::InvalidReply => None,
            #[cfg(feature = "comms")]
            Error::MethodError(_, _, _) => None,
            Error::MissingField => None,
            Error::InvalidGUID => None,
            Error::Unsupported => None,
            Error::NameTaken => None,
            Error::InvalidMatchRule => None,
            Error::MissingParameter(_) => None,
            Error::InvalidSerial => None,
            Error::InterfaceExists(_, _) => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Failure(e) => write!(f, "{e}"),
            Error::InputOutput(e) => write!(f, "I/O error: {e}"),
            Error::IncorrectType => write!(f, "incorrect type"),
            Error::Utf8(e) => write!(f, "{e}"),
            Error::PaddingNot0(b) => write!(f, "Unexpected non-0 padding byte `{b}`"),
            Error::UnknownFd => write!(f, "File descriptor not in the given FD index"),
            Error::SignatureMismatch(provided, expected) => write!(
                f,
                "Signature mismatch: got `{provided}`, expected {expected}",
            ),
            Error::OutOfBounds => write!(
                f,
                // FIXME: using the `Debug` impl of `Range` because it doesn't impl `Display`.
                "Out of bounds range specified",
            ),
            Error::MaxDepthExceeded(max) => write!(f, "{max}"),
            Error::SignatureParse(e) => write!(f, "{e}"),
            Error::EmptyStructure => write!(f, "Attempted to create an empty structure"),
            Error::InvalidObjectPath => write!(f, "Invalid object path"),
            Error::InvalidName(s) => write!(f, "{s}"),
            Error::InvalidNameConversion { from, to } => {
                write!(f, "Invalid conversion from `{from}` to `{to}`")
            }
            Error::InterfaceNotFound => write!(f, "Interface not found"),
            Error::Address(e) => write!(f, "address error: {e}"),
            Error::InvalidField => write!(f, "invalid message field"),
            Error::ExcessData => write!(f, "excess data"),
            Error::IncorrectEndian => write!(f, "incorrect endian"),
            Error::Handshake(e) => write!(f, "D-Bus handshake failed: {e}"),
            Error::InvalidReply => write!(f, "Invalid D-Bus method reply"),
            #[cfg(feature = "comms")]
            Error::MethodError(name, detail, _reply) => write!(
                f,
                "{}: {}",
                **name,
                detail.as_ref().map(|s| s.as_str()).unwrap_or("no details")
            ),
            Error::MissingField => write!(f, "A required field is missing from message headers"),
            Error::InvalidGUID => write!(f, "Invalid GUID"),
            Error::Unsupported => write!(f, "Connection support is lacking"),
            #[cfg(feature = "comms")]
            Error::FDO(e) => write!(f, "{e}"),
            #[cfg(feature = "comms")]
            Error::DBus(e) => write!(f, "{e}"),
            Error::NameTaken => write!(f, "name already taken on the bus"),
            Error::InvalidMatchRule => write!(f, "Invalid match rule string"),
            Error::MissingParameter(p) => {
                write!(f, "Parameter `{p}` was not specified but it is required")
            }
            Error::InvalidSerial => write!(f, "Serial number in the message header is 0"),
            Error::InterfaceExists(i, p) => write!(f, "Interface `{i}` already exists at `{p}`"),
            #[cfg(feature = "comms")]
            Error::Connection(e, addr) => write!(f, "failed to connect to `{addr}`: {e}"),
        }
    }
}

impl Error {
    /// A [`SignatureMismatch`](Error::SignatureMismatch) for `signature` where `expected` was
    /// needed.
    ///
    /// The (de)serializers hit this from generic code. Building the error here keeps that error
    /// path out of every instantiation.
    #[cold]
    pub(crate) fn signature_mismatch(signature: &Signature, expected: &str) -> Self {
        Self::SignatureMismatch(signature.clone(), expected.to_string())
    }

    /// A description of the error.
    ///
    /// This is a generic description of the error (if any). For a more detailed description
    /// make use of the [`std::fmt::Display`] implementation, for example, through
    /// [`std::string::ToString`].
    pub fn description(&self) -> Option<&str> {
        match self {
            Error::Failure(e) => Some(e),
            Error::InputOutput(_) => Some("i/o error"),
            Error::IncorrectType => Some("incorrect type"),
            Error::Utf8(_) => Some("invalid UTF-8"),
            Error::PaddingNot0(_) => Some("unexpected non-0 padding byte"),
            Error::UnknownFd => Some("file descriptor not in the given FD index"),
            Error::SignatureMismatch(_, _) => Some("signature mismatch"),
            Error::OutOfBounds => Some("out of bounds range specified"),
            Error::MaxDepthExceeded(_) => Some("maximum allowed container depth exceeded"),
            Error::SignatureParse(_) => Some("invalid signature"),
            Error::EmptyStructure => Some("attempted to create an empty structure"),
            Error::InvalidObjectPath => Some("invalid object path"),
            Error::InvalidName(s) => Some(s),
            Error::InvalidNameConversion { .. } => Some("invalid name conversion"),
            Error::InterfaceNotFound => Some("interface not found"),
            Error::Address(e) => Some(e),
            Error::InvalidField => Some("invalid field"),
            Error::ExcessData => Some("excess data"),
            Error::IncorrectEndian => Some("incorrect endian"),
            Error::Handshake(e) => Some(e),
            Error::InvalidReply => Some("invalid reply"),
            #[cfg(feature = "comms")]
            Error::MethodError(_, desc, _) => desc.as_deref(),
            #[cfg(feature = "comms")]
            Error::DBus(e) => e.description(),
            Error::MissingField => Some("a required field is missing from message headers"),
            Error::InvalidGUID => Some("invalid GUID"),
            Error::Unsupported => Some("connection support is lacking"),
            #[cfg(feature = "comms")]
            Error::FDO(_) => Some("FDO error"),
            Error::NameTaken => Some("name already taken on the bus"),
            Error::InvalidMatchRule => Some("invalid match rule string"),
            Error::MissingParameter(_) => Some("A required parameter is missing"),
            Error::InvalidSerial => Some("serial number in the message header is 0"),
            Error::InterfaceExists(_, _) => Some("interface already exists"),
            #[cfg(feature = "comms")]
            Error::Connection(_, _) => Some("could not connect to specified address"),
        }
    }
}

impl de::Error for Error {
    // TODO: Add more specific error variants to Error enum above so we can implement other methods
    // here too.
    fn custom<T>(msg: T) -> Error
    where
        T: fmt::Display,
    {
        Error::Failure(msg.to_string())
    }
}

impl ser::Error for Error {
    fn custom<T>(msg: T) -> Error
    where
        T: fmt::Display,
    {
        Error::Failure(msg.to_string())
    }
}

impl From<io::Error> for Error {
    fn from(val: io::Error) -> Self {
        Error::InputOutput(Arc::new(val))
    }
}

impl From<wire::signature::Error> for Error {
    fn from(e: wire::signature::Error) -> Self {
        Error::SignatureParse(e)
    }
}

impl From<Infallible> for Error {
    fn from(i: Infallible) -> Self {
        match i {}
    }
}

#[cfg(feature = "comms")]
impl From<fdo::Error> for Error {
    fn from(val: fdo::Error) -> Self {
        match val {
            fdo::Error::ZBus(e) => e,
            e => Error::FDO(Box::new(e)),
        }
    }
}

// For messages that are D-Bus error returns
#[cfg(feature = "comms")]
impl From<Message> for Error {
    fn from(message: Message) -> Error {
        // FIXME: Instead of checking this, we should have Method as trait and specific types for
        // each message type.
        let header = message.header();
        if header.primary().msg_type() != Type::Error {
            return Error::InvalidReply;
        }

        if let Some(name) = header.error_name() {
            let name: OwnedErrorName = name.to_owned().into();
            let detail: Option<String> = message
                .body()
                .deserialize_ignore_signature::<&str>()
                .ok()
                .map(String::from);
            let method_error = Error::MethodError(name, detail, message);

            // The conversion through `fdo::Error` is always attempted. A name defined by
            // `fdo::Error` becomes the matching `fdo::Error` variant, wrapped in `Error::FDO`. Any
            // other name falls through `fdo::Error::ZBus`, which `From<fdo::Error>` unwraps back
            // into the original `Error::MethodError`.
            Error::from(fdo::Error::from(method_error))
        } else {
            Error::InvalidReply
        }
    }
}

/// Enum representing the max depth exceeded error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaxDepthExceeded {
    /// The maximum allowed depth for structures in encoding was exceeded.
    Structure,
    /// The maximum allowed depth for arrays in encoding was exceeded.
    Array,
    /// The maximum allowed depth for containers in encoding was exceeded.
    Container,
}

impl fmt::Display for MaxDepthExceeded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Structure => write!(
                f,
                "Maximum allowed depth for structures in encoding was exceeded"
            ),
            Self::Array => write!(
                f,
                "Maximum allowed depth for arrays in encoding was exceeded"
            ),
            Self::Container => write!(
                f,
                "Maximum allowed depth for containers in encoding was exceeded"
            ),
        }
    }
}

/// Alias for a `Result` with the error type `zbus::Error`.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(all(test, feature = "comms"))]
mod tests {
    use crate::{Error, fdo, message::Message};

    #[test]
    fn error_reply_with_fdo_name() {
        let error = error_reply(
            "org.freedesktop.DBus.Error.ServiceUnknown",
            &"no such service",
        );

        assert_eq!(
            error,
            Error::FDO(Box::new(fdo::Error::ServiceUnknown(
                "no such service".to_string()
            ))),
        );
    }

    #[test]
    fn error_reply_with_fdo_name_and_no_description() {
        // An empty body has no description to deserialize.
        let error = error_reply("org.freedesktop.DBus.Error.ServiceUnknown", &());

        assert_eq!(
            error,
            Error::FDO(Box::new(fdo::Error::ServiceUnknown(String::new()))),
        );
    }

    #[test]
    fn error_reply_with_other_name() {
        let error = error_reply("org.example.Error.Oops", &"oops");

        let Error::MethodError(name, detail, _) = error else {
            panic!("expected `Error::MethodError`, got {error:?}");
        };
        assert_eq!(name.as_str(), "org.example.Error.Oops");
        assert_eq!(detail.as_deref(), Some("oops"));
    }

    fn error_reply<B>(name: &str, body: &B) -> Error
    where
        B: serde::Serialize + crate::DynamicType,
    {
        let call = Message::method_call("/", "foo")
            .destination(":1.2")
            .build(&())
            .unwrap();

        Message::error(&call.header(), name)
            .build(body)
            .unwrap()
            .into()
    }
}