1use std::collections::{BTreeSet, HashMap};
30use std::fmt;
31use std::io::{self, Read, Write};
32use std::sync::atomic::{AtomicU32, Ordering};
33use std::sync::mpsc;
34use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
35use std::thread::{self, ThreadId};
36use std::time::Duration;
37
38pub mod sni;
39
40pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2);
42
43pub const BUS_NAME: &str = "org.freedesktop.DBus";
45pub const BUS_PATH: &str = "/org/freedesktop/DBus";
47pub const BUS_INTERFACE: &str = "org.freedesktop.DBus";
49pub const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
51pub const INTROSPECTABLE_INTERFACE: &str = "org.freedesktop.DBus.Introspectable";
53pub const PEER_INTERFACE: &str = "org.freedesktop.DBus.Peer";
55
56pub const NAME_FLAG_ALLOW_REPLACEMENT: u32 = 0x1;
58pub const NAME_FLAG_REPLACE_EXISTING: u32 = 0x2;
60pub const NAME_FLAG_DO_NOT_QUEUE: u32 = 0x4;
62pub const NAME_REPLY_PRIMARY_OWNER: u32 = 1;
64pub const NAME_REPLY_IN_QUEUE: u32 = 2;
66pub const NAME_REPLY_EXISTS: u32 = 3;
68pub const NAME_REPLY_ALREADY_OWNER: u32 = 4;
70
71pub const FLAG_NO_REPLY_EXPECTED: u8 = 0x1;
73pub const FLAG_NO_AUTO_START: u8 = 0x2;
75
76const MAX_MESSAGE: usize = 128 * 1024 * 1024;
78const MAX_ARRAY: usize = 64 * 1024 * 1024;
80const MAX_DEPTH: u32 = 64;
82
83#[derive(Debug)]
89pub enum Error {
90 Unsupported,
92 NoBus(String),
94 Io(io::Error),
96 Auth(String),
98 Protocol(String),
100 Disconnected,
102 Timeout,
104 ReaderThread,
107 Remote {
109 name: String,
111 message: String,
113 },
114}
115
116impl fmt::Display for Error {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 match self {
119 Error::Unsupported => f.write_str("D-Bus is not available on this platform"),
120 Error::NoBus(why) => write!(f, "no session bus: {why}"),
121 Error::Io(e) => write!(f, "D-Bus socket error: {e}"),
122 Error::Auth(why) => write!(f, "D-Bus authentication failed: {why}"),
123 Error::Protocol(why) => write!(f, "D-Bus protocol error: {why}"),
124 Error::Disconnected => f.write_str("D-Bus connection closed"),
125 Error::Timeout => f.write_str("D-Bus call timed out"),
126 Error::ReaderThread => {
127 f.write_str("blocking D-Bus call made from the connection's reader thread")
128 }
129 Error::Remote { name, message } if message.is_empty() => f.write_str(name),
130 Error::Remote { name, message } => write!(f, "{name}: {message}"),
131 }
132 }
133}
134
135impl std::error::Error for Error {
136 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
137 match self {
138 Error::Io(e) => Some(e),
139 _ => None,
140 }
141 }
142}
143
144impl From<io::Error> for Error {
145 fn from(e: io::Error) -> Self {
146 Error::Io(e)
147 }
148}
149
150fn protocol(why: impl Into<String>) -> Error {
151 Error::Protocol(why.into())
152}
153
154#[derive(Clone, Debug, PartialEq)]
161pub enum Value {
162 Byte(u8),
164 Bool(bool),
166 I16(i16),
168 U16(u16),
170 I32(i32),
172 U32(u32),
174 I64(i64),
176 U64(u64),
178 Double(f64),
180 Str(String),
182 ObjectPath(String),
184 Signature(String),
186 Array {
189 elem: String,
191 items: Vec<Value>,
193 },
194 Struct(Vec<Value>),
196 DictEntry(Box<Value>, Box<Value>),
198 Variant(Box<Value>),
200}
201
202impl Value {
203 pub fn str(s: impl Into<String>) -> Value {
205 Value::Str(s.into())
206 }
207
208 pub fn path(p: impl Into<String>) -> Value {
210 Value::ObjectPath(p.into())
211 }
212
213 #[must_use]
215 pub fn variant(v: Value) -> Value {
216 Value::Variant(Box::new(v))
217 }
218
219 pub fn array(elem: impl Into<String>, items: Vec<Value>) -> Value {
221 Value::Array {
222 elem: elem.into(),
223 items,
224 }
225 }
226
227 #[must_use]
229 pub fn bytes(bytes: &[u8]) -> Value {
230 Value::array("y", bytes.iter().map(|b| Value::Byte(*b)).collect())
231 }
232
233 pub fn strings<S: AsRef<str>>(items: &[S]) -> Value {
235 Value::array("s", items.iter().map(|s| Value::str(s.as_ref())).collect())
236 }
237
238 pub fn dict(
240 key: &str,
241 value: &str,
242 entries: impl IntoIterator<Item = (Value, Value)>,
243 ) -> Value {
244 Value::array(
245 format!("{{{key}{value}}}"),
246 entries
247 .into_iter()
248 .map(|(k, v)| Value::DictEntry(Box::new(k), Box::new(v)))
249 .collect(),
250 )
251 }
252
253 pub fn props<K: Into<String>>(entries: impl IntoIterator<Item = (K, Value)>) -> Value {
255 Value::dict(
256 "s",
257 "v",
258 entries
259 .into_iter()
260 .map(|(k, v)| (Value::Str(k.into()), Value::variant(v))),
261 )
262 }
263
264 #[must_use]
266 pub fn signature(&self) -> String {
267 let mut s = String::new();
268 self.write_signature(&mut s);
269 s
270 }
271
272 fn write_signature(&self, out: &mut String) {
273 match self {
274 Value::Array { elem, .. } => {
275 out.push('a');
276 out.push_str(elem);
277 }
278 Value::Struct(fields) => {
279 out.push('(');
280 for f in fields {
281 f.write_signature(out);
282 }
283 out.push(')');
284 }
285 Value::DictEntry(k, v) => {
286 out.push('{');
287 k.write_signature(out);
288 v.write_signature(out);
289 out.push('}');
290 }
291 other => out.push(other.basic_code().unwrap_or('v')),
292 }
293 }
294
295 fn basic_code(&self) -> Option<char> {
297 Some(match self {
298 Value::Byte(_) => 'y',
299 Value::Bool(_) => 'b',
300 Value::I16(_) => 'n',
301 Value::U16(_) => 'q',
302 Value::I32(_) => 'i',
303 Value::U32(_) => 'u',
304 Value::I64(_) => 'x',
305 Value::U64(_) => 't',
306 Value::Double(_) => 'd',
307 Value::Str(_) => 's',
308 Value::ObjectPath(_) => 'o',
309 Value::Signature(_) => 'g',
310 Value::Variant(_) => 'v',
311 Value::Array { .. } | Value::Struct(_) | Value::DictEntry(..) => return None,
312 })
313 }
314
315 fn conforms(&self, sig: &str) -> bool {
317 match self {
318 Value::Array { elem, .. } => sig.strip_prefix('a') == Some(elem.as_str()),
319 Value::Struct(fields) => {
320 let Some(mut inner) = sig.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
321 else {
322 return false;
323 };
324 for f in fields {
325 match split_first_type(inner) {
326 Ok((first, rest)) if f.conforms(first) => inner = rest,
327 _ => return false,
328 }
329 }
330 inner.is_empty() && !fields.is_empty()
331 }
332 Value::DictEntry(k, v) => {
333 let Some(inner) = sig.strip_prefix('{').and_then(|s| s.strip_suffix('}')) else {
334 return false;
335 };
336 match split_first_type(inner) {
337 Ok((first, rest)) => k.conforms(first) && v.conforms(rest),
338 Err(_) => false,
339 }
340 }
341 basic => {
342 let mut chars = sig.chars();
343 basic.basic_code() == chars.next() && chars.next().is_none()
344 }
345 }
346 }
347
348 #[must_use]
350 pub fn as_str(&self) -> Option<&str> {
351 match self {
352 Value::Str(s) | Value::ObjectPath(s) | Value::Signature(s) => Some(s),
353 Value::Variant(v) => v.as_str(),
354 _ => None,
355 }
356 }
357
358 #[must_use]
360 pub fn as_bool(&self) -> Option<bool> {
361 match self {
362 Value::Bool(b) => Some(*b),
363 Value::Variant(v) => v.as_bool(),
364 _ => None,
365 }
366 }
367
368 #[must_use]
371 pub fn as_i64(&self) -> Option<i64> {
372 match self {
373 Value::Byte(n) => Some(i64::from(*n)),
374 Value::I16(n) => Some(i64::from(*n)),
375 Value::U16(n) => Some(i64::from(*n)),
376 Value::I32(n) => Some(i64::from(*n)),
377 Value::U32(n) => Some(i64::from(*n)),
378 Value::I64(n) => Some(*n),
379 Value::U64(n) => i64::try_from(*n).ok(),
380 Value::Variant(v) => v.as_i64(),
381 _ => None,
382 }
383 }
384
385 #[must_use]
387 pub fn as_f64(&self) -> Option<f64> {
388 match self {
389 Value::Double(d) => Some(*d),
390 Value::Variant(v) => v.as_f64(),
391 other => other.as_i64().map(|n| n as f64),
392 }
393 }
394
395 #[must_use]
397 pub fn as_array(&self) -> Option<&[Value]> {
398 match self {
399 Value::Array { items, .. } => Some(items),
400 Value::Variant(v) => v.as_array(),
401 _ => None,
402 }
403 }
404
405 #[must_use]
407 pub fn as_struct(&self) -> Option<&[Value]> {
408 match self {
409 Value::Struct(fields) => Some(fields),
410 Value::Variant(v) => v.as_struct(),
411 _ => None,
412 }
413 }
414
415 #[must_use]
417 pub fn unwrap_variant(&self) -> &Value {
418 match self {
419 Value::Variant(v) => v.unwrap_variant(),
420 other => other,
421 }
422 }
423
424 #[must_use]
427 pub fn dict_get(&self, key: &str) -> Option<&Value> {
428 self.as_array()?.iter().find_map(|item| match item {
429 Value::DictEntry(k, v) if k.as_str() == Some(key) => Some(v.unwrap_variant()),
430 _ => None,
431 })
432 }
433}
434
435fn split_first_type(sig: &str) -> Result<(&str, &str), Error> {
437 let len = complete_type_len(sig.as_bytes(), 0)?;
438 Ok(sig.split_at(len))
439}
440
441fn complete_type_len(sig: &[u8], depth: u32) -> Result<usize, Error> {
442 if depth > MAX_DEPTH {
443 return Err(protocol("signature nests too deeply"));
444 }
445 match sig.first() {
446 None => Err(protocol("empty signature")),
447 Some(
448 b'y' | b'b' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'd' | b's' | b'o' | b'g'
449 | b'v',
450 ) => Ok(1),
451 Some(b'a') => Ok(1 + complete_type_len(&sig[1..], depth + 1)?),
452 Some(b'(') => {
453 let mut at = 1;
454 while sig.get(at) != Some(&b')') {
455 if at >= sig.len() {
456 return Err(protocol("unterminated struct in signature"));
457 }
458 at += complete_type_len(&sig[at..], depth + 1)?;
459 }
460 if at == 1 {
461 return Err(protocol("empty struct in signature"));
462 }
463 Ok(at + 1)
464 }
465 Some(b'{') => {
466 let key = sig.get(1).copied();
467 if !matches!(
468 key,
469 Some(
470 b'y' | b'b'
471 | b'n'
472 | b'q'
473 | b'i'
474 | b'u'
475 | b'x'
476 | b't'
477 | b'd'
478 | b's'
479 | b'o'
480 | b'g'
481 )
482 ) {
483 return Err(protocol("dict entry key must be a basic type"));
484 }
485 let value = complete_type_len(&sig[2..], depth + 1)?;
486 if sig.get(2 + value) != Some(&b'}') {
487 return Err(protocol("dict entry must hold exactly two types"));
488 }
489 Ok(value + 3)
490 }
491 Some(c) => Err(protocol(format!(
492 "unsupported type code {:?} in signature",
493 char::from(*c)
494 ))),
495 }
496}
497
498fn validate_signature(sig: &str) -> Result<(), Error> {
500 if sig.len() > 255 {
501 return Err(protocol("signature longer than 255 bytes"));
502 }
503 let mut rest = sig;
504 while !rest.is_empty() {
505 rest = split_first_type(rest)?.1;
506 }
507 Ok(())
508}
509
510fn alignment(sig: &str) -> usize {
512 match sig.as_bytes().first() {
513 Some(b'n' | b'q') => 2,
514 Some(b'b' | b'i' | b'u' | b's' | b'o' | b'a' | b'h') => 4,
515 Some(b'x' | b't' | b'd' | b'(' | b'{') => 8,
516 _ => 1,
517 }
518}
519
520#[must_use]
522pub fn is_valid_object_path(p: &str) -> bool {
523 if p == "/" {
524 return true;
525 }
526 let Some(rest) = p.strip_prefix('/') else {
527 return false;
528 };
529 rest.split('/')
530 .all(|seg| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'))
531}
532
533fn is_valid_interface(name: &str) -> bool {
536 name.len() <= 255
537 && name.split('.').count() >= 2
538 && name.split('.').all(|el| {
539 !el.is_empty()
540 && !el.starts_with(|c: char| c.is_ascii_digit())
541 && el.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
542 })
543}
544
545fn is_valid_member(name: &str) -> bool {
547 !name.is_empty()
548 && name.len() <= 255
549 && !name.starts_with(|c: char| c.is_ascii_digit())
550 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
551}
552
553fn is_valid_bus_name(name: &str) -> bool {
555 let (unique, body) = match name.strip_prefix(':') {
556 Some(rest) => (true, rest),
557 None => (false, name),
558 };
559 name.len() <= 255
560 && body.split('.').count() >= 2
561 && body.split('.').all(|el| {
562 !el.is_empty()
563 && (unique || !el.starts_with(|c: char| c.is_ascii_digit()))
564 && el
565 .bytes()
566 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
567 })
568}
569
570struct Encoder {
577 buf: Vec<u8>,
578 big: bool,
579}
580
581impl Encoder {
582 fn new(big: bool) -> Self {
583 Encoder {
584 buf: Vec::new(),
585 big,
586 }
587 }
588
589 fn pad(&mut self, align: usize) {
590 let padded = self.buf.len().next_multiple_of(align);
591 self.buf.resize(padded, 0);
592 }
593
594 fn put(&mut self, le: &[u8], be: &[u8]) {
595 self.pad(le.len());
596 self.buf.extend_from_slice(if self.big { be } else { le });
597 }
598
599 fn u32(&mut self, v: u32) {
600 self.put(&v.to_le_bytes(), &v.to_be_bytes());
601 }
602
603 fn string(&mut self, s: &str) -> Result<(), Error> {
604 if s.contains('\0') {
605 return Err(protocol("string contains a NUL byte"));
606 }
607 let len = u32::try_from(s.len()).map_err(|_| protocol("string too long"))?;
608 self.u32(len);
609 self.buf.extend_from_slice(s.as_bytes());
610 self.buf.push(0);
611 Ok(())
612 }
613
614 fn signature(&mut self, s: &str) -> Result<(), Error> {
615 validate_signature(s)?;
616 self.buf.push(s.len() as u8);
618 self.buf.extend_from_slice(s.as_bytes());
619 self.buf.push(0);
620 Ok(())
621 }
622
623 fn value(&mut self, v: &Value, depth: u32) -> Result<(), Error> {
624 if depth > MAX_DEPTH {
625 return Err(protocol("value nests too deeply"));
626 }
627 match v {
628 Value::Byte(b) => self.buf.push(*b),
629 Value::Bool(b) => self.u32(u32::from(*b)),
630 Value::I16(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
631 Value::U16(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
632 Value::I32(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
633 Value::U32(n) => self.u32(*n),
634 Value::I64(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
635 Value::U64(n) => self.put(&n.to_le_bytes(), &n.to_be_bytes()),
636 Value::Double(d) => self.put(&d.to_le_bytes(), &d.to_be_bytes()),
637 Value::Str(s) => self.string(s)?,
638 Value::ObjectPath(p) => {
639 if !is_valid_object_path(p) {
640 return Err(protocol(format!("invalid object path {p:?}")));
641 }
642 self.string(p)?;
643 }
644 Value::Signature(s) => self.signature(s)?,
645 Value::Array { elem, items } => {
646 let (_, rest) = split_first_type(elem)?;
647 if !rest.is_empty() {
648 return Err(protocol(format!(
649 "array element signature {elem:?} is not a single complete type"
650 )));
651 }
652 self.pad(4);
653 let len_at = self.buf.len();
654 self.buf.extend_from_slice(&[0; 4]);
655 self.pad(alignment(elem));
658 let start = self.buf.len();
659 for item in items {
660 if !item.conforms(elem) {
661 return Err(protocol(format!(
662 "array item {} does not match element signature {elem}",
663 item.signature()
664 )));
665 }
666 self.value(item, depth + 1)?;
667 }
668 let len = self.buf.len() - start;
669 if len > MAX_ARRAY {
670 return Err(protocol("array longer than 64 MiB"));
671 }
672 let len = len as u32;
674 let bytes = if self.big {
675 len.to_be_bytes()
676 } else {
677 len.to_le_bytes()
678 };
679 self.buf[len_at..len_at + 4].copy_from_slice(&bytes);
680 }
681 Value::Struct(fields) => {
682 if fields.is_empty() {
683 return Err(protocol("a struct needs at least one field"));
684 }
685 self.pad(8);
686 for f in fields {
687 self.value(f, depth + 1)?;
688 }
689 }
690 Value::DictEntry(k, val) => {
691 if matches!(
692 **k,
693 Value::Variant(_)
694 | Value::Array { .. }
695 | Value::Struct(_)
696 | Value::DictEntry(..)
697 ) {
698 return Err(protocol("dict entry key must be a basic type"));
699 }
700 self.pad(8);
701 self.value(k, depth + 1)?;
702 self.value(val, depth + 1)?;
703 }
704 Value::Variant(inner) => {
705 let sig = inner.signature();
706 self.signature(&sig)?;
707 self.value(inner, depth + 1)?;
708 }
709 }
710 Ok(())
711 }
712}
713
714struct Decoder<'a> {
716 data: &'a [u8],
717 pos: usize,
718 big: bool,
719}
720
721impl<'a> Decoder<'a> {
722 fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
723 let end = self
724 .pos
725 .checked_add(n)
726 .filter(|end| *end <= self.data.len())
727 .ok_or_else(|| protocol("message truncated"))?;
728 let bytes = &self.data[self.pos..end];
729 self.pos = end;
730 Ok(bytes)
731 }
732
733 fn align(&mut self, a: usize) -> Result<(), Error> {
734 let to = self.pos.next_multiple_of(a);
735 if to > self.data.len() {
736 return Err(protocol("message truncated in padding"));
737 }
738 self.pos = to;
739 Ok(())
740 }
741
742 fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Error> {
743 self.align(N)?;
744 let mut out = [0; N];
745 out.copy_from_slice(self.take(N)?);
746 Ok(out)
747 }
748
749 fn u32(&mut self) -> Result<u32, Error> {
750 let b = self.fixed::<4>()?;
751 Ok(if self.big {
752 u32::from_be_bytes(b)
753 } else {
754 u32::from_le_bytes(b)
755 })
756 }
757
758 fn string(&mut self) -> Result<String, Error> {
759 let len = self.u32()? as usize;
760 let bytes = self.take(len)?;
761 if self.take(1)? != [0] || bytes.contains(&0) {
762 return Err(protocol("string is not NUL-terminated"));
763 }
764 String::from_utf8(bytes.to_vec()).map_err(|_| protocol("string is not UTF-8"))
765 }
766
767 fn signature(&mut self) -> Result<String, Error> {
768 let len = usize::from(self.take(1)?[0]);
769 let bytes = self.take(len)?;
770 if self.take(1)? != [0] {
771 return Err(protocol("signature is not NUL-terminated"));
772 }
773 let sig = std::str::from_utf8(bytes).map_err(|_| protocol("signature is not ASCII"))?;
774 validate_signature(sig)?;
775 Ok(sig.to_owned())
776 }
777
778 fn value(&mut self, sig: &str, depth: u32) -> Result<Value, Error> {
780 if depth > MAX_DEPTH {
781 return Err(protocol("value nests too deeply"));
782 }
783 let big = self.big;
784 macro_rules! num {
785 ($t:ty, $n:literal, $variant:ident) => {{
786 let b = self.fixed::<$n>()?;
787 Value::$variant(if big {
788 <$t>::from_be_bytes(b)
789 } else {
790 <$t>::from_le_bytes(b)
791 })
792 }};
793 }
794 Ok(match sig.as_bytes().first() {
795 Some(b'y') => Value::Byte(self.take(1)?[0]),
796 Some(b'b') => match self.u32()? {
797 0 => Value::Bool(false),
798 1 => Value::Bool(true),
799 n => return Err(protocol(format!("boolean holds {n}"))),
800 },
801 Some(b'n') => num!(i16, 2, I16),
802 Some(b'q') => num!(u16, 2, U16),
803 Some(b'i') => num!(i32, 4, I32),
804 Some(b'u') => num!(u32, 4, U32),
805 Some(b'x') => num!(i64, 8, I64),
806 Some(b't') => num!(u64, 8, U64),
807 Some(b'd') => num!(f64, 8, Double),
808 Some(b's') => Value::Str(self.string()?),
809 Some(b'o') => {
810 let p = self.string()?;
811 if !is_valid_object_path(&p) {
812 return Err(protocol(format!("invalid object path {p:?}")));
813 }
814 Value::ObjectPath(p)
815 }
816 Some(b'g') => Value::Signature(self.signature()?),
817 Some(b'v') => {
818 let inner = self.signature()?;
819 let (first, rest) = split_first_type(&inner)?;
820 if !rest.is_empty() {
821 return Err(protocol("variant signature is not a single complete type"));
822 }
823 Value::Variant(Box::new(self.value(first, depth + 1)?))
824 }
825 Some(b'a') => {
826 let elem = &sig[1..];
827 let len = self.u32()? as usize;
828 if len > MAX_ARRAY {
829 return Err(protocol("array longer than 64 MiB"));
830 }
831 self.align(alignment(elem))?;
832 let end = self
833 .pos
834 .checked_add(len)
835 .filter(|end| *end <= self.data.len())
836 .ok_or_else(|| protocol("array runs past the message"))?;
837 let mut items = Vec::new();
838 while self.pos < end {
839 items.push(self.value(elem, depth + 1)?);
840 }
841 if self.pos != end {
842 return Err(protocol("array items overrun the array length"));
843 }
844 Value::Array {
845 elem: elem.to_owned(),
846 items,
847 }
848 }
849 Some(b'(') => {
850 self.align(8)?;
851 let mut inner = &sig[1..sig.len() - 1];
852 let mut fields = Vec::new();
853 while !inner.is_empty() {
854 let (first, rest) = split_first_type(inner)?;
855 fields.push(self.value(first, depth + 1)?);
856 inner = rest;
857 }
858 Value::Struct(fields)
859 }
860 Some(b'{') => {
861 self.align(8)?;
862 let (key, rest) = split_first_type(&sig[1..sig.len() - 1])?;
863 let k = self.value(key, depth + 1)?;
864 let v = self.value(rest, depth + 1)?;
865 Value::DictEntry(Box::new(k), Box::new(v))
866 }
867 _ => return Err(protocol(format!("cannot read type {sig:?}"))),
868 })
869 }
870}
871
872pub fn marshal(values: &[Value]) -> Result<Vec<u8>, Error> {
879 let mut e = Encoder::new(false);
880 for v in values {
881 e.value(v, 0)?;
882 }
883 Ok(e.buf)
884}
885
886pub fn unmarshal(bytes: &[u8], signature: &str, big_endian: bool) -> Result<Vec<Value>, Error> {
894 validate_signature(signature)?;
895 let mut d = Decoder {
896 data: bytes,
897 pos: 0,
898 big: big_endian,
899 };
900 let mut out = Vec::new();
901 let mut rest = signature;
902 while !rest.is_empty() {
903 let (first, tail) = split_first_type(rest)?;
904 out.push(d.value(first, 0)?);
905 rest = tail;
906 }
907 if d.pos != bytes.len() {
908 return Err(protocol("trailing bytes after the body"));
909 }
910 Ok(out)
911}
912
913#[derive(Clone, Copy, Debug, PartialEq, Eq)]
919pub enum MessageType {
920 MethodCall,
922 MethodReturn,
924 Error,
926 Signal,
928}
929
930impl MessageType {
931 fn code(self) -> u8 {
932 match self {
933 MessageType::MethodCall => 1,
934 MessageType::MethodReturn => 2,
935 MessageType::Error => 3,
936 MessageType::Signal => 4,
937 }
938 }
939}
940
941#[derive(Clone, Debug, PartialEq)]
944pub struct Message {
945 pub message_type: MessageType,
947 pub flags: u8,
949 pub serial: u32,
951 pub path: Option<String>,
953 pub interface: Option<String>,
955 pub member: Option<String>,
957 pub error_name: Option<String>,
959 pub reply_serial: Option<u32>,
961 pub destination: Option<String>,
963 pub sender: Option<String>,
965 pub body: Vec<Value>,
967}
968
969impl Message {
970 fn empty(message_type: MessageType) -> Message {
971 Message {
972 message_type,
973 flags: 0,
974 serial: 0,
975 path: None,
976 interface: None,
977 member: None,
978 error_name: None,
979 reply_serial: None,
980 destination: None,
981 sender: None,
982 body: Vec::new(),
983 }
984 }
985
986 #[must_use]
988 pub fn method_call(
989 destination: &str,
990 path: &str,
991 interface: &str,
992 member: &str,
993 body: Vec<Value>,
994 ) -> Message {
995 Message {
996 path: Some(path.to_owned()),
997 interface: Some(interface.to_owned()),
998 member: Some(member.to_owned()),
999 destination: Some(destination.to_owned()),
1000 body,
1001 ..Message::empty(MessageType::MethodCall)
1002 }
1003 }
1004
1005 #[must_use]
1007 pub fn signal(path: &str, interface: &str, member: &str, body: Vec<Value>) -> Message {
1008 Message {
1009 path: Some(path.to_owned()),
1010 interface: Some(interface.to_owned()),
1011 member: Some(member.to_owned()),
1012 body,
1013 ..Message::empty(MessageType::Signal)
1014 }
1015 }
1016
1017 fn reply_to(call: &Message, body: Vec<Value>) -> Message {
1018 Message {
1019 reply_serial: Some(call.serial),
1020 destination: call.sender.clone(),
1021 flags: FLAG_NO_REPLY_EXPECTED,
1022 body,
1023 ..Message::empty(MessageType::MethodReturn)
1024 }
1025 }
1026
1027 fn error_to(call: &Message, name: &str, text: &str) -> Message {
1028 Message {
1029 reply_serial: Some(call.serial),
1030 destination: call.sender.clone(),
1031 error_name: Some(name.to_owned()),
1032 flags: FLAG_NO_REPLY_EXPECTED,
1033 body: vec![Value::str(text)],
1034 ..Message::empty(MessageType::Error)
1035 }
1036 }
1037
1038 #[must_use]
1040 pub fn signature(&self) -> String {
1041 let mut s = String::new();
1042 for v in &self.body {
1043 v.write_signature(&mut s);
1044 }
1045 s
1046 }
1047
1048 pub fn encode(&self) -> Result<Vec<u8>, Error> {
1055 self.encode_with(false)
1056 }
1057
1058 fn encode_with(&self, big: bool) -> Result<Vec<u8>, Error> {
1059 self.check_fields()?;
1060 let mut body = Encoder::new(big);
1061 for v in &self.body {
1062 body.value(v, 0)?;
1063 }
1064 let sig = self.signature();
1065 validate_signature(&sig)?;
1066
1067 let field = |code: u8, v: Value| Value::Struct(vec![Value::Byte(code), Value::variant(v)]);
1068 let mut fields = Vec::new();
1069 if let Some(p) = &self.path {
1070 fields.push(field(1, Value::path(p)));
1071 }
1072 if let Some(s) = &self.interface {
1073 fields.push(field(2, Value::str(s)));
1074 }
1075 if let Some(s) = &self.member {
1076 fields.push(field(3, Value::str(s)));
1077 }
1078 if let Some(s) = &self.error_name {
1079 fields.push(field(4, Value::str(s)));
1080 }
1081 if let Some(n) = self.reply_serial {
1082 fields.push(field(5, Value::U32(n)));
1083 }
1084 if let Some(s) = &self.destination {
1085 fields.push(field(6, Value::str(s)));
1086 }
1087 if let Some(s) = &self.sender {
1088 fields.push(field(7, Value::str(s)));
1089 }
1090 if !sig.is_empty() {
1091 fields.push(field(8, Value::Signature(sig)));
1092 }
1093
1094 let mut e = Encoder::new(big);
1095 e.buf.extend_from_slice(&[
1096 if big { b'B' } else { b'l' },
1097 self.message_type.code(),
1098 self.flags,
1099 1,
1100 ]);
1101 let body_len = u32::try_from(body.buf.len()).map_err(|_| protocol("body too long"))?;
1102 e.u32(body_len);
1103 e.u32(self.serial);
1104 e.value(&Value::array("(yv)", fields), 0)?;
1105 e.pad(8);
1106 e.buf.extend_from_slice(&body.buf);
1107 if e.buf.len() > MAX_MESSAGE {
1108 return Err(protocol("message longer than 128 MiB"));
1109 }
1110 Ok(e.buf)
1111 }
1112
1113 fn check_fields(&self) -> Result<(), Error> {
1114 let missing = |what: &str| protocol(format!("{:?} without {what}", self.message_type));
1115 match self.message_type {
1116 MessageType::MethodCall => {
1117 if self.path.is_none() {
1118 return Err(missing("a path"));
1119 }
1120 if self.member.is_none() {
1121 return Err(missing("a member"));
1122 }
1123 }
1124 MessageType::Signal => {
1125 if self.path.is_none() || self.interface.is_none() || self.member.is_none() {
1126 return Err(missing("a path, interface and member"));
1127 }
1128 }
1129 MessageType::Error => {
1130 if self.error_name.is_none() || self.reply_serial.is_none() {
1131 return Err(missing("an error name and reply serial"));
1132 }
1133 }
1134 MessageType::MethodReturn => {
1135 if self.reply_serial.is_none() {
1136 return Err(missing("a reply serial"));
1137 }
1138 }
1139 }
1140 if let Some(p) = &self.path
1141 && !is_valid_object_path(p)
1142 {
1143 return Err(protocol(format!("invalid object path {p:?}")));
1144 }
1145 if let Some(i) = &self.interface
1146 && !is_valid_interface(i)
1147 {
1148 return Err(protocol(format!("invalid interface name {i:?}")));
1149 }
1150 if let Some(e) = &self.error_name
1151 && !is_valid_interface(e)
1152 {
1153 return Err(protocol(format!("invalid error name {e:?}")));
1154 }
1155 if let Some(m) = &self.member
1156 && !is_valid_member(m)
1157 {
1158 return Err(protocol(format!("invalid member name {m:?}")));
1159 }
1160 if let Some(d) = &self.destination
1161 && !is_valid_bus_name(d)
1162 {
1163 return Err(protocol(format!("invalid bus name {d:?}")));
1164 }
1165 Ok(())
1166 }
1167
1168 pub fn decode(bytes: &[u8]) -> Result<Message, Error> {
1175 let big = match bytes.first() {
1176 Some(b'l') => false,
1177 Some(b'B') => true,
1178 _ => return Err(protocol("unknown byte order mark")),
1179 };
1180 let mut d = Decoder {
1181 data: bytes,
1182 pos: 0,
1183 big,
1184 };
1185 let head = d.take(4)?;
1186 let message_type = match head[1] {
1187 1 => MessageType::MethodCall,
1188 2 => MessageType::MethodReturn,
1189 3 => MessageType::Error,
1190 4 => MessageType::Signal,
1191 n => return Err(protocol(format!("unknown message type {n}"))),
1192 };
1193 if head[3] != 1 {
1194 return Err(protocol(format!(
1195 "unsupported protocol version {}",
1196 head[3]
1197 )));
1198 }
1199 let mut msg = Message::empty(message_type);
1200 msg.flags = head[2];
1201 let body_len = d.u32()? as usize;
1202 msg.serial = d.u32()?;
1203 let fields = d.value("a(yv)", 0)?;
1204 let mut signature = String::new();
1205 for field in fields.as_array().unwrap_or_default() {
1206 let Some([Value::Byte(code), Value::Variant(v)]) = field.as_struct() else {
1207 continue;
1208 };
1209 let text = || v.as_str().map(str::to_owned);
1210 match code {
1211 1 => msg.path = text(),
1212 2 => msg.interface = text(),
1213 3 => msg.member = text(),
1214 4 => msg.error_name = text(),
1215 5 => {
1216 if let Value::U32(n) = **v {
1217 msg.reply_serial = Some(n);
1218 }
1219 }
1220 6 => msg.destination = text(),
1221 7 => msg.sender = text(),
1222 8 => signature = text().unwrap_or_default(),
1223 9 => {
1224 if matches!(**v, Value::U32(n) if n > 0) {
1225 return Err(protocol("unix fds were not negotiated"));
1226 }
1227 }
1228 _ => {}
1229 }
1230 }
1231 d.align(8)?;
1232 if d.data.len() - d.pos != body_len {
1233 return Err(protocol("body length does not match the header"));
1234 }
1235 let mut rest = signature.as_str();
1236 while !rest.is_empty() {
1237 let (first, tail) = split_first_type(rest)?;
1238 msg.body.push(d.value(first, 0)?);
1239 rest = tail;
1240 }
1241 if d.pos != bytes.len() {
1242 return Err(protocol("body shorter than its length"));
1243 }
1244 Ok(msg)
1245 }
1246}
1247
1248fn read_frame(r: &mut dyn Read) -> io::Result<Vec<u8>> {
1250 let mut buf = vec![0u8; 16];
1251 r.read_exact(&mut buf)?;
1252 let word = |at: usize| {
1253 let b = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]];
1254 match buf[0] {
1255 b'l' => Ok(u32::from_le_bytes(b) as usize),
1256 b'B' => Ok(u32::from_be_bytes(b) as usize),
1257 _ => Err(io::Error::new(
1258 io::ErrorKind::InvalidData,
1259 "unknown byte order mark",
1260 )),
1261 }
1262 };
1263 let body_len = word(4)?;
1264 let fields_len = word(12)?;
1265 if fields_len > MAX_MESSAGE || body_len > MAX_MESSAGE {
1266 return Err(io::Error::new(
1267 io::ErrorKind::InvalidData,
1268 "message too long",
1269 ));
1270 }
1271 let total = (16 + fields_len).next_multiple_of(8) + body_len;
1272 if total > MAX_MESSAGE {
1273 return Err(io::Error::new(
1274 io::ErrorKind::InvalidData,
1275 "message too long",
1276 ));
1277 }
1278 buf.resize(total, 0);
1279 r.read_exact(&mut buf[16..])?;
1280 Ok(buf)
1281}
1282
1283fn read_line(s: &mut dyn Read) -> Result<String, Error> {
1288 let mut line = Vec::new();
1289 let mut byte = [0u8; 1];
1290 while !line.ends_with(b"\r\n") {
1291 if line.len() > 1024 {
1292 return Err(Error::Auth("overlong reply line".into()));
1293 }
1294 if s.read(&mut byte)? == 0 {
1295 return Err(Error::Disconnected);
1296 }
1297 line.push(byte[0]);
1298 }
1299 line.truncate(line.len() - 2);
1300 String::from_utf8(line).map_err(|_| Error::Auth("reply is not text".into()))
1301}
1302
1303#[cfg_attr(
1307 not(unix),
1308 allow(dead_code, reason = "only unix transports authenticate")
1309)]
1310fn authenticate<S: Read + Write>(s: &mut S, uid: Option<u32>) -> Result<(), Error> {
1311 use std::fmt::Write as _;
1312 s.write_all(b"\0")?;
1313 match uid {
1314 Some(uid) => {
1315 let hex = uid.to_string().bytes().fold(String::new(), |mut hex, b| {
1316 let _ = write!(hex, "{b:02x}");
1317 hex
1318 });
1319 s.write_all(format!("AUTH EXTERNAL {hex}\r\n").as_bytes())?;
1320 }
1321 None => s.write_all(b"AUTH EXTERNAL\r\n")?,
1322 }
1323 let mut reply = read_line(s)?;
1324 if reply == "DATA" || reply.starts_with("DATA ") {
1325 s.write_all(b"DATA\r\n")?;
1326 reply = read_line(s)?;
1327 }
1328 if !(reply == "OK" || reply.starts_with("OK ")) {
1329 let _ = s.write_all(b"CANCEL\r\n");
1330 return Err(Error::Auth(reply));
1331 }
1332 s.write_all(b"BEGIN\r\n")?;
1333 s.flush()?;
1334 Ok(())
1335}
1336
1337#[cfg_attr(
1339 not(unix),
1340 allow(dead_code, reason = "only unix transports authenticate")
1341)]
1342fn current_uid() -> Option<u32> {
1343 #[cfg(any(target_os = "linux", target_os = "android"))]
1344 {
1345 use std::os::unix::fs::MetadataExt;
1346 std::fs::metadata("/proc/self").ok().map(|m| m.uid())
1347 }
1348 #[cfg(not(any(target_os = "linux", target_os = "android")))]
1349 {
1350 None
1351 }
1352}
1353
1354#[derive(Clone, Debug)]
1360pub struct MethodCall {
1361 pub connection: Connection,
1363 pub path: String,
1365 pub interface: Option<String>,
1367 pub member: String,
1369 pub args: Vec<Value>,
1371 pub sender: Option<String>,
1373}
1374
1375#[derive(Clone, Debug, PartialEq, Eq)]
1377pub struct MethodError {
1378 pub name: String,
1380 pub message: String,
1382}
1383
1384impl MethodError {
1385 pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
1387 MethodError {
1388 name: name.into(),
1389 message: message.into(),
1390 }
1391 }
1392
1393 #[must_use]
1395 pub fn unknown_method(call: &MethodCall) -> Self {
1396 MethodError::new(
1397 "org.freedesktop.DBus.Error.UnknownMethod",
1398 format!(
1399 "no method {}.{} on {}",
1400 call.interface.as_deref().unwrap_or("*"),
1401 call.member,
1402 call.path
1403 ),
1404 )
1405 }
1406
1407 pub fn invalid_args(message: impl Into<String>) -> Self {
1409 MethodError::new("org.freedesktop.DBus.Error.InvalidArgs", message)
1410 }
1411
1412 #[must_use]
1414 pub fn unknown_property(name: &str) -> Self {
1415 MethodError::new(
1416 "org.freedesktop.DBus.Error.UnknownProperty",
1417 format!("no property {name}"),
1418 )
1419 }
1420
1421 pub fn failed(message: impl Into<String>) -> Self {
1423 MethodError::new("org.freedesktop.DBus.Error.Failed", message)
1424 }
1425
1426 fn is_unknown_method(&self) -> bool {
1427 self.name == "org.freedesktop.DBus.Error.UnknownMethod"
1428 }
1429}
1430
1431#[derive(Clone, Debug, Default, PartialEq, Eq)]
1435#[must_use]
1436pub struct SignalFilter {
1437 pub sender: Option<String>,
1440 pub path: Option<String>,
1442 pub interface: Option<String>,
1444 pub member: Option<String>,
1446}
1447
1448impl SignalFilter {
1449 pub fn new() -> Self {
1451 Self::default()
1452 }
1453
1454 pub fn sender(mut self, sender: &str) -> Self {
1456 self.sender = Some(sender.to_owned());
1457 self
1458 }
1459
1460 pub fn path(mut self, path: &str) -> Self {
1462 self.path = Some(path.to_owned());
1463 self
1464 }
1465
1466 pub fn interface(mut self, interface: &str) -> Self {
1468 self.interface = Some(interface.to_owned());
1469 self
1470 }
1471
1472 pub fn member(mut self, member: &str) -> Self {
1474 self.member = Some(member.to_owned());
1475 self
1476 }
1477
1478 fn matches(&self, m: &Message) -> bool {
1479 let field = |want: &Option<String>, have: &Option<String>| {
1480 want.as_ref().is_none_or(|w| have.as_ref() == Some(w))
1481 };
1482 field(&self.sender, &m.sender)
1483 && field(&self.path, &m.path)
1484 && field(&self.interface, &m.interface)
1485 && field(&self.member, &m.member)
1486 }
1487}
1488
1489#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1491pub struct SubscriptionId(u64);
1492
1493type HandlerFn = dyn Fn(&MethodCall) -> Result<Vec<Value>, MethodError> + Send + Sync;
1494type SignalFn = dyn Fn(&Connection, &Message) + Send + Sync;
1495
1496struct State {
1497 closed: bool,
1498 pending: HashMap<u32, mpsc::Sender<Message>>,
1499 objects: HashMap<String, Arc<HandlerFn>>,
1500 signals: Vec<(SubscriptionId, SignalFilter, Arc<SignalFn>)>,
1501 next_subscription: u64,
1502}
1503
1504struct Inner {
1505 writer: Mutex<Box<dyn Write + Send>>,
1506 close: Box<dyn Fn() + Send + Sync>,
1508 serial: AtomicU32,
1509 unique_name: String,
1510 state: Mutex<State>,
1511 reader: OnceLock<ThreadId>,
1512}
1513
1514impl Drop for Inner {
1515 fn drop(&mut self) {
1516 (self.close)();
1517 }
1518}
1519
1520fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
1521 m.lock().unwrap_or_else(PoisonError::into_inner)
1524}
1525
1526#[derive(Clone)]
1534pub struct Connection {
1535 inner: Arc<Inner>,
1536}
1537
1538impl fmt::Debug for Connection {
1539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1540 f.debug_struct("Connection")
1541 .field("unique_name", &self.inner.unique_name)
1542 .field("closed", &self.is_closed())
1543 .finish()
1544 }
1545}
1546
1547impl Connection {
1548 pub fn session() -> Result<Connection, Error> {
1556 if let Some(address) = std::env::var_os("DBUS_SESSION_BUS_ADDRESS")
1557 && !address.is_empty()
1558 {
1559 let address = address
1560 .into_string()
1561 .map_err(|_| Error::NoBus("DBUS_SESSION_BUS_ADDRESS is not UTF-8".into()))?;
1562 return Connection::connect(&address);
1563 }
1564 let runtime = std::env::var_os("XDG_RUNTIME_DIR")
1565 .filter(|d| !d.is_empty())
1566 .ok_or_else(|| {
1567 Error::NoBus("neither DBUS_SESSION_BUS_ADDRESS nor XDG_RUNTIME_DIR is set".into())
1568 })?;
1569 let path = std::path::Path::new(&runtime).join("bus");
1570 let path = path
1571 .to_str()
1572 .ok_or_else(|| Error::NoBus("XDG_RUNTIME_DIR is not UTF-8".into()))?;
1573 Connection::connect(&format!("unix:path={}", escape_address(path)))
1574 }
1575
1576 pub fn connect(address: &str) -> Result<Connection, Error> {
1585 #[cfg(unix)]
1586 {
1587 let stream = unix::connect_address(address)?;
1588 Connection::from_unix_stream(stream)
1589 }
1590 #[cfg(not(unix))]
1591 {
1592 let _ = address;
1593 Err(Error::Unsupported)
1594 }
1595 }
1596
1597 #[cfg(unix)]
1598 fn from_unix_stream(mut stream: std::os::unix::net::UnixStream) -> Result<Connection, Error> {
1599 use std::net::Shutdown;
1600 stream.set_read_timeout(Some(Duration::from_secs(10)))?;
1602 authenticate(&mut stream, current_uid())?;
1603 let reader = stream.try_clone()?;
1604 let closer = stream.try_clone()?;
1605 let mut hello_reader = stream.try_clone()?;
1606 let unique_name = hello(&mut stream, &mut hello_reader)?;
1607 stream.set_read_timeout(None)?;
1608 Connection::start(
1609 Box::new(reader),
1610 Box::new(stream),
1611 Box::new(move || {
1612 let _ = closer.shutdown(Shutdown::Both);
1613 }),
1614 unique_name,
1615 )
1616 }
1617
1618 #[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
1620 fn start(
1621 reader: Box<dyn Read + Send>,
1622 writer: Box<dyn Write + Send>,
1623 close: Box<dyn Fn() + Send + Sync>,
1624 unique_name: String,
1625 ) -> Result<Connection, Error> {
1626 let inner = Arc::new(Inner {
1627 writer: Mutex::new(writer),
1628 close,
1629 serial: AtomicU32::new(2),
1631 unique_name,
1632 state: Mutex::new(State {
1633 closed: false,
1634 pending: HashMap::new(),
1635 objects: HashMap::new(),
1636 signals: Vec::new(),
1637 next_subscription: 1,
1638 }),
1639 reader: OnceLock::new(),
1640 });
1641 let weak = Arc::downgrade(&inner);
1642 let handle = thread::Builder::new()
1643 .name("day-platform-linux".into())
1644 .spawn(move || reader_loop(reader, &weak))?;
1645 let _ = inner.reader.set(handle.thread().id());
1646 Ok(Connection { inner })
1647 }
1648
1649 #[must_use]
1651 pub fn unique_name(&self) -> &str {
1652 &self.inner.unique_name
1653 }
1654
1655 #[must_use]
1657 pub fn is_closed(&self) -> bool {
1658 lock(&self.inner.state).closed
1659 }
1660
1661 pub fn close(&self) {
1664 mark_closed(&self.inner);
1665 (self.inner.close)();
1666 }
1667
1668 fn next_serial(&self) -> u32 {
1669 loop {
1670 let s = self.inner.serial.fetch_add(1, Ordering::Relaxed);
1671 if s != 0 {
1672 return s;
1673 }
1674 }
1675 }
1676
1677 pub fn send(&self, mut msg: Message) -> Result<u32, Error> {
1684 if self.is_closed() {
1685 return Err(Error::Disconnected);
1686 }
1687 msg.serial = self.next_serial();
1688 let bytes = msg.encode()?;
1689 self.write(&bytes)?;
1690 Ok(msg.serial)
1691 }
1692
1693 fn write(&self, bytes: &[u8]) -> Result<(), Error> {
1694 let mut w = lock(&self.inner.writer);
1695 w.write_all(bytes)?;
1696 w.flush()?;
1697 Ok(())
1698 }
1699
1700 pub fn call(
1706 &self,
1707 destination: &str,
1708 path: &str,
1709 interface: &str,
1710 member: &str,
1711 args: &[Value],
1712 ) -> Result<Vec<Value>, Error> {
1713 self.call_with_timeout(destination, path, interface, member, args, DEFAULT_TIMEOUT)
1714 }
1715
1716 pub fn call_with_timeout(
1725 &self,
1726 destination: &str,
1727 path: &str,
1728 interface: &str,
1729 member: &str,
1730 args: &[Value],
1731 timeout: Duration,
1732 ) -> Result<Vec<Value>, Error> {
1733 if self.inner.reader.get() == Some(&thread::current().id()) {
1734 return Err(Error::ReaderThread);
1735 }
1736 let mut msg = Message::method_call(destination, path, interface, member, args.to_vec());
1737 msg.serial = self.next_serial();
1738 let bytes = msg.encode()?;
1739 let (tx, rx) = mpsc::channel();
1740 {
1741 let mut state = lock(&self.inner.state);
1742 if state.closed {
1743 return Err(Error::Disconnected);
1744 }
1745 state.pending.insert(msg.serial, tx);
1746 }
1747 if let Err(e) = self.write(&bytes) {
1748 lock(&self.inner.state).pending.remove(&msg.serial);
1749 return Err(e);
1750 }
1751 match rx.recv_timeout(timeout) {
1752 Ok(reply) if reply.message_type == MessageType::Error => Err(Error::Remote {
1753 name: reply.error_name.unwrap_or_default(),
1754 message: reply
1755 .body
1756 .first()
1757 .and_then(Value::as_str)
1758 .unwrap_or_default()
1759 .to_owned(),
1760 }),
1761 Ok(reply) => Ok(reply.body),
1762 Err(mpsc::RecvTimeoutError::Timeout) => {
1763 lock(&self.inner.state).pending.remove(&msg.serial);
1764 Err(Error::Timeout)
1765 }
1766 Err(mpsc::RecvTimeoutError::Disconnected) => Err(Error::Disconnected),
1767 }
1768 }
1769
1770 pub fn call_no_reply(
1776 &self,
1777 destination: &str,
1778 path: &str,
1779 interface: &str,
1780 member: &str,
1781 args: &[Value],
1782 ) -> Result<(), Error> {
1783 let mut msg = Message::method_call(destination, path, interface, member, args.to_vec());
1784 msg.flags |= FLAG_NO_REPLY_EXPECTED;
1785 self.send(msg).map(|_| ())
1786 }
1787
1788 pub fn emit_signal(
1794 &self,
1795 path: &str,
1796 interface: &str,
1797 member: &str,
1798 args: &[Value],
1799 ) -> Result<(), Error> {
1800 self.send(Message::signal(path, interface, member, args.to_vec()))
1801 .map(|_| ())
1802 }
1803
1804 fn bus_call(&self, member: &str, args: &[Value]) -> Result<Vec<Value>, Error> {
1805 self.call(BUS_NAME, BUS_PATH, BUS_INTERFACE, member, args)
1806 }
1807
1808 pub fn request_name(&self, name: &str, flags: u32) -> Result<u32, Error> {
1815 let reply = self.bus_call("RequestName", &[Value::str(name), Value::U32(flags)])?;
1816 match reply.first() {
1817 Some(Value::U32(code)) => Ok(*code),
1818 _ => Err(protocol("RequestName returned no code")),
1819 }
1820 }
1821
1822 pub fn release_name(&self, name: &str) -> Result<(), Error> {
1828 self.call_no_reply(
1829 BUS_NAME,
1830 BUS_PATH,
1831 BUS_INTERFACE,
1832 "ReleaseName",
1833 &[Value::str(name)],
1834 )
1835 }
1836
1837 #[must_use]
1839 pub fn name_has_owner(&self, name: &str) -> bool {
1840 matches!(
1841 self.bus_call("NameHasOwner", &[Value::str(name)])
1842 .as_deref(),
1843 Ok([Value::Bool(true)])
1844 )
1845 }
1846
1847 pub fn add_match(&self, rule: &str) -> Result<(), Error> {
1854 self.bus_call("AddMatch", &[Value::str(rule)]).map(|_| ())
1855 }
1856
1857 pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
1863 self.call_no_reply(
1864 BUS_NAME,
1865 BUS_PATH,
1866 BUS_INTERFACE,
1867 "RemoveMatch",
1868 &[Value::str(rule)],
1869 )
1870 }
1871
1872 pub fn on_signal<F>(&self, filter: SignalFilter, callback: F) -> SubscriptionId
1874 where
1875 F: Fn(&Connection, &Message) + Send + Sync + 'static,
1876 {
1877 let mut state = lock(&self.inner.state);
1878 let id = SubscriptionId(state.next_subscription);
1879 state.next_subscription += 1;
1880 state.signals.push((id, filter, Arc::new(callback)));
1881 id
1882 }
1883
1884 pub fn remove_signal_handler(&self, id: SubscriptionId) {
1886 lock(&self.inner.state).signals.retain(|(s, ..)| *s != id);
1887 }
1888
1889 pub fn export<F>(&self, path: &str, handler: F) -> Result<(), Error>
1901 where
1902 F: Fn(&MethodCall) -> Result<Vec<Value>, MethodError> + Send + Sync + 'static,
1903 {
1904 if !is_valid_object_path(path) {
1905 return Err(protocol(format!("invalid object path {path:?}")));
1906 }
1907 let mut state = lock(&self.inner.state);
1908 if state.objects.contains_key(path) {
1909 return Err(protocol(format!("{path} is already exported")));
1910 }
1911 state.objects.insert(path.to_owned(), Arc::new(handler));
1912 Ok(())
1913 }
1914
1915 pub fn unexport(&self, path: &str) {
1917 lock(&self.inner.state).objects.remove(path);
1918 }
1919}
1920
1921#[cfg(unix)]
1922mod unix {
1923 use super::Error;
1924 use std::io;
1925 use std::os::unix::net::UnixStream;
1926
1927 fn unescape(value: &str) -> Vec<u8> {
1929 let bytes = value.as_bytes();
1930 let mut out = Vec::with_capacity(bytes.len());
1931 let mut i = 0;
1932 while i < bytes.len() {
1933 let hex = bytes
1934 .get(i + 1..i + 3)
1935 .and_then(|h| std::str::from_utf8(h).ok())
1936 .and_then(|h| u8::from_str_radix(h, 16).ok());
1937 match (bytes[i], hex) {
1938 (b'%', Some(b)) => {
1939 out.push(b);
1940 i += 3;
1941 }
1942 (b, _) => {
1943 out.push(b);
1944 i += 1;
1945 }
1946 }
1947 }
1948 out
1949 }
1950
1951 pub(super) fn connect_address(address: &str) -> Result<UnixStream, Error> {
1952 use std::ffi::OsStr;
1953 use std::os::unix::ffi::OsStrExt;
1954
1955 let mut last = Error::NoBus(format!("no unix transport in {address:?}"));
1956 for entry in address.split(';').filter(|e| !e.is_empty()) {
1957 let Some(("unix", params)) = entry.split_once(':') else {
1958 continue;
1959 };
1960 let param = |key: &str| {
1961 params.split(',').find_map(|kv| {
1962 kv.split_once('=')
1963 .filter(|(k, _)| *k == key)
1964 .map(|(_, v)| unescape(v))
1965 })
1966 };
1967 let result = if let Some(path) = param("path") {
1968 UnixStream::connect(OsStr::from_bytes(&path))
1969 } else if let Some(name) = param("abstract") {
1970 connect_abstract(&name)
1971 } else {
1972 continue;
1973 };
1974 match result {
1975 Ok(stream) => return Ok(stream),
1976 Err(e) => last = Error::Io(e),
1977 }
1978 }
1979 Err(last)
1980 }
1981
1982 #[cfg(any(target_os = "linux", target_os = "android"))]
1983 fn connect_abstract(name: &[u8]) -> io::Result<UnixStream> {
1984 #[cfg(target_os = "android")]
1985 use std::os::android::net::SocketAddrExt;
1986 #[cfg(target_os = "linux")]
1987 use std::os::linux::net::SocketAddrExt;
1988 let addr = std::os::unix::net::SocketAddr::from_abstract_name(name)?;
1989 UnixStream::connect_addr(&addr)
1990 }
1991
1992 #[cfg(not(any(target_os = "linux", target_os = "android")))]
1993 fn connect_abstract(_name: &[u8]) -> io::Result<UnixStream> {
1994 Err(io::Error::new(
1995 io::ErrorKind::Unsupported,
1996 "abstract unix sockets exist only on Linux",
1997 ))
1998 }
1999}
2000
2001fn escape_address(value: &str) -> String {
2003 value
2004 .bytes()
2005 .map(|b| {
2006 if b.is_ascii_alphanumeric() || b"-_/.\\*".contains(&b) {
2007 char::from(b).to_string()
2008 } else {
2009 format!("%{b:02x}")
2010 }
2011 })
2012 .collect()
2013}
2014
2015#[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
2017fn hello(w: &mut dyn Write, r: &mut dyn Read) -> Result<String, Error> {
2018 let mut msg = Message::method_call(BUS_NAME, BUS_PATH, BUS_INTERFACE, "Hello", Vec::new());
2019 msg.serial = 1;
2020 w.write_all(&msg.encode()?)?;
2021 w.flush()?;
2022 loop {
2023 let reply = Message::decode(&read_frame(r)?)?;
2024 if reply.reply_serial != Some(1) {
2025 continue;
2026 }
2027 if reply.message_type == MessageType::Error {
2028 return Err(Error::Remote {
2029 name: reply.error_name.unwrap_or_default(),
2030 message: String::new(),
2031 });
2032 }
2033 return match reply.body.first() {
2034 Some(Value::Str(name)) => Ok(name.clone()),
2035 _ => Err(protocol("Hello returned no name")),
2036 };
2037 }
2038}
2039
2040fn mark_closed(inner: &Inner) {
2041 let mut state = lock(&inner.state);
2042 state.closed = true;
2043 state.pending.clear();
2045}
2046
2047#[cfg_attr(not(unix), allow(dead_code, reason = "only unix transports connect"))]
2048fn reader_loop(mut reader: Box<dyn Read + Send>, weak: &Weak<Inner>) {
2049 loop {
2050 let frame = read_frame(&mut *reader);
2051 let Some(inner) = weak.upgrade() else {
2052 return;
2053 };
2054 let Ok(bytes) = frame else {
2055 mark_closed(&inner);
2056 return;
2057 };
2058 let conn = Connection { inner };
2059 if let Ok(msg) = Message::decode(&bytes) {
2062 dispatch(&conn, msg);
2063 }
2064 }
2065}
2066
2067fn dispatch(conn: &Connection, msg: Message) {
2068 match msg.message_type {
2069 MessageType::MethodReturn | MessageType::Error => {
2070 let Some(serial) = msg.reply_serial else {
2071 return;
2072 };
2073 let waiter = lock(&conn.inner.state).pending.remove(&serial);
2074 if let Some(tx) = waiter {
2075 let _ = tx.send(msg);
2076 }
2077 }
2078 MessageType::Signal => {
2079 let callbacks: Vec<Arc<SignalFn>> = lock(&conn.inner.state)
2080 .signals
2081 .iter()
2082 .filter(|(_, filter, _)| filter.matches(&msg))
2083 .map(|(_, _, cb)| cb.clone())
2084 .collect();
2085 for cb in callbacks {
2086 cb(conn, &msg);
2087 }
2088 }
2089 MessageType::MethodCall => {
2090 let reply = answer(conn, &msg);
2091 if msg.flags & FLAG_NO_REPLY_EXPECTED != 0 {
2092 return;
2093 }
2094 let out = match reply {
2095 Ok(body) => Message::reply_to(&msg, body),
2096 Err(e) => Message::error_to(&msg, &e.name, &e.message),
2097 };
2098 let out = match out.encode() {
2099 Ok(_) => out,
2100 Err(e) => Message::error_to(
2103 &msg,
2104 "org.freedesktop.DBus.Error.Failed",
2105 &format!("reply could not be sent: {e}"),
2106 ),
2107 };
2108 let _ = conn.send(out);
2109 }
2110 }
2111}
2112
2113fn answer(conn: &Connection, msg: &Message) -> Result<Vec<Value>, MethodError> {
2114 let path = msg.path.clone().unwrap_or_default();
2115 let member = msg.member.clone().unwrap_or_default();
2116 let interface = msg.interface.as_deref();
2117 if interface == Some(PEER_INTERFACE) {
2118 return match member.as_str() {
2119 "Ping" => Ok(Vec::new()),
2120 "GetMachineId" => machine_id()
2121 .map(|id| vec![Value::Str(id)])
2122 .ok_or_else(|| MethodError::failed("no machine id")),
2123 _ => Err(MethodError::new(
2124 "org.freedesktop.DBus.Error.UnknownMethod",
2125 format!("no method {PEER_INTERFACE}.{member}"),
2126 )),
2127 };
2128 }
2129 let introspect =
2130 member == "Introspect" && interface.is_none_or(|i| i == INTROSPECTABLE_INTERFACE);
2131 let handler = lock(&conn.inner.state).objects.get(&path).cloned();
2132 let call = MethodCall {
2133 connection: conn.clone(),
2134 path: path.clone(),
2135 interface: msg.interface.clone(),
2136 member,
2137 args: msg.body.clone(),
2138 sender: msg.sender.clone(),
2139 };
2140 if let Some(handler) = handler {
2141 match handler(&call) {
2142 Err(e) if introspect && e.is_unknown_method() => Ok(vec![Value::Str(
2143 introspection_xml("", &children(conn, &path)),
2144 )]),
2145 other => other,
2146 }
2147 } else {
2148 let kids = children(conn, &path);
2149 if introspect && !kids.is_empty() {
2150 Ok(vec![Value::Str(introspection_xml("", &kids))])
2151 } else {
2152 Err(MethodError::new(
2153 "org.freedesktop.DBus.Error.UnknownObject",
2154 format!("no object at {path}"),
2155 ))
2156 }
2157 }
2158}
2159
2160fn children(conn: &Connection, path: &str) -> Vec<String> {
2162 let prefix = if path == "/" {
2163 "/".to_owned()
2164 } else {
2165 format!("{path}/")
2166 };
2167 let names: BTreeSet<String> = lock(&conn.inner.state)
2168 .objects
2169 .keys()
2170 .filter_map(|p| p.strip_prefix(&prefix))
2171 .filter_map(|rest| rest.split('/').next())
2172 .filter(|seg| !seg.is_empty())
2173 .map(str::to_owned)
2174 .collect();
2175 names.into_iter().collect()
2176}
2177
2178fn machine_id() -> Option<String> {
2179 ["/etc/machine-id", "/var/lib/dbus/machine-id"]
2180 .iter()
2181 .find_map(|p| std::fs::read_to_string(p).ok())
2182 .map(|s| s.trim().to_owned())
2183 .filter(|s| !s.is_empty())
2184}
2185
2186#[must_use]
2189pub fn introspection_xml(interfaces: &str, children: &[String]) -> String {
2190 use std::fmt::Write as _;
2191 let mut xml = String::from(
2192 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n \
2193 \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n<node>\n \
2194 <interface name=\"org.freedesktop.DBus.Peer\">\n <method name=\"Ping\"/>\n \
2195 <method name=\"GetMachineId\"><arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/></method>\n \
2196 </interface>\n <interface name=\"org.freedesktop.DBus.Introspectable\">\n \
2197 <method name=\"Introspect\"><arg type=\"s\" name=\"xml_data\" direction=\"out\"/></method>\n \
2198 </interface>\n",
2199 );
2200 xml.push_str(interfaces);
2201 for child in children {
2202 let _ = writeln!(xml, " <node name=\"{child}\"/>");
2203 }
2204 xml.push_str("</node>\n");
2205 xml
2206}
2207
2208pub mod launcher {
2216 use super::{Connection, Error, Value};
2217
2218 pub const INTERFACE: &str = "com.canonical.Unity.LauncherEntry";
2220
2221 #[derive(Clone, Copy, Debug, Default, PartialEq)]
2224 pub struct LauncherProps {
2225 pub count: Option<i64>,
2227 pub progress: Option<f64>,
2229 pub urgent: Option<bool>,
2231 }
2232
2233 #[must_use]
2235 pub fn object_path(desktop_id: &str) -> String {
2236 let hash = desktop_id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
2238 (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
2239 });
2240 format!("/com/canonical/unity/launcherentry/{hash}")
2241 }
2242
2243 pub fn update(conn: &Connection, desktop_id: &str, props: LauncherProps) -> Result<(), Error> {
2250 let id = desktop_id.strip_suffix(".desktop").unwrap_or(desktop_id);
2251 let uri = format!("application://{id}.desktop");
2252 let entries = vec![
2253 ("count", Value::I64(props.count.unwrap_or(0))),
2254 ("count-visible", Value::Bool(props.count.is_some())),
2255 (
2256 "progress",
2257 Value::Double(props.progress.unwrap_or(0.0).clamp(0.0, 1.0)),
2258 ),
2259 ("progress-visible", Value::Bool(props.progress.is_some())),
2260 ("urgent", Value::Bool(props.urgent.unwrap_or(false))),
2261 ];
2262 conn.emit_signal(
2263 &object_path(id),
2264 INTERFACE,
2265 "Update",
2266 &[Value::Str(uri), Value::props(entries)],
2267 )
2268 }
2269}
2270
2271pub mod instance {
2285 use super::{
2286 Connection, Error, INTROSPECTABLE_INTERFACE, MethodError, NAME_FLAG_DO_NOT_QUEUE,
2287 NAME_REPLY_ALREADY_OWNER, NAME_REPLY_EXISTS, NAME_REPLY_PRIMARY_OWNER, Value,
2288 introspection_xml,
2289 };
2290 use std::fmt;
2291
2292 pub const PATH: &str = "/dev/daybrite/Instance";
2294 pub const INTERFACE: &str = "dev.daybrite.Instance";
2296
2297 const XML: &str = " <interface name=\"dev.daybrite.Instance\">\n \
2298 <method name=\"Forward\"><arg type=\"as\" name=\"args\" direction=\"in\"/></method>\n \
2299 </interface>\n";
2300
2301 #[derive(Debug)]
2303 pub enum Claimed {
2304 Forwarded,
2307 NoBus(Error),
2310 }
2311
2312 impl fmt::Display for Claimed {
2313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2314 match self {
2315 Claimed::Forwarded => f.write_str("forwarded to the running instance"),
2316 Claimed::NoBus(e) => write!(f, "single-instance claim unavailable: {e}"),
2317 }
2318 }
2319 }
2320
2321 impl std::error::Error for Claimed {
2322 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2323 match self {
2324 Claimed::Forwarded => None,
2325 Claimed::NoBus(e) => Some(e),
2326 }
2327 }
2328 }
2329
2330 #[derive(Debug)]
2333 pub struct Claim {
2334 conn: Connection,
2335 name: String,
2336 }
2337
2338 impl Claim {
2339 #[must_use]
2341 pub fn name(&self) -> &str {
2342 &self.name
2343 }
2344
2345 #[must_use]
2347 pub fn connection(&self) -> &Connection {
2348 &self.conn
2349 }
2350 }
2351
2352 impl Drop for Claim {
2353 fn drop(&mut self) {
2354 self.conn.unexport(PATH);
2355 let _ = self.conn.release_name(&self.name);
2356 }
2357 }
2358
2359 #[must_use]
2364 pub fn bus_name(app_id: &str) -> String {
2365 let elements: Vec<String> = app_id
2366 .split('.')
2367 .map(|el| {
2368 let mut out: String = el
2369 .chars()
2370 .map(|c| {
2371 if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
2372 c
2373 } else {
2374 '_'
2375 }
2376 })
2377 .collect();
2378 if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
2379 out.insert(0, '_');
2380 }
2381 out
2382 })
2383 .collect();
2384 let name = if elements.len() < 2 {
2385 format!("dev.daybrite.instance.{}", elements.join("."))
2386 } else {
2387 elements.join(".")
2388 };
2389 if name.len() <= 255 {
2390 return name;
2391 }
2392 let hash = app_id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
2393 (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
2394 });
2395 format!("dev.daybrite.instance.h{hash:016x}")
2396 }
2397
2398 fn owner_vanished(e: &Error) -> bool {
2400 match e {
2401 Error::Remote { name, .. } => matches!(
2402 name.as_str(),
2403 "org.freedesktop.DBus.Error.ServiceUnknown"
2404 | "org.freedesktop.DBus.Error.NameHasNoOwner"
2405 | "org.freedesktop.DBus.Error.NoReply"
2406 ),
2407 _ => false,
2408 }
2409 }
2410
2411 #[expect(
2424 clippy::needless_pass_by_value,
2425 reason = "public signature; callers pass the argument list they collected for this launch"
2426 )]
2427 pub fn claim<F>(app_id: &str, args: Vec<String>, on_forward: F) -> Result<Claim, Claimed>
2428 where
2429 F: Fn(Vec<String>) + Send + Sync + 'static,
2430 {
2431 let conn = Connection::session().map_err(Claimed::NoBus)?;
2432 let name = bus_name(app_id);
2433 conn.export(PATH, move |call| {
2436 match (call.interface.as_deref(), call.member.as_str()) {
2437 (Some(INTERFACE) | None, "Forward") => {
2438 let [Value::Array { elem, items }] = call.args.as_slice() else {
2439 return Err(MethodError::invalid_args("expected (as)"));
2440 };
2441 if elem != "s" {
2442 return Err(MethodError::invalid_args("expected (as)"));
2443 }
2444 on_forward(
2445 items
2446 .iter()
2447 .filter_map(|v| v.as_str().map(str::to_owned))
2448 .collect(),
2449 );
2450 Ok(Vec::new())
2451 }
2452 (Some(INTROSPECTABLE_INTERFACE) | None, "Introspect") => {
2453 Ok(vec![Value::Str(introspection_xml(XML, &[]))])
2454 }
2455 _ => Err(MethodError::unknown_method(call)),
2456 }
2457 })
2458 .map_err(Claimed::NoBus)?;
2459 let forwarded = Value::strings(&args);
2460 let mut last = Error::Disconnected;
2461 for _ in 0..2 {
2463 match conn.request_name(&name, NAME_FLAG_DO_NOT_QUEUE) {
2464 Ok(NAME_REPLY_PRIMARY_OWNER | NAME_REPLY_ALREADY_OWNER) => {
2465 return Ok(Claim { conn, name });
2466 }
2467 Ok(NAME_REPLY_EXISTS) => {}
2468 Ok(code) => {
2469 last = Error::Protocol(format!("RequestName answered {code}"));
2470 break;
2471 }
2472 Err(e) => {
2473 last = e;
2474 break;
2475 }
2476 }
2477 match conn.call(
2478 &name,
2479 PATH,
2480 INTERFACE,
2481 "Forward",
2482 std::slice::from_ref(&forwarded),
2483 ) {
2484 Ok(_) => {
2485 conn.unexport(PATH);
2486 return Err(Claimed::Forwarded);
2487 }
2488 Err(e) if owner_vanished(&e) => last = e,
2489 Err(e) => {
2490 last = e;
2491 break;
2492 }
2493 }
2494 }
2495 conn.unexport(PATH);
2496 Err(Claimed::NoBus(last))
2497 }
2498}
2499
2500#[cfg(test)]
2505mod tests {
2506 use super::*;
2507
2508 fn round_trip(values: &[Value]) {
2509 let sig: String = values.iter().map(Value::signature).collect();
2510 let bytes = marshal(values).expect("marshal");
2511 assert_eq!(unmarshal(&bytes, &sig, false).expect("unmarshal"), values);
2512 let mut e = Encoder::new(true);
2513 for v in values {
2514 e.value(v, 0).expect("marshal big-endian");
2515 }
2516 assert_eq!(unmarshal(&e.buf, &sig, true).expect("unmarshal BE"), values);
2517 }
2518
2519 #[test]
2520 fn every_basic_type_round_trips() {
2521 round_trip(&[
2522 Value::Byte(0xab),
2523 Value::Bool(true),
2524 Value::Bool(false),
2525 Value::I16(-2),
2526 Value::U16(65535),
2527 Value::I32(-70000),
2528 Value::U32(0xdead_beef),
2529 Value::I64(i64::MIN),
2530 Value::U64(u64::MAX),
2531 Value::Double(-1.5),
2532 Value::str("héllo"),
2533 Value::str(""),
2534 Value::path("/org/example/Obj_1"),
2535 Value::Signature("a{sv}(iiay)".into()),
2536 ]);
2537 }
2538
2539 #[test]
2540 fn containers_round_trip() {
2541 round_trip(&[
2542 Value::Struct(vec![
2543 Value::I32(1),
2544 Value::str("x"),
2545 Value::bytes(&[1, 2, 3]),
2546 ]),
2547 Value::props([("a", Value::U32(7)), ("b", Value::strings(&["p", "q"]))]),
2548 Value::dict("i", "s", [(Value::I32(3), Value::str("three"))]),
2549 Value::array(
2550 "(iiay)",
2551 vec![Value::Struct(vec![
2552 Value::I32(2),
2553 Value::I32(2),
2554 Value::bytes(&[0; 16]),
2555 ])],
2556 ),
2557 ]);
2558 }
2559
2560 #[test]
2561 fn struct_after_a_byte_is_padded_to_eight() {
2562 let values = vec![Value::Byte(1), Value::Struct(vec![Value::Byte(2)])];
2563 let bytes = marshal(&values).expect("marshal");
2564 assert_eq!(bytes, [1, 0, 0, 0, 0, 0, 0, 0, 2]);
2565 round_trip(&values);
2566 }
2567
2568 #[test]
2569 fn empty_arrays_still_pad_to_their_element_alignment() {
2570 let values = vec![Value::Byte(9), Value::array("(ii)", Vec::new())];
2572 let bytes = marshal(&values).expect("marshal");
2573 assert_eq!(bytes, [9, 0, 0, 0, 0, 0, 0, 0]);
2574 round_trip(&values);
2575 let values = vec![Value::U32(1), Value::props(Vec::<(&str, Value)>::new())];
2577 assert_eq!(marshal(&values).expect("marshal").len(), 8);
2578 round_trip(&values);
2579 let values = vec![Value::Byte(1), Value::bytes(&[]), Value::Byte(2)];
2581 assert_eq!(
2582 marshal(&values).expect("marshal"),
2583 [1, 0, 0, 0, 0, 0, 0, 0, 2]
2584 );
2585 round_trip(&values);
2586 }
2587
2588 #[test]
2589 fn array_length_excludes_the_leading_padding() {
2590 let bytes = marshal(&[Value::array(
2592 "(i)",
2593 vec![Value::Struct(vec![Value::I32(5)])],
2594 )])
2595 .expect("marshal");
2596 assert_eq!(bytes, [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0]);
2597 }
2598
2599 #[test]
2600 fn nested_variants_round_trip() {
2601 let deep = Value::variant(Value::variant(Value::variant(Value::Struct(vec![
2602 Value::Byte(1),
2603 Value::variant(Value::array("v", vec![Value::variant(Value::I64(-1))])),
2604 ]))));
2605 assert_eq!(deep.signature(), "v");
2606 round_trip(&[Value::Byte(7), deep]);
2607 }
2608
2609 #[test]
2610 fn mismatched_array_items_are_rejected() {
2611 let bad = Value::array("s", vec![Value::I32(1)]);
2612 assert!(marshal(&[bad]).is_err());
2613 assert!(marshal(&[Value::path("no/slash")]).is_err());
2614 assert!(marshal(&[Value::Struct(Vec::new())]).is_err());
2615 }
2616
2617 #[test]
2618 fn malformed_input_is_an_error_not_a_panic() {
2619 assert!(unmarshal(&[1, 0, 0, 0], "b", false).is_ok());
2620 assert!(unmarshal(&[2, 0, 0, 0], "b", false).is_err());
2621 assert!(unmarshal(&[0xff, 0xff, 0xff, 0x0f], "ay", false).is_err());
2622 assert!(unmarshal(&[3, 0, 0, 0, b'a', b'b'], "s", false).is_err());
2623 assert!(unmarshal(&[], "a{vs}", false).is_err());
2624 assert!(Message::decode(b"x").is_err());
2625 for len in 0..40 {
2626 let _ = Message::decode(&vec![b'l'; len]);
2627 }
2628 }
2629
2630 #[test]
2631 fn signatures_parse() {
2632 assert_eq!(split_first_type("a{sv}i").expect("split"), ("a{sv}", "i"));
2633 assert_eq!(
2634 split_first_type("(ia(s))x").expect("split"),
2635 ("(ia(s))", "x")
2636 );
2637 for bad in ["(", "()", "a", "a{vs}", "a{s}", "a{sss}", "z", "(i"] {
2638 assert!(validate_signature(bad).is_err(), "{bad}");
2639 }
2640 }
2641
2642 #[test]
2646 fn hello_matches_the_spec_bytes() {
2647 let mut hello =
2648 Message::method_call(BUS_NAME, BUS_PATH, BUS_INTERFACE, "Hello", Vec::new());
2649 hello.serial = 1;
2650 let mut want: Vec<u8> = Vec::new();
2651 want.extend_from_slice(&[b'l', 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0x6d, 0, 0, 0]);
2653 want.extend_from_slice(&[1, 1, b'o', 0, 21, 0, 0, 0]);
2655 want.extend_from_slice(b"/org/freedesktop/DBus\0");
2656 want.extend_from_slice(&[0, 0]); want.extend_from_slice(&[2, 1, b's', 0, 20, 0, 0, 0]);
2659 want.extend_from_slice(b"org.freedesktop.DBus\0");
2660 want.extend_from_slice(&[0, 0, 0]); want.extend_from_slice(&[3, 1, b's', 0, 5, 0, 0, 0]);
2663 want.extend_from_slice(b"Hello\0");
2664 want.extend_from_slice(&[0, 0]); want.extend_from_slice(&[6, 1, b's', 0, 20, 0, 0, 0]);
2667 want.extend_from_slice(b"org.freedesktop.DBus\0");
2668 want.extend_from_slice(&[0, 0, 0]); assert_eq!(want.len(), 128);
2670 assert_eq!(hello.encode().expect("encode"), want);
2671 assert_eq!(Message::decode(&want).expect("decode"), hello);
2672 }
2673
2674 #[test]
2675 fn big_endian_header_parses() {
2676 let mut m: Vec<u8> = vec![b'B', 4, 0, 1, 0, 0, 0, 4, 0, 0, 0, 7];
2679 let mut fields: Vec<u8> = Vec::new();
2680 fields.extend_from_slice(&[1, 1, b'o', 0, 0, 0, 0, 2, b'/', b'a', 0]);
2682 fields.extend_from_slice(&[0, 0, 0, 0, 0]); fields.extend_from_slice(&[2, 1, b's', 0, 0, 0, 0, 3, b'x', b'.', b'y', 0]);
2685 fields.extend_from_slice(&[0, 0, 0, 0]); fields.extend_from_slice(&[3, 1, b's', 0, 0, 0, 0, 1, b'Z', 0]);
2688 fields.extend_from_slice(&[0, 0, 0, 0, 0, 0]); fields.extend_from_slice(&[7, 1, b's', 0, 0, 0, 0, 4, b':', b'1', b'.', b'5', 0]);
2691 fields.extend_from_slice(&[0, 0, 0]); fields.extend_from_slice(&[8, 1, b'g', 0, 1, b'u', 0]); let fields_len = fields.len() as u32;
2694 m.extend_from_slice(&fields_len.to_be_bytes());
2695 m.extend_from_slice(&fields);
2696 m.resize(88, 0); m.extend_from_slice(&[1, 2, 3, 4]); let msg = Message::decode(&m).expect("decode big-endian");
2699 assert_eq!(msg.message_type, MessageType::Signal);
2700 assert_eq!(msg.serial, 7);
2701 assert_eq!(msg.path.as_deref(), Some("/a"));
2702 assert_eq!(msg.interface.as_deref(), Some("x.y"));
2703 assert_eq!(msg.member.as_deref(), Some("Z"));
2704 assert_eq!(msg.sender.as_deref(), Some(":1.5"));
2705 assert_eq!(msg.body, vec![Value::U32(0x0102_0304)]);
2706 let framed = read_frame(&mut &m[..]).expect("frame");
2708 assert_eq!(framed.len(), m.len());
2709 let mut ours = Message::signal("/a", "x.y", "Z", vec![Value::U32(0x0102_0304)]);
2711 ours.serial = 7;
2712 ours.sender = Some(":1.5".into());
2713 let decoded = Message::decode(&ours.encode_with(true).expect("encode BE")).expect("BE");
2714 assert_eq!(decoded, msg);
2715 }
2716
2717 #[test]
2718 fn auth_sends_uid_as_hex_ascii() {
2719 struct Script {
2720 replies: io::Cursor<Vec<u8>>,
2721 sent: Vec<u8>,
2722 }
2723 impl Read for Script {
2724 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2725 self.replies.read(buf)
2726 }
2727 }
2728 impl Write for Script {
2729 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2730 self.sent.extend_from_slice(buf);
2731 Ok(buf.len())
2732 }
2733 fn flush(&mut self) -> io::Result<()> {
2734 Ok(())
2735 }
2736 }
2737 let mut s = Script {
2738 replies: io::Cursor::new(b"OK 1234deadbeef\r\n".to_vec()),
2739 sent: Vec::new(),
2740 };
2741 authenticate(&mut s, Some(1000)).expect("auth");
2742 assert_eq!(s.sent, b"\0AUTH EXTERNAL 31303030\r\nBEGIN\r\n");
2743
2744 let mut s = Script {
2745 replies: io::Cursor::new(b"DATA\r\nOK 1234\r\n".to_vec()),
2746 sent: Vec::new(),
2747 };
2748 authenticate(&mut s, None).expect("auth without uid");
2749 assert_eq!(s.sent, b"\0AUTH EXTERNAL\r\nDATA\r\nBEGIN\r\n");
2750
2751 let mut s = Script {
2752 replies: io::Cursor::new(b"REJECTED EXTERNAL\r\n".to_vec()),
2753 sent: Vec::new(),
2754 };
2755 std::assert_matches!(authenticate(&mut s, Some(0)), Err(Error::Auth(_)));
2756 }
2757
2758 #[test]
2759 fn instance_bus_names_are_legal() {
2760 use instance::bus_name;
2761 for (id, want) in [
2762 ("dev.daybrite.Notes", "dev.daybrite.Notes"),
2763 ("com.example.my-app", "com.example.my-app"),
2764 ("org.7zip.App", "org._7zip.App"),
2765 ("io.github.user.2048", "io.github.user._2048"),
2766 ("notes", "dev.daybrite.instance.notes"),
2767 ("a..b", "a._.b"),
2768 ("dev.sun rise/x.é", "dev.sun_rise_x._"),
2769 ("", "dev.daybrite.instance._"),
2770 ] {
2771 let name = bus_name(id);
2772 assert_eq!(name, want, "{id:?}");
2773 assert!(is_valid_bus_name(&name), "{name}");
2774 }
2775 let long = format!("dev.daybrite.{}", "x".repeat(300));
2776 let name = bus_name(&long);
2777 assert!(name.len() <= 255 && is_valid_bus_name(&name), "{name}");
2778 assert_eq!(name, bus_name(&long));
2779 }
2780
2781 #[test]
2782 fn launcher_path_is_valid() {
2783 assert!(is_valid_object_path(&launcher::object_path(
2784 "dev.daybrite.Some-App"
2785 )));
2786 }
2787
2788 #[cfg(unix)]
2791 #[test]
2792 fn connection_calls_and_disconnects() {
2793 use std::os::unix::net::UnixStream;
2794 let (client, mut bus) = UnixStream::pair().expect("pair");
2795 let peer = thread::spawn(move || {
2796 let mut nul = [0u8];
2798 bus.read_exact(&mut nul).expect("read NUL");
2799 loop {
2800 let line = read_line(&mut bus).expect("read auth line");
2801 match line.as_str() {
2802 "AUTH EXTERNAL" => bus.write_all(b"DATA\r\n").expect("write"),
2803 "BEGIN" => break,
2804 _ => bus.write_all(b"OK 0123456789abcdef\r\n").expect("write"),
2805 }
2806 }
2807 for _ in 0..2 {
2808 let call = Message::decode(&read_frame(&mut bus).expect("frame")).expect("msg");
2809 let name = if call.member.as_deref() == Some("Hello") {
2810 vec![Value::str(":1.7")]
2811 } else {
2812 call.body.clone()
2813 };
2814 let mut reply = Message::reply_to(&call, name);
2815 reply.serial = 100 + call.serial;
2816 bus.write_all(&reply.encode().expect("encode"))
2817 .expect("write");
2818 }
2819 let _ = read_frame(&mut bus);
2821 });
2822 let conn = Connection::from_unix_stream(client).expect("connect");
2823 assert_eq!(conn.unique_name(), ":1.7");
2824 let echoed = conn
2825 .call("x.y", "/", "x.y", "Echo", &[Value::str("ping")])
2826 .expect("echo");
2827 assert_eq!(echoed, vec![Value::str("ping")]);
2828 let err = conn.call("x.y", "/", "x.y", "Never", &[]);
2829 std::assert_matches!(err, Err(Error::Disconnected), "{err:?}");
2830 peer.join().expect("peer");
2831 assert!(conn.is_closed());
2832 std::assert_matches!(
2833 conn.emit_signal("/", "x.y", "Z", &[]),
2834 Err(Error::Disconnected)
2835 );
2836 }
2837}