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
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::io::{Read, Write};
use std::mem::size_of;
use std::os::fd::AsRawFd;
use std::os::fd::RawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;

use crate::buf::OwnedBuf;
use crate::buf::MAX_ARRAY_LENGTH;
use crate::buf::{padding_to, MAX_BODY_LENGTH};
use crate::error::{Error, ErrorKind, Result};
use crate::protocol;
use crate::sasl::Auth;
use crate::sasl::{Guid, SaslRequest, SaslResponse};
use crate::Frame;

const ENV_SESSION_BUS: &str = "DBUS_SESSION_BUS_ADDRESS";
const ENV_SYSTEM_BUS: &str = "DBUS_SYSTEM_BUS_ADDRESS";
const DEFAULT_SYSTEM_BUS: &str = "unix:path=/var/run/dbus/system_bus_socket";

/// An owned reference to a message in a [`RecvBuf`].
///
/// To convert into a [`Message`], use [`Client::read_message`] or
/// [`RecvBuf::read_message`].
///
/// [`Message`]: crate::Message
/// [`Client::read_message`]: crate::Client::read_message
/// [`RecvBuf::read_message`]: crate::RecvBuf::read_message
/// [`RecvBuf`]: crate::RecvBuf
#[derive(Debug)]
pub struct MessageRef {
    pub(super) header: protocol::Header,
    pub(super) headers: usize,
    pub(super) total: usize,
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum SaslState {
    // SASL state before it's been initialized.
    Init,
    // SASL message being sent.
    Idle,
    // SASL message is being sent.
    Send,
}

impl fmt::Display for SaslState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SaslState::Init => write!(f, "sasl-init"),
            SaslState::Idle => write!(f, "sasl-idle"),
            SaslState::Send => write!(f, "sasl-send"),
        }
    }
}

/// The state of the connection.
#[derive(Debug, Clone, Copy)]
pub(crate) enum ConnectionState {
    // Newly opened socket in the SASL state.
    Sasl(SaslState),
    // Connection is open and idle.
    Idle,
    /// Body is being received.
    RecvBody(protocol::Header, usize, usize),
}

impl fmt::Display for ConnectionState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConnectionState::Sasl(state) => write!(f, "sasl ({state})"),
            ConnectionState::Idle => write!(f, "idle"),
            ConnectionState::RecvBody(..) => write!(f, "recv-body"),
        }
    }
}

/// A connection to a d-bus session.
pub struct Connection {
    // Stream of the connection.
    stream: UnixStream,
    // The state of the connection.
    state: ConnectionState,
}

impl Connection {
    /// Construct a new connection to the session bus.
    ///
    /// This uses the `DBUS_SESSION_BUS_ADDRESS` environment variable to
    /// determine its address.
    pub fn session_bus() -> Result<Self> {
        Self::from_env(ENV_SESSION_BUS, None)
    }

    /// Construct a new connection to the session bus.
    ///
    /// This uses the `DBUS_SYSTEM_BUS_ADDRESS` environment variable to
    /// determine its address or fallback to the well-known address
    /// `unix:path=/var/run/dbus/system_bus_socket`.
    pub fn system_bus() -> Result<Self> {
        Self::from_env(ENV_SYSTEM_BUS, Some(DEFAULT_SYSTEM_BUS))
    }

    /// Construct a new connection to the session bus.
    ///
    /// This uses the `DBUS_SESSION_BUS_ADDRESS` environment variable to
    /// determine its address.
    fn from_env(env: &str, default: Option<&str>) -> Result<Self> {
        let value;

        let address: &OsStr = match env::var_os(env) {
            Some(address) => {
                value = address;
                value.as_os_str()
            }
            None => match default {
                Some(default) => default.as_ref(),
                None => return Err(Error::new(ErrorKind::MissingBus)),
            },
        };

        let stream = match parse_address(address)? {
            Address::Unix(address) => UnixStream::connect(OsStr::from_bytes(address))?,
        };

        Ok(Self::from_std(stream))
    }

    /// Set the connection as non-blocking.
    pub(crate) fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.stream.set_nonblocking(nonblocking)?;
        Ok(())
    }

    /// Constru.ct a connection directly from a unix stream.
    pub(crate) fn from_std(stream: UnixStream) -> Self {
        Self {
            stream,
            state: ConnectionState::Sasl(SaslState::Init),
        }
    }

    /// Send a SASL message and receive a response.
    pub(crate) fn sasl_send(
        &mut self,
        buf: &mut OwnedBuf,
        request: &SaslRequest<'_>,
    ) -> Result<()> {
        loop {
            match &mut self.state {
                ConnectionState::Sasl(sasl) => match sasl {
                    SaslState::Init => {
                        buf.extend_from_slice(b"\0");
                        *sasl = SaslState::Idle;
                    }
                    SaslState::Idle => {
                        match request {
                            SaslRequest::Auth(auth) => match auth {
                                Auth::External(external) => {
                                    buf.extend_from_slice(b"AUTH EXTERNAL ");
                                    buf.extend_from_slice(external);
                                }
                            },
                        }

                        buf.extend_from_slice(b"\r\n");
                        *sasl = SaslState::Send;
                    }
                    SaslState::Send => {
                        send_buf(&mut &self.stream, buf)?;
                        *sasl = SaslState::Idle;
                        return Ok(());
                    }
                },
                state => return Err(Error::new(ErrorKind::InvalidState(*state))),
            }
        }
    }

    /// Receive a sasl response.
    pub(crate) fn sasl_recv(&mut self, buf: &mut OwnedBuf) -> Result<usize> {
        match self.state {
            ConnectionState::Sasl(SaslState::Idle) => {
                let value = recv_line(&mut &self.stream, buf)?;
                Ok(value)
            }
            state => Err(Error::new(ErrorKind::InvalidState(state))),
        }
    }

    /// Send the SASL `BEGIN` message.
    ///
    /// This does not expect a response from the server, instead it is expected
    /// to transition into the binary D-Bus protocol.
    pub(crate) fn sasl_begin(&mut self, buf: &mut OwnedBuf) -> Result<()> {
        loop {
            match &mut self.state {
                ConnectionState::Sasl(sasl) => match sasl {
                    SaslState::Init => {
                        buf.extend_from_slice(b"\0");
                        *sasl = SaslState::Idle;
                    }
                    SaslState::Idle => {
                        buf.extend_from_slice(b"BEGIN\r\n");
                        *sasl = SaslState::Send;
                    }
                    SaslState::Send => {
                        send_buf(&mut &self.stream, buf)?;
                        self.state = ConnectionState::Idle;
                        return Ok(());
                    }
                },
                state => return Err(Error::new(ErrorKind::InvalidState(*state))),
            }
        }
    }

    /// Write and sned a single message over the connection.
    pub(crate) fn send_buf(&self, buf: &mut OwnedBuf) -> Result<()> {
        send_buf(&mut &self.stream, buf)?;
        Ok(())
    }

    /// Receive a message.
    pub(crate) fn recv_message(&mut self, buf: &mut OwnedBuf) -> Result<MessageRef> {
        loop {
            match self.state {
                ConnectionState::Idle => {
                    self.recv_buf(buf, size_of::<protocol::Header>() + size_of::<u32>())?;

                    let mut read_buf =
                        buf.read_until(size_of::<protocol::Header>() + size_of::<u32>());

                    let mut header = read_buf.load::<protocol::Header>()?;
                    let mut headers = read_buf.load::<u32>()?;

                    header.adjust(header.endianness);
                    headers.adjust(header.endianness);

                    if header.body_length > MAX_BODY_LENGTH {
                        return Err(Error::new(ErrorKind::BodyTooLong(header.body_length)));
                    }

                    if headers > MAX_ARRAY_LENGTH {
                        return Err(Error::new(ErrorKind::ArrayTooLong(headers)));
                    }

                    let Some(body_length) = usize::try_from(header.body_length).ok() else {
                        return Err(Error::new(ErrorKind::BodyTooLong(header.body_length)));
                    };

                    let Some(headers) = usize::try_from(headers).ok() else {
                        return Err(Error::new(ErrorKind::ArrayTooLong(headers)));
                    };

                    // Padding used in the header.
                    let total = headers + padding_to::<u64>(headers) + body_length;
                    self.state = ConnectionState::RecvBody(header, headers, total);
                }
                ConnectionState::RecvBody(header, headers, total) => {
                    self.recv_buf(buf, total)?;
                    self.state = ConnectionState::Idle;

                    return Ok(MessageRef {
                        header,
                        headers,
                        total,
                    });
                }
                state => return Err(Error::new(ErrorKind::InvalidState(state))),
            }
        }
    }

    /// Fill a buffer up to `n` bytes.
    pub(crate) fn recv_buf(&self, buf: &mut OwnedBuf, n: usize) -> io::Result<()> {
        buf.reserve_bytes(n);

        while buf.len() < n {
            recv_some(&mut &self.stream, buf)?;
        }

        Ok(())
    }
}

impl Read for Connection {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.stream.read(buf)
    }
}

impl Write for Connection {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.stream.write(buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        self.stream.flush()
    }
}

/// Receive a SASL message from the connection.
pub(crate) fn sasl_recv(bytes: &[u8]) -> Result<SaslResponse<'_>> {
    let line = crate::utils::trim_end(bytes);

    let Some((command, rest)) = crate::utils::split_once(line, b' ') else {
        return Err(Error::new(ErrorKind::InvalidSasl));
    };

    match command {
        b"OK" => Ok(SaslResponse::Ok(Guid::new(rest))),
        _ => Err(Error::new(ErrorKind::InvalidSaslResponse)),
    }
}

/// Send the given buffer over the connection.
fn send_buf(stream: &mut &UnixStream, buf: &mut OwnedBuf) -> io::Result<()> {
    while !buf.is_empty() {
        let n = stream.write(buf.get())?;
        buf.advance(n);
    }

    stream.flush()?;
    Ok(())
}

fn recv_line(stream: &mut &UnixStream, buf: &mut OwnedBuf) -> io::Result<usize> {
    loop {
        if let Some(n) = buf.get().iter().position(|b| *b == b'\n') {
            return Ok(n + 1);
        }

        recv_some(stream, buf)?;
    }
}

/// Receive data into the specified buffer.
fn recv_some(stream: &mut &UnixStream, buf: &mut OwnedBuf) -> io::Result<()> {
    buf.reserve_bytes(4096);
    let n = stream.read(buf.get_mut())?;

    if n == 0 {
        return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
    }

    buf.advance_mut(n);
    Ok(())
}

enum Address<'a> {
    Unix(&'a [u8]),
}

#[cfg(unix)]
fn parse_address(string: &OsStr) -> Result<Address<'_>> {
    parse_address_bytes(string.as_bytes())
}

fn parse_address_bytes(bytes: &[u8]) -> Result<Address<'_>> {
    let Some(index) = bytes.iter().position(|&b| b == b'=') else {
        return Err(Error::new(ErrorKind::InvalidAddress));
    };

    let (head, tail) = bytes.split_at(index);

    match head {
        b"unix:path" => Ok(Address::Unix(&tail[1..])),
        _ => Err(Error::new(ErrorKind::InvalidAddress)),
    }
}

impl AsRawFd for Connection {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.stream.as_raw_fd()
    }
}