1use std::io::{Read, Write};
7use std::os::unix::net::UnixStream;
8use std::time::Duration;
9
10pub 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
16pub 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
26pub const DBUS_FLAG_NO_REPLY_EXPECTED: u8 = 0x01;
28pub const DBUS_FLAG_NO_AUTO_START: u8 = 0x02;
29
30pub 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
52pub fn system_bus_socket_path() -> Result<String, String> {
55 if let Ok(addr) = std::env::var("DBUS_SYSTEM_BUS_ADDRESS") {
56 for part in addr.split(',') {
57 if let Some(path) = part.strip_prefix("unix:path=") {
58 return Ok(path.to_string());
59 }
60 }
61 }
62 for candidate in ["/run/dbus/system_bus_socket", "/var/run/dbus/system_bus_socket"] {
63 if std::path::Path::new(candidate).exists() {
64 return Ok(candidate.to_string());
65 }
66 }
67 Err("Could not resolve D-Bus system bus socket address".to_string())
68}
69
70pub fn hex_encode_bytes(bytes: &[u8]) -> String {
72 let mut out = String::with_capacity(bytes.len() * 2);
73 for b in bytes {
74 out.push_str(&format!("{:02x}", b));
75 }
76 out
77}
78
79pub fn format_sasl_auth_request(uid: u32) -> Vec<u8> {
81 let uid_str = uid.to_string();
82 let hex_uid = hex_encode_bytes(uid_str.as_bytes());
83 format!("\0AUTH EXTERNAL {}\r\nBEGIN\r\n", hex_uid).into_bytes()
84}
85
86#[derive(Debug, Default)]
88pub struct DbusMessageEncoder {
89 buffer: Vec<u8>,
90}
91
92impl DbusMessageEncoder {
93 pub fn new() -> Self {
95 Self {
96 buffer: Vec::with_capacity(512),
97 }
98 }
99
100 pub fn clear(&mut self) {
102 self.buffer.clear();
103 }
104
105 pub fn as_bytes(&self) -> &[u8] {
107 &self.buffer
108 }
109
110 pub fn pad_to(&mut self, alignment: usize) {
112 let remainder = self.buffer.len() % alignment;
113 if remainder != 0 {
114 let pad = alignment - remainder;
115 self.buffer.resize(self.buffer.len() + pad, 0);
116 }
117 }
118
119 pub fn push_u8(&mut self, val: u8) {
121 self.buffer.push(val);
122 }
123
124 pub fn push_u16(&mut self, val: u16) {
126 self.pad_to(2);
127 self.buffer.extend_from_slice(&val.to_le_bytes());
128 }
129
130 pub fn push_u32(&mut self, val: u32) {
132 self.pad_to(4);
133 self.buffer.extend_from_slice(&val.to_le_bytes());
134 }
135
136 pub fn push_i32(&mut self, val: i32) {
138 self.pad_to(4);
139 self.buffer.extend_from_slice(&val.to_le_bytes());
140 }
141
142 pub fn push_u64(&mut self, val: u64) {
144 self.pad_to(8);
145 self.buffer.extend_from_slice(&val.to_le_bytes());
146 }
147
148 pub fn push_string(&mut self, val: &str) {
150 self.push_u32(val.len() as u32);
151 self.buffer.extend_from_slice(val.as_bytes());
152 self.buffer.push(0);
153 }
154
155 pub fn push_object_path(&mut self, path: &str) {
157 self.push_string(path);
158 }
159
160 pub fn push_signature(&mut self, sig: &str) {
162 self.push_u8(sig.len() as u8);
163 self.buffer.extend_from_slice(sig.as_bytes());
164 self.buffer.push(0);
165 }
166
167 pub fn encode_method_call(
169 &mut self,
170 serial: u32,
171 destination: Option<&str>,
172 path: &str,
173 interface: Option<&str>,
174 member: &str,
175 signature: Option<&str>,
176 body: &[u8],
177 ) {
178 self.clear();
179
180 let mut fields_encoder = DbusMessageEncoder::new();
182
183 fields_encoder.pad_to(8);
185 fields_encoder.push_u8(DBUS_HEADER_FIELD_PATH);
186 fields_encoder.push_signature("o");
187 fields_encoder.push_object_path(path);
188
189 fields_encoder.pad_to(8);
191 fields_encoder.push_u8(DBUS_HEADER_FIELD_MEMBER);
192 fields_encoder.push_signature("s");
193 fields_encoder.push_string(member);
194
195 if let Some(iface) = interface {
197 fields_encoder.pad_to(8);
198 fields_encoder.push_u8(DBUS_HEADER_FIELD_INTERFACE);
199 fields_encoder.push_signature("s");
200 fields_encoder.push_string(iface);
201 }
202
203 if let Some(dest) = destination {
205 fields_encoder.pad_to(8);
206 fields_encoder.push_u8(DBUS_HEADER_FIELD_DESTINATION);
207 fields_encoder.push_signature("s");
208 fields_encoder.push_string(dest);
209 }
210
211 if let Some(sig) = signature {
213 fields_encoder.pad_to(8);
214 fields_encoder.push_u8(DBUS_HEADER_FIELD_SIGNATURE);
215 fields_encoder.push_signature("g");
216 fields_encoder.push_signature(sig);
217 }
218
219 let fields_bytes = fields_encoder.as_bytes();
220 let fields_len = fields_bytes.len() as u32;
221 let body_len = body.len() as u32;
222
223 self.push_u8(b'l'); self.push_u8(DBUS_MESSAGE_TYPE_METHOD_CALL);
226 self.push_u8(0); self.push_u8(1); self.push_u32(body_len);
229 self.push_u32(serial);
230 self.push_u32(fields_len);
231
232 self.buffer.extend_from_slice(fields_bytes);
234
235 self.pad_to(8);
237
238 self.buffer.extend_from_slice(body);
240 }
241
242 pub fn encode_method_return(
244 &mut self,
245 serial: u32,
246 reply_serial: u32,
247 destination: Option<&str>,
248 signature: Option<&str>,
249 body: &[u8],
250 ) {
251 self.clear();
252
253 let mut fields_encoder = DbusMessageEncoder::new();
254
255 fields_encoder.pad_to(8);
257 fields_encoder.push_u8(DBUS_HEADER_FIELD_REPLY_SERIAL);
258 fields_encoder.push_signature("u");
259 fields_encoder.push_u32(reply_serial);
260
261 if let Some(dest) = destination {
263 fields_encoder.pad_to(8);
264 fields_encoder.push_u8(DBUS_HEADER_FIELD_DESTINATION);
265 fields_encoder.push_signature("s");
266 fields_encoder.push_string(dest);
267 }
268
269 if let Some(sig) = signature {
271 fields_encoder.pad_to(8);
272 fields_encoder.push_u8(DBUS_HEADER_FIELD_SIGNATURE);
273 fields_encoder.push_signature("g");
274 fields_encoder.push_signature(sig);
275 }
276
277 let fields_bytes = fields_encoder.as_bytes();
278 let fields_len = fields_bytes.len() as u32;
279 let body_len = body.len() as u32;
280
281 self.push_u8(b'l'); self.push_u8(DBUS_MESSAGE_TYPE_METHOD_RETURN);
284 self.push_u8(0); self.push_u8(1); self.push_u32(body_len);
287 self.push_u32(serial);
288 self.push_u32(fields_len);
289
290 self.buffer.extend_from_slice(fields_bytes);
292
293 self.pad_to(8);
295
296 self.buffer.extend_from_slice(body);
298 }
299}
300
301pub struct DbusMessageDecoder<'a> {
303 data: &'a [u8],
304 offset: usize,
305}
306
307impl<'a> DbusMessageDecoder<'a> {
308 pub fn new(data: &'a [u8]) -> Self {
310 Self { data, offset: 0 }
311 }
312
313 pub fn align_to(&mut self, alignment: usize) {
315 let rem = self.offset % alignment;
316 if rem != 0 {
317 self.offset += alignment - rem;
318 }
319 }
320
321 pub fn read_u8(&mut self) -> Option<u8> {
323 if self.offset < self.data.len() {
324 let val = self.data[self.offset];
325 self.offset += 1;
326 Some(val)
327 } else {
328 None
329 }
330 }
331
332 pub fn read_u16(&mut self) -> Option<u16> {
334 self.align_to(2);
335 if self.offset + 2 <= self.data.len() {
336 let val =
337 u16::from_le_bytes(self.data[self.offset..self.offset + 2].try_into().unwrap());
338 self.offset += 2;
339 Some(val)
340 } else {
341 None
342 }
343 }
344
345 pub fn read_u32(&mut self) -> Option<u32> {
347 self.align_to(4);
348 if self.offset + 4 <= self.data.len() {
349 let val =
350 u32::from_le_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
351 self.offset += 4;
352 Some(val)
353 } else {
354 None
355 }
356 }
357
358 pub fn read_i32(&mut self) -> Option<i32> {
360 self.align_to(4);
361 if self.offset + 4 <= self.data.len() {
362 let val =
363 i32::from_le_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
364 self.offset += 4;
365 Some(val)
366 } else {
367 None
368 }
369 }
370
371 pub fn read_string(&mut self) -> Option<String> {
373 let len = self.read_u32()? as usize;
374 if self.offset + len < self.data.len() {
375 let bytes = &self.data[self.offset..self.offset + len];
376 let str = String::from_utf8_lossy(bytes).to_string();
377 self.offset += len + 1; Some(str)
379 } else {
380 None
381 }
382 }
383}
384
385pub struct DbusClient {
387 stream: UnixStream,
388 next_serial: u32,
389 pub unique_name: Option<String>,
390}
391
392impl DbusClient {
393 pub fn connect() -> Result<Self, String> {
395 let path = session_bus_socket_path()?;
396 Self::connect_to_path(&path)
397 }
398
399 pub fn connect_system() -> Result<Self, String> {
401 let path = system_bus_socket_path()?;
402 Self::connect_to_path(&path)
403 }
404
405 pub fn connect_to_path(socket_path: &str) -> Result<Self, String> {
407 let mut stream = UnixStream::connect(socket_path)
408 .map_err(|e| format!("Cannot connect to D-Bus socket \"{}\": {}", socket_path, e))?;
409
410 stream
411 .set_read_timeout(Some(Duration::from_millis(1500)))
412 .map_err(|e| format!("Failed to set read timeout: {}", e))?;
413
414 #[cfg(unix)]
415 let uid = unsafe { libc::getuid() };
416 #[cfg(not(unix))]
417 let uid = 1000;
418
419 let auth_payload = format_sasl_auth_request(uid);
421 stream
422 .write_all(&auth_payload)
423 .map_err(|e| format!("Failed to write SASL auth: {}", e))?;
424
425 let mut response = Vec::new();
427 let mut byte = [0u8; 1];
428 while let Ok(1) = stream.read(&mut byte) {
429 response.push(byte[0]);
430 if response.ends_with(b"\r\n") {
431 break;
432 }
433 }
434
435 let resp_str = String::from_utf8_lossy(&response);
436 if !resp_str.starts_with("OK") {
437 return Err(format!("D-Bus SASL auth rejected: {}", resp_str.trim()));
438 }
439
440 let mut client = Self {
441 stream,
442 next_serial: 1,
443 unique_name: None,
444 };
445
446 let name = client.call_hello()?;
448 client.unique_name = Some(name);
449
450 Ok(client)
451 }
452
453 pub fn next_serial(&mut self) -> u32 {
455 let s = self.next_serial;
456 self.next_serial += 1;
457 s
458 }
459
460 pub fn call_hello(&mut self) -> Result<String, String> {
462 let serial = self.next_serial();
463 let mut encoder = DbusMessageEncoder::new();
464 encoder.encode_method_call(
465 serial,
466 Some("org.freedesktop.DBus"),
467 "/org/freedesktop/DBus",
468 Some("org.freedesktop.DBus"),
469 "Hello",
470 None,
471 &[],
472 );
473
474 self.stream
475 .write_all(encoder.as_bytes())
476 .map_err(|e| format!("Failed to send DBus.Hello: {}", e))?;
477
478 let reply = self.read_message()?;
480 let mut decoder = DbusMessageDecoder::new(&reply);
481 if reply.len() < 16 {
483 return Err("D-Bus reply header too short".to_string());
484 }
485 let body_len = u32::from_le_bytes(reply[4..8].try_into().unwrap()) as usize;
486 let fields_len = u32::from_le_bytes(reply[12..16].try_into().unwrap()) as usize;
487 let mut header_total = 16 + fields_len;
488 if !header_total.is_multiple_of(8) {
489 header_total += 8 - (header_total % 8);
490 }
491
492 if reply.len() < header_total + body_len {
493 return Err("D-Bus reply payload truncated".to_string());
494 }
495
496 decoder.offset = header_total;
497 decoder
498 .read_string()
499 .ok_or_else(|| "Failed to parse unique name from DBus.Hello".to_string())
500 }
501
502 pub fn call_method(
504 &mut self,
505 destination: &str,
506 path: &str,
507 interface: &str,
508 member: &str,
509 signature: Option<&str>,
510 body: &[u8],
511 ) -> Result<Vec<u8>, String> {
512 let serial = self.next_serial();
513 let mut encoder = DbusMessageEncoder::new();
514 encoder.encode_method_call(
515 serial,
516 Some(destination),
517 path,
518 Some(interface),
519 member,
520 signature,
521 body,
522 );
523
524 self.stream
525 .write_all(encoder.as_bytes())
526 .map_err(|e| format!("D-Bus write error for {}.{}: {}", interface, member, e))?;
527
528 self.read_message()
529 }
530
531 pub fn read_message(&mut self) -> Result<Vec<u8>, String> {
533 let mut header = [0u8; 16];
534 self.stream
535 .read_exact(&mut header)
536 .map_err(|e| format!("Failed to read D-Bus message header: {}", e))?;
537
538 let body_len = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;
539 let fields_len = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
540
541 let mut header_fields = vec![0u8; fields_len];
542 if fields_len > 0 {
543 self.stream
544 .read_exact(&mut header_fields)
545 .map_err(|e| format!("Failed to read D-Bus header fields: {}", e))?;
546 }
547
548 let total_header = 16 + fields_len;
550 let rem = total_header % 8;
551 let pad_len = if rem != 0 { 8 - rem } else { 0 };
552 if pad_len > 0 {
553 let mut pad = vec![0u8; pad_len];
554 self.stream
555 .read_exact(&mut pad)
556 .map_err(|e| format!("Failed to read D-Bus header padding: {}", e))?;
557 }
558
559 let mut body = vec![0u8; body_len];
560 if body_len > 0 {
561 self.stream
562 .read_exact(&mut body)
563 .map_err(|e| format!("Failed to read D-Bus body: {}", e))?;
564 }
565
566 let mut full_msg = Vec::with_capacity(16 + fields_len + pad_len + body_len);
567 full_msg.extend_from_slice(&header);
568 full_msg.extend_from_slice(&header_fields);
569 full_msg.resize(full_msg.len() + pad_len, 0);
570 full_msg.extend_from_slice(&body);
571 Ok(full_msg)
572 }
573}
574
575pub fn show_desktop_notification(
579 summary: &str,
580 body: &str,
581 icon: Option<&str>,
582 timeout_ms: i32,
583) -> Result<u32, String> {
584 let mut client = DbusClient::connect()?;
585
586 let mut body_encoder = DbusMessageEncoder::new();
589 body_encoder.push_string("Strata");
590 body_encoder.push_u32(0); body_encoder.push_string(icon.unwrap_or("dialog-information"));
592 body_encoder.push_string(summary);
593 body_encoder.push_string(body);
594
595 body_encoder.push_u32(0);
597
598 body_encoder.push_u32(0);
600
601 body_encoder.push_i32(timeout_ms);
603
604 let reply = client.call_method(
605 "org.freedesktop.Notifications",
606 "/org/freedesktop/Notifications",
607 "org.freedesktop.Notifications",
608 "Notify",
609 Some("susssasa{sv}i"),
610 body_encoder.as_bytes(),
611 )?;
612
613 if reply.len() < 16 {
614 return Err("Notification reply payload too short".to_string());
615 }
616
617 let fields_len = u32::from_le_bytes(reply[12..16].try_into().unwrap()) as usize;
618 let mut header_total = 16 + fields_len;
619 if !header_total.is_multiple_of(8) {
620 header_total += 8 - (header_total % 8);
621 }
622
623 if reply.len() >= header_total + 4 {
624 let notif_id =
625 u32::from_le_bytes(reply[header_total..header_total + 4].try_into().unwrap());
626 Ok(notif_id)
627 } else {
628 Ok(1)
629 }
630}
631
632#[derive(Debug, Clone, PartialEq)]
634pub enum DbusVariantValue {
635 Byte(u8),
636 Bool(bool),
637 Uint32(u32),
638 Int32(i32),
639 String(String),
640 ObjectPath(String),
641}
642
643impl DbusMessageEncoder {
644 pub fn push_bool(&mut self, val: bool) {
646 self.push_u32(if val { 1 } else { 0 });
647 }
648
649 pub fn push_string_array(&mut self, items: &[&str]) {
651 self.pad_to(4);
652 let len_pos = self.buffer.len();
653 self.buffer.extend_from_slice(&0u32.to_le_bytes());
654 let data_start = self.buffer.len();
655 for item in items {
656 self.push_string(item);
657 }
658 let byte_len = (self.buffer.len() - data_start) as u32;
659 self.buffer[len_pos..len_pos + 4].copy_from_slice(&byte_len.to_le_bytes());
660 }
661
662 pub fn push_variant(&mut self, val: &DbusVariantValue) {
664 match val {
665 DbusVariantValue::Byte(b) => {
666 self.push_signature("y");
667 self.push_u8(*b);
668 }
669 DbusVariantValue::Bool(b) => {
670 self.push_signature("b");
671 self.push_bool(*b);
672 }
673 DbusVariantValue::Uint32(u) => {
674 self.push_signature("u");
675 self.push_u32(*u);
676 }
677 DbusVariantValue::Int32(i) => {
678 self.push_signature("i");
679 self.push_i32(*i);
680 }
681 DbusVariantValue::String(s) => {
682 self.push_signature("s");
683 self.push_string(s);
684 }
685 DbusVariantValue::ObjectPath(o) => {
686 self.push_signature("o");
687 self.push_object_path(o);
688 }
689 }
690 }
691
692 pub fn push_dict_sv(&mut self, entries: &[(&str, DbusVariantValue)]) {
694 self.pad_to(4);
695 let len_pos = self.buffer.len();
696 self.buffer.extend_from_slice(&0u32.to_le_bytes());
697 self.pad_to(8);
699 let data_start = self.buffer.len();
700 for (k, v) in entries {
701 self.pad_to(8);
702 self.push_string(k);
703 self.push_variant(v);
704 }
705 let byte_len = (self.buffer.len() - data_start) as u32;
706 self.buffer[len_pos..len_pos + 4].copy_from_slice(&byte_len.to_le_bytes());
707 }
708}
709
710impl<'a> DbusMessageDecoder<'a> {
711 pub fn body_from_message(full_msg: &'a [u8]) -> Option<Self> {
713 if full_msg.len() < 16 {
714 return None;
715 }
716 let body_len = u32::from_le_bytes(full_msg[4..8].try_into().ok()?) as usize;
717 let fields_len = u32::from_le_bytes(full_msg[12..16].try_into().ok()?) as usize;
718 let mut header_total = 16 + fields_len;
719 if !header_total.is_multiple_of(8) {
720 header_total += 8 - (header_total % 8);
721 }
722 if full_msg.len() < header_total + body_len {
723 return None;
724 }
725 Some(Self::new(&full_msg[header_total..header_total + body_len]))
726 }
727
728 pub fn remaining(&self) -> usize {
729 self.data.len().saturating_sub(self.offset)
730 }
731
732 pub fn read_bool(&mut self) -> Option<bool> {
733 self.read_u32().map(|u| u != 0)
734 }
735
736 pub fn read_signature(&mut self) -> Option<String> {
737 let len = self.read_u8()? as usize;
738 let bytes = self.data.get(self.offset..self.offset + len)?;
739 self.offset += len;
740 if self.offset < self.data.len() {
741 self.offset += 1;
742 }
743 Some(String::from_utf8_lossy(bytes).into_owned())
744 }
745}
746
747impl DbusClient {
748 pub fn add_match_rule(&mut self, rule: &str) -> Result<(), String> {
750 let mut body = DbusMessageEncoder::new();
751 body.push_string(rule);
752 let _ = self.call_method(
753 "org.freedesktop.DBus",
754 "/org/freedesktop/DBus",
755 "org.freedesktop.DBus",
756 "AddMatch",
757 Some("s"),
758 body.as_bytes(),
759 )?;
760 Ok(())
761 }
762}
763
764pub fn show_desktop_notification_rich(
767 app_name: &str,
768 replaces_id: u32,
769 icon: Option<&str>,
770 summary: &str,
771 body: &str,
772 actions: &[(&str, &str)],
773 urgency: u8,
774 category: Option<&str>,
775 timeout_ms: i32,
776) -> Result<u32, String> {
777 let mut client = DbusClient::connect()?;
778 let mut body_encoder = DbusMessageEncoder::new();
779 body_encoder.push_string(app_name);
780 body_encoder.push_u32(replaces_id);
781 body_encoder.push_string(icon.unwrap_or("dialog-information"));
782 body_encoder.push_string(summary);
783 body_encoder.push_string(body);
784
785 let mut flat_actions: Vec<&str> = Vec::with_capacity(actions.len() * 2);
787 for (k, label) in actions {
788 flat_actions.push(k);
789 flat_actions.push(label);
790 }
791 body_encoder.push_string_array(&flat_actions);
792
793 let mut hints: Vec<(&str, DbusVariantValue)> =
794 vec![("urgency", DbusVariantValue::Byte(urgency.min(2)))];
795 if let Some(cat) = category {
796 hints.push(("category", DbusVariantValue::String(cat.to_string())));
797 }
798 body_encoder.push_dict_sv(&hints);
799 body_encoder.push_i32(timeout_ms);
800
801 let reply = client.call_method(
802 "org.freedesktop.Notifications",
803 "/org/freedesktop/Notifications",
804 "org.freedesktop.Notifications",
805 "Notify",
806 Some("susssasa{sv}i"),
807 body_encoder.as_bytes(),
808 )?;
809
810 if let Some(mut dec) = DbusMessageDecoder::body_from_message(&reply) {
811 if let Some(id) = dec.read_u32() {
812 return Ok(id);
813 }
814 }
815 Ok(replaces_id.max(1))
816}
817
818pub fn close_desktop_notification(id: u32) -> Result<(), String> {
820 let mut client = DbusClient::connect()?;
821 let mut body = DbusMessageEncoder::new();
822 body.push_u32(id);
823 let _ = client.call_method(
824 "org.freedesktop.Notifications",
825 "/org/freedesktop/Notifications",
826 "org.freedesktop.Notifications",
827 "CloseNotification",
828 Some("u"),
829 body.as_bytes(),
830 )?;
831 Ok(())
832}