zbus/connection/handshake/
auth_mechanism.rs

1use std::{fmt, str::FromStr};
2
3use crate::{Error, Result};
4
5/// Authentication mechanisms
6///
7/// Note that the `DBUS_COOKIE_SHA1` mechanism is not supported by zbus since version 5.0. The
8/// reasons are:
9///
10/// * It drags the `sha1` crate as a dependency, which can be [problematic for some users].
11/// * It makes the handshake more complex, now allowing use to pipeline all the commands.
12/// * It's not widely used. If `EXTERNAL` is not an option, you might as well just use `ANONYMOUS`.
13///
14/// See <https://dbus.freedesktop.org/doc/dbus-specification.html#auth-mechanisms>
15///
16/// [problematic for some users]: https://github.com/dbus2/zbus/issues/543
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum AuthMechanism {
19    /// This is the recommended authentication mechanism on platforms where credentials can be
20    /// transferred out-of-band, in particular Unix platforms that can perform credentials-passing
21    /// over the `unix:` transport.
22    External,
23
24    /// Does not perform any authentication at all, and should not be accepted by message buses.
25    /// However, it might sometimes be useful for non-message-bus uses of D-Bus.
26    Anonymous,
27}
28
29impl AuthMechanism {
30    pub fn as_str(&self) -> &'static str {
31        match self {
32            AuthMechanism::External => "EXTERNAL",
33            AuthMechanism::Anonymous => "ANONYMOUS",
34        }
35    }
36}
37
38impl fmt::Display for AuthMechanism {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let mech = self.as_str();
41        write!(f, "{mech}")
42    }
43}
44
45impl FromStr for AuthMechanism {
46    type Err = Error;
47
48    fn from_str(s: &str) -> Result<Self> {
49        match s {
50            "EXTERNAL" => Ok(AuthMechanism::External),
51            "ANONYMOUS" => Ok(AuthMechanism::Anonymous),
52            _ => Err(Error::Handshake(format!("Unsupported mechanism: {s}"))),
53        }
54    }
55}