Skip to main content

strata_platform/
dbus.rs

1//! Pure-Rust D-Bus wire protocol serializer, client, and desktop notification daemon.
2//!
3//! Provides zero-dependency D-Bus message framing, SASL authentication over UNIX domain sockets,
4//! and integration with `org.freedesktop.Notifications` and `org.kde.StatusNotifierItem`.
5
6use std::io::{Read, Write};
7use std::os::unix::net::UnixStream;
8use std::time::Duration;
9
10// D-Bus Message Types
11pub const DBUS_MESSAGE_TYPE_METHOD_CALL: u8 = 1;
12pub const DBUS_MESSAGE_TYPE_METHOD_RETURN: u8 = 2;
13pub const DBUS_MESSAGE_TYPE_ERROR: u8 = 3;
14pub const DBUS_MESSAGE_TYPE_SIGNAL: u8 = 4;
15
16// D-Bus Header Field Codes
17pub const DBUS_HEADER_FIELD_PATH: u8 = 1;
18pub const DBUS_HEADER_FIELD_INTERFACE: u8 = 2;
19pub const DBUS_HEADER_FIELD_MEMBER: u8 = 3;
20pub const DBUS_HEADER_FIELD_ERROR_NAME: u8 = 4;
21pub const DBUS_HEADER_FIELD_REPLY_SERIAL: u8 = 5;
22pub const DBUS_HEADER_FIELD_DESTINATION: u8 = 6;
23pub const DBUS_HEADER_FIELD_SENDER: u8 = 7;
24pub const DBUS_HEADER_FIELD_SIGNATURE: u8 = 8;
25
26// D-Bus Flags
27pub const DBUS_FLAG_NO_REPLY_EXPECTED: u8 = 0x01;
28pub const DBUS_FLAG_NO_AUTO_START: u8 = 0x02;
29
30/// Resolves the UNIX domain socket path for the active D-Bus session bus.
31pub fn session_bus_socket_path() -> Result<String, String> {
32    if let Ok(addr) = std::env::var("DBUS_SESSION_BUS_ADDRESS") {
33        for part in addr.split(',') {
34            if let Some(path) = part.strip_prefix("unix:path=") {
35                return Ok(path.to_string());
36            }
37        }
38    }
39
40    #[cfg(unix)]
41    {
42        let uid = unsafe { libc::getuid() };
43        let candidate = format!("/run/user/{}/bus", uid);
44        if std::path::Path::new(&candidate).exists() {
45            return Ok(candidate);
46        }
47    }
48
49    Err("Could not resolve D-Bus session bus socket address".to_string())
50}
51
52/// Encodes an ASCII string to hexadecimal for D-Bus SASL authentication.
53pub fn hex_encode_bytes(bytes: &[u8]) -> String {
54    let mut out = String::with_capacity(bytes.len() * 2);
55    for b in bytes {
56        out.push_str(&format!("{:02x}", b));
57    }
58    out
59}
60
61/// Formats a complete SASL authentication handshake sequence for external UID auth.
62pub fn format_sasl_auth_request(uid: u32) -> Vec<u8> {
63    let uid_str = uid.to_string();
64    let hex_uid = hex_encode_bytes(uid_str.as_bytes());
65    format!("\0AUTH EXTERNAL {}\r\nBEGIN\r\n", hex_uid).into_bytes()
66}
67
68/// Encoder for little-endian D-Bus wire protocol binary messages.
69#[derive(Debug, Default)]
70pub struct DbusMessageEncoder {
71    buffer: Vec<u8>,
72}
73
74impl DbusMessageEncoder {
75    /// Creates a new encoder with standard capacity.
76    pub fn new() -> Self {
77        Self {
78            buffer: Vec::with_capacity(512),
79        }
80    }
81
82    /// Clears the internal buffer.
83    pub fn clear(&mut self) {
84        self.buffer.clear();
85    }
86
87    /// Returns the encoded byte slice.
88    pub fn as_bytes(&self) -> &[u8] {
89        &self.buffer
90    }
91
92    /// Pads the buffer to the given byte alignment.
93    pub fn pad_to(&mut self, alignment: usize) {
94        let remainder = self.buffer.len() % alignment;
95        if remainder != 0 {
96            let pad = alignment - remainder;
97            self.buffer.resize(self.buffer.len() + pad, 0);
98        }
99    }
100
101    /// Appends a raw byte.
102    pub fn push_u8(&mut self, val: u8) {
103        self.buffer.push(val);
104    }
105
106    /// Appends a little-endian unsigned 16-bit integer.
107    pub fn push_u16(&mut self, val: u16) {
108        self.pad_to(2);
109        self.buffer.extend_from_slice(&val.to_le_bytes());
110    }
111
112    /// Appends a little-endian unsigned 32-bit integer.
113    pub fn push_u32(&mut self, val: u32) {
114        self.pad_to(4);
115        self.buffer.extend_from_slice(&val.to_le_bytes());
116    }
117
118    /// Appends a little-endian signed 32-bit integer.
119    pub fn push_i32(&mut self, val: i32) {
120        self.pad_to(4);
121        self.buffer.extend_from_slice(&val.to_le_bytes());
122    }
123
124    /// Appends a little-endian unsigned 64-bit integer.
125    pub fn push_u64(&mut self, val: u64) {
126        self.pad_to(8);
127        self.buffer.extend_from_slice(&val.to_le_bytes());
128    }
129
130    /// Appends a D-Bus String (4-byte length + bytes + null terminator).
131    pub fn push_string(&mut self, val: &str) {
132        self.push_u32(val.len() as u32);
133        self.buffer.extend_from_slice(val.as_bytes());
134        self.buffer.push(0);
135    }
136
137    /// Appends a D-Bus ObjectPath (4-byte length + bytes + null terminator).
138    pub fn push_object_path(&mut self, path: &str) {
139        self.push_string(path);
140    }
141
142    /// Appends a D-Bus Signature (1-byte length + bytes + null terminator).
143    pub fn push_signature(&mut self, sig: &str) {
144        self.push_u8(sig.len() as u8);
145        self.buffer.extend_from_slice(sig.as_bytes());
146        self.buffer.push(0);
147    }
148
149    /// Encodes a method call message with the given header fields and body data.
150    pub fn encode_method_call(
151        &mut self,
152        serial: u32,
153        destination: Option<&str>,
154        path: &str,
155        interface: Option<&str>,
156        member: &str,
157        signature: Option<&str>,
158        body: &[u8],
159    ) {
160        self.clear();
161
162        // Build header fields array
163        let mut fields_encoder = DbusMessageEncoder::new();
164
165        // 1. Path field
166        fields_encoder.pad_to(8);
167        fields_encoder.push_u8(DBUS_HEADER_FIELD_PATH);
168        fields_encoder.push_signature("o");
169        fields_encoder.push_object_path(path);
170
171        // 2. Member field
172        fields_encoder.pad_to(8);
173        fields_encoder.push_u8(DBUS_HEADER_FIELD_MEMBER);
174        fields_encoder.push_signature("s");
175        fields_encoder.push_string(member);
176
177        // 3. Interface field
178        if let Some(iface) = interface {
179            fields_encoder.pad_to(8);
180            fields_encoder.push_u8(DBUS_HEADER_FIELD_INTERFACE);
181            fields_encoder.push_signature("s");
182            fields_encoder.push_string(iface);
183        }
184
185        // 4. Destination field
186        if let Some(dest) = destination {
187            fields_encoder.pad_to(8);
188            fields_encoder.push_u8(DBUS_HEADER_FIELD_DESTINATION);
189            fields_encoder.push_signature("s");
190            fields_encoder.push_string(dest);
191        }
192
193        // 5. Signature field
194        if let Some(sig) = signature {
195            fields_encoder.pad_to(8);
196            fields_encoder.push_u8(DBUS_HEADER_FIELD_SIGNATURE);
197            fields_encoder.push_signature("g");
198            fields_encoder.push_signature(sig);
199        }
200
201        let fields_bytes = fields_encoder.as_bytes();
202        let fields_len = fields_bytes.len() as u32;
203        let body_len = body.len() as u32;
204
205        // Fixed 16-byte header
206        self.push_u8(b'l'); // Little-endian
207        self.push_u8(DBUS_MESSAGE_TYPE_METHOD_CALL);
208        self.push_u8(0); // Flags
209        self.push_u8(1); // Protocol version 1
210        self.push_u32(body_len);
211        self.push_u32(serial);
212        self.push_u32(fields_len);
213
214        // Header fields
215        self.buffer.extend_from_slice(fields_bytes);
216
217        // Pad header to 8 bytes before body
218        self.pad_to(8);
219
220        // Body
221        self.buffer.extend_from_slice(body);
222    }
223
224    /// Encodes a method return message in reply to a specific method call serial.
225    pub fn encode_method_return(
226        &mut self,
227        serial: u32,
228        reply_serial: u32,
229        destination: Option<&str>,
230        signature: Option<&str>,
231        body: &[u8],
232    ) {
233        self.clear();
234
235        let mut fields_encoder = DbusMessageEncoder::new();
236
237        // 1. ReplySerial field
238        fields_encoder.pad_to(8);
239        fields_encoder.push_u8(DBUS_HEADER_FIELD_REPLY_SERIAL);
240        fields_encoder.push_signature("u");
241        fields_encoder.push_u32(reply_serial);
242
243        // 2. Destination field
244        if let Some(dest) = destination {
245            fields_encoder.pad_to(8);
246            fields_encoder.push_u8(DBUS_HEADER_FIELD_DESTINATION);
247            fields_encoder.push_signature("s");
248            fields_encoder.push_string(dest);
249        }
250
251        // 3. Signature field
252        if let Some(sig) = signature {
253            fields_encoder.pad_to(8);
254            fields_encoder.push_u8(DBUS_HEADER_FIELD_SIGNATURE);
255            fields_encoder.push_signature("g");
256            fields_encoder.push_signature(sig);
257        }
258
259        let fields_bytes = fields_encoder.as_bytes();
260        let fields_len = fields_bytes.len() as u32;
261        let body_len = body.len() as u32;
262
263        // Fixed 16-byte header
264        self.push_u8(b'l'); // Little-endian
265        self.push_u8(DBUS_MESSAGE_TYPE_METHOD_RETURN);
266        self.push_u8(0); // Flags
267        self.push_u8(1); // Protocol version 1
268        self.push_u32(body_len);
269        self.push_u32(serial);
270        self.push_u32(fields_len);
271
272        // Header fields
273        self.buffer.extend_from_slice(fields_bytes);
274
275        // Pad header to 8 bytes before body
276        self.pad_to(8);
277
278        // Body
279        self.buffer.extend_from_slice(body);
280    }
281}
282
283/// Decoder for little-endian D-Bus wire protocol binary messages.
284pub struct DbusMessageDecoder<'a> {
285    data: &'a [u8],
286    offset: usize,
287}
288
289impl<'a> DbusMessageDecoder<'a> {
290    /// Creates a decoder wrapping the given slice.
291    pub fn new(data: &'a [u8]) -> Self {
292        Self { data, offset: 0 }
293    }
294
295    /// Aligns current offset to the specified boundary.
296    pub fn align_to(&mut self, alignment: usize) {
297        let rem = self.offset % alignment;
298        if rem != 0 {
299            self.offset += alignment - rem;
300        }
301    }
302
303    /// Reads a single byte.
304    pub fn read_u8(&mut self) -> Option<u8> {
305        if self.offset < self.data.len() {
306            let val = self.data[self.offset];
307            self.offset += 1;
308            Some(val)
309        } else {
310            None
311        }
312    }
313
314    /// Reads a little-endian unsigned 16-bit integer.
315    pub fn read_u16(&mut self) -> Option<u16> {
316        self.align_to(2);
317        if self.offset + 2 <= self.data.len() {
318            let val =
319                u16::from_le_bytes(self.data[self.offset..self.offset + 2].try_into().unwrap());
320            self.offset += 2;
321            Some(val)
322        } else {
323            None
324        }
325    }
326
327    /// Reads a little-endian unsigned 32-bit integer.
328    pub fn read_u32(&mut self) -> Option<u32> {
329        self.align_to(4);
330        if self.offset + 4 <= self.data.len() {
331            let val =
332                u32::from_le_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
333            self.offset += 4;
334            Some(val)
335        } else {
336            None
337        }
338    }
339
340    /// Reads a little-endian signed 32-bit integer.
341    pub fn read_i32(&mut self) -> Option<i32> {
342        self.align_to(4);
343        if self.offset + 4 <= self.data.len() {
344            let val =
345                i32::from_le_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
346            self.offset += 4;
347            Some(val)
348        } else {
349            None
350        }
351    }
352
353    /// Reads a D-Bus String (4-byte length + bytes + null).
354    pub fn read_string(&mut self) -> Option<String> {
355        let len = self.read_u32()? as usize;
356        if self.offset + len < self.data.len() {
357            let bytes = &self.data[self.offset..self.offset + len];
358            let str = String::from_utf8_lossy(bytes).to_string();
359            self.offset += len + 1; // +1 to skip null terminator
360            Some(str)
361        } else {
362            None
363        }
364    }
365}
366
367/// Lightweight D-Bus connection for session bus interaction.
368pub struct DbusClient {
369    stream: UnixStream,
370    next_serial: u32,
371    pub unique_name: Option<String>,
372}
373
374impl DbusClient {
375    /// Connects to the local session bus and completes SASL authentication.
376    pub fn connect() -> Result<Self, String> {
377        let path = session_bus_socket_path()?;
378        Self::connect_to_path(&path)
379    }
380
381    /// Connects to a specific UNIX domain socket path and performs SASL authentication.
382    pub fn connect_to_path(socket_path: &str) -> Result<Self, String> {
383        let mut stream = UnixStream::connect(socket_path)
384            .map_err(|e| format!("Cannot connect to D-Bus socket \"{}\": {}", socket_path, e))?;
385
386        stream
387            .set_read_timeout(Some(Duration::from_millis(1500)))
388            .map_err(|e| format!("Failed to set read timeout: {}", e))?;
389
390        #[cfg(unix)]
391        let uid = unsafe { libc::getuid() };
392        #[cfg(not(unix))]
393        let uid = 1000;
394
395        // 1. Send SASL authentication
396        let auth_payload = format_sasl_auth_request(uid);
397        stream
398            .write_all(&auth_payload)
399            .map_err(|e| format!("Failed to write SASL auth: {}", e))?;
400
401        // 2. Read SASL OK reply line
402        let mut response = Vec::new();
403        let mut byte = [0u8; 1];
404        while let Ok(1) = stream.read(&mut byte) {
405            response.push(byte[0]);
406            if response.ends_with(b"\r\n") {
407                break;
408            }
409        }
410
411        let resp_str = String::from_utf8_lossy(&response);
412        if !resp_str.starts_with("OK") {
413            return Err(format!("D-Bus SASL auth rejected: {}", resp_str.trim()));
414        }
415
416        let mut client = Self {
417            stream,
418            next_serial: 1,
419            unique_name: None,
420        };
421
422        // 3. Call org.freedesktop.DBus.Hello to register on the bus
423        let name = client.call_hello()?;
424        client.unique_name = Some(name);
425
426        Ok(client)
427    }
428
429    /// Allocates an incremental serial number.
430    pub fn next_serial(&mut self) -> u32 {
431        let s = self.next_serial;
432        self.next_serial += 1;
433        s
434    }
435
436    /// Invokes `org.freedesktop.DBus.Hello` to obtain the assigned client unique name.
437    pub fn call_hello(&mut self) -> Result<String, String> {
438        let serial = self.next_serial();
439        let mut encoder = DbusMessageEncoder::new();
440        encoder.encode_method_call(
441            serial,
442            Some("org.freedesktop.DBus"),
443            "/org/freedesktop/DBus",
444            Some("org.freedesktop.DBus"),
445            "Hello",
446            None,
447            &[],
448        );
449
450        self.stream
451            .write_all(encoder.as_bytes())
452            .map_err(|e| format!("Failed to send DBus.Hello: {}", e))?;
453
454        // Read method return
455        let reply = self.read_message()?;
456        let mut decoder = DbusMessageDecoder::new(&reply);
457        // Skip 16-byte fixed header
458        if reply.len() < 16 {
459            return Err("D-Bus reply header too short".to_string());
460        }
461        let body_len = u32::from_le_bytes(reply[4..8].try_into().unwrap()) as usize;
462        let fields_len = u32::from_le_bytes(reply[12..16].try_into().unwrap()) as usize;
463        let mut header_total = 16 + fields_len;
464        if !header_total.is_multiple_of(8) {
465            header_total += 8 - (header_total % 8);
466        }
467
468        if reply.len() < header_total + body_len {
469            return Err("D-Bus reply payload truncated".to_string());
470        }
471
472        decoder.offset = header_total;
473        decoder
474            .read_string()
475            .ok_or_else(|| "Failed to parse unique name from DBus.Hello".to_string())
476    }
477
478    /// Dispatches a method call and reads the method return reply.
479    pub fn call_method(
480        &mut self,
481        destination: &str,
482        path: &str,
483        interface: &str,
484        member: &str,
485        signature: Option<&str>,
486        body: &[u8],
487    ) -> Result<Vec<u8>, String> {
488        let serial = self.next_serial();
489        let mut encoder = DbusMessageEncoder::new();
490        encoder.encode_method_call(
491            serial,
492            Some(destination),
493            path,
494            Some(interface),
495            member,
496            signature,
497            body,
498        );
499
500        self.stream
501            .write_all(encoder.as_bytes())
502            .map_err(|e| format!("D-Bus write error for {}.{}: {}", interface, member, e))?;
503
504        self.read_message()
505    }
506
507    /// Reads a complete framed D-Bus binary message from the stream.
508    pub fn read_message(&mut self) -> Result<Vec<u8>, String> {
509        let mut header = [0u8; 16];
510        self.stream
511            .read_exact(&mut header)
512            .map_err(|e| format!("Failed to read D-Bus message header: {}", e))?;
513
514        let body_len = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;
515        let fields_len = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
516
517        let mut header_fields = vec![0u8; fields_len];
518        if fields_len > 0 {
519            self.stream
520                .read_exact(&mut header_fields)
521                .map_err(|e| format!("Failed to read D-Bus header fields: {}", e))?;
522        }
523
524        // Header padding
525        let total_header = 16 + fields_len;
526        let rem = total_header % 8;
527        let pad_len = if rem != 0 { 8 - rem } else { 0 };
528        if pad_len > 0 {
529            let mut pad = vec![0u8; pad_len];
530            self.stream
531                .read_exact(&mut pad)
532                .map_err(|e| format!("Failed to read D-Bus header padding: {}", e))?;
533        }
534
535        let mut body = vec![0u8; body_len];
536        if body_len > 0 {
537            self.stream
538                .read_exact(&mut body)
539                .map_err(|e| format!("Failed to read D-Bus body: {}", e))?;
540        }
541
542        let mut full_msg = Vec::with_capacity(16 + fields_len + pad_len + body_len);
543        full_msg.extend_from_slice(&header);
544        full_msg.extend_from_slice(&header_fields);
545        full_msg.resize(full_msg.len() + pad_len, 0);
546        full_msg.extend_from_slice(&body);
547        Ok(full_msg)
548    }
549}
550
551/// Dispatches a native desktop notification via `org.freedesktop.Notifications.Notify`.
552///
553/// Returns the notification ID assigned by the daemon.
554pub fn show_desktop_notification(
555    summary: &str,
556    body: &str,
557    icon: Option<&str>,
558    timeout_ms: i32,
559) -> Result<u32, String> {
560    let mut client = DbusClient::connect()?;
561
562    // Body signature: susssasa{sv}i
563    // app_name (s), replaces_id (u), app_icon (s), summary (s), body (s), actions (as), hints (a{sv}), expire_timeout (i)
564    let mut body_encoder = DbusMessageEncoder::new();
565    body_encoder.push_string("Strata");
566    body_encoder.push_u32(0); // replaces_id = 0
567    body_encoder.push_string(icon.unwrap_or("dialog-information"));
568    body_encoder.push_string(summary);
569    body_encoder.push_string(body);
570
571    // actions: array of strings (empty)
572    body_encoder.push_u32(0);
573
574    // hints: array of dict entries {sv} (empty)
575    body_encoder.push_u32(0);
576
577    // expire_timeout (i32)
578    body_encoder.push_i32(timeout_ms);
579
580    let reply = client.call_method(
581        "org.freedesktop.Notifications",
582        "/org/freedesktop/Notifications",
583        "org.freedesktop.Notifications",
584        "Notify",
585        Some("susssasa{sv}i"),
586        body_encoder.as_bytes(),
587    )?;
588
589    if reply.len() < 16 {
590        return Err("Notification reply payload too short".to_string());
591    }
592
593    let fields_len = u32::from_le_bytes(reply[12..16].try_into().unwrap()) as usize;
594    let mut header_total = 16 + fields_len;
595    if !header_total.is_multiple_of(8) {
596        header_total += 8 - (header_total % 8);
597    }
598
599    if reply.len() >= header_total + 4 {
600        let notif_id =
601            u32::from_le_bytes(reply[header_total..header_total + 4].try_into().unwrap());
602        Ok(notif_id)
603    } else {
604        Ok(1)
605    }
606}