1use core::convert::TryFrom;
2
3use serde::de::{self, DeserializeSeed, EnumAccess, MapAccess, SeqAccess, Visitor};
4use static_assertions::assert_impl_all;
5
6use std::{marker::PhantomData, str};
7
8#[cfg(unix)]
9use std::os::unix::io::RawFd;
10
11use crate::{
12 de::ValueParseStage, signature_parser::SignatureParser, utils::*, Basic, EncodingContext,
13 EncodingFormat, Error, ObjectPath, Result, Signature,
14};
15
16#[cfg(unix)]
17use crate::Fd;
18
19/// Our D-Bus deserialization implementation.
20#[derive(Debug)]
21pub struct Deserializer<'de, 'sig, 'f, B>(pub(crate) crate::DeserializerCommon<'de, 'sig, 'f, B>);
22
23assert_impl_all!(Deserializer<'_, '_, '_, i32>: Send, Sync, Unpin);
24
25impl<'de, 'sig, 'f, B> Deserializer<'de, 'sig, 'f, B>
26where
27 B: byteorder::ByteOrder,
28{
29 /// Create a Deserializer struct instance.
30 ///
31 /// On Windows, there is no `fds` argument.
32 pub fn new<'r: 'de>(
33 bytes: &'r [u8],
34 #[cfg(unix)] fds: Option<&'f [RawFd]>,
35 signature: &Signature<'sig>,
36 ctxt: EncodingContext<B>,
37 ) -> Self {
38 assert_eq!(ctxt.format(), EncodingFormat::DBus);
39
40 let sig_parser = SignatureParser::new(signature.clone());
41 Self(crate::DeserializerCommon {
42 ctxt,
43 sig_parser,
44 bytes,
45 #[cfg(unix)]
46 fds,
47 #[cfg(not(unix))]
48 fds: PhantomData,
49 pos: 0,
50 container_depths: Default::default(),
51 b: PhantomData,
52 })
53 }
54}
55
56macro_rules! deserialize_basic {
57 ($method:ident $read_method:ident $visitor_method:ident($type:ty)) => {
58 fn $method<V>(self, visitor: V) -> Result<V::Value>
59 where
60 V: Visitor<'de>,
61 {
62 let v = B::$read_method(self.0.next_const_size_slice::<$type>()?);
63
64 visitor.$visitor_method(v)
65 }
66 };
67}
68
69macro_rules! deserialize_as {
70 ($method:ident => $as:ident) => {
71 deserialize_as!($method() => $as());
72 };
73 ($method:ident($($in_arg:ident: $type:ty),*) => $as:ident($($as_arg:expr),*)) => {
74 #[inline]
75 fn $method<V>(self, $($in_arg: $type,)* visitor: V) -> Result<V::Value>
76 where
77 V: Visitor<'de>,
78 {
79 self.$as($($as_arg,)* visitor)
80 }
81 }
82}
83
84impl<'de, 'd, 'sig, 'f, B> de::Deserializer<'de> for &'d mut Deserializer<'de, 'sig, 'f, B>
85where
86 B: byteorder::ByteOrder,
87{
88 type Error = Error;
89
90 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
91 where
92 V: Visitor<'de>,
93 {
94 let c = self.0.sig_parser.next_char()?;
95
96 crate::de::deserialize_any::<Self, V>(self, c, visitor)
97 }
98
99 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
100 where
101 V: Visitor<'de>,
102 {
103 let v = B::read_u32(self.0.next_const_size_slice::<bool>()?);
104 let b = match v {
105 1 => true,
106 0 => false,
107 // As per D-Bus spec, only 0 and 1 values are allowed
108 _ => {
109 return Err(de::Error::invalid_value(
110 de::Unexpected::Unsigned(v as u64),
111 &"0 or 1",
112 ))
113 }
114 };
115
116 visitor.visit_bool(b)
117 }
118
119 fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
120 where
121 V: Visitor<'de>,
122 {
123 self.deserialize_i16(visitor)
124 }
125
126 deserialize_basic!(deserialize_i16 read_i16 visit_i16(i16));
127 deserialize_basic!(deserialize_i64 read_i64 visit_i64(i64));
128 deserialize_basic!(deserialize_u16 read_u16 visit_u16(u16));
129 deserialize_basic!(deserialize_u32 read_u32 visit_u32(u32));
130 deserialize_basic!(deserialize_u64 read_u64 visit_u64(u64));
131 deserialize_basic!(deserialize_f64 read_f64 visit_f64(f64));
132
133 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
134 where
135 V: Visitor<'de>,
136 {
137 let bytes = deserialize_ay(self)?;
138 visitor.visit_byte_buf(bytes.into())
139 }
140
141 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
142 where
143 V: Visitor<'de>,
144 {
145 let bytes = deserialize_ay(self)?;
146 visitor.visit_borrowed_bytes(bytes)
147 }
148
149 deserialize_as!(deserialize_char => deserialize_str);
150 deserialize_as!(deserialize_string => deserialize_str);
151 deserialize_as!(deserialize_tuple(_l: usize) => deserialize_struct("", &[]));
152 deserialize_as!(deserialize_tuple_struct(n: &'static str, _l: usize) => deserialize_struct(n, &[]));
153 deserialize_as!(deserialize_struct(_n: &'static str, _f: &'static [&'static str]) => deserialize_seq());
154 deserialize_as!(deserialize_map => deserialize_seq);
155 deserialize_as!(deserialize_ignored_any => deserialize_any);
156
157 fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
158 where
159 V: Visitor<'de>,
160 {
161 let v = match self.0.sig_parser.next_char()? {
162 #[cfg(unix)]
163 Fd::SIGNATURE_CHAR => {
164 self.0.sig_parser.skip_char()?;
165 let alignment = u32::alignment(EncodingFormat::DBus);
166 self.0.parse_padding(alignment)?;
167 let idx = B::read_u32(self.0.next_slice(alignment)?);
168 self.0.get_fd(idx)?
169 }
170 _ => B::read_i32(self.0.next_const_size_slice::<i32>()?),
171 };
172
173 visitor.visit_i32(v)
174 }
175
176 fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
177 where
178 V: Visitor<'de>,
179 {
180 // Endianness is irrelevant for single bytes.
181 visitor.visit_u8(self.0.next_const_size_slice::<u8>().map(|bytes| bytes[0])?)
182 }
183
184 fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
185 where
186 V: Visitor<'de>,
187 {
188 let v = B::read_f64(self.0.next_const_size_slice::<f64>()?);
189
190 visitor.visit_f32(f64_to_f32(v))
191 }
192
193 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
194 where
195 V: Visitor<'de>,
196 {
197 let len = match self.0.sig_parser.next_char()? {
198 Signature::SIGNATURE_CHAR | VARIANT_SIGNATURE_CHAR => {
199 let len_slice = self.0.next_slice(1)?;
200
201 len_slice[0] as usize
202 }
203 <&str>::SIGNATURE_CHAR | ObjectPath::SIGNATURE_CHAR => {
204 let alignment = u32::alignment(EncodingFormat::DBus);
205 self.0.parse_padding(alignment)?;
206 let len_slice = self.0.next_slice(alignment)?;
207
208 B::read_u32(len_slice) as usize
209 }
210 c => {
211 let expected = format!(
212 "`{}`, `{}`, `{}` or `{}`",
213 <&str>::SIGNATURE_STR,
214 Signature::SIGNATURE_STR,
215 ObjectPath::SIGNATURE_STR,
216 VARIANT_SIGNATURE_CHAR,
217 );
218 return Err(de::Error::invalid_type(
219 de::Unexpected::Char(c),
220 &expected.as_str(),
221 ));
222 }
223 };
224 let slice = self.0.next_slice(len)?;
225 if slice.contains(&0) {
226 return Err(serde::de::Error::invalid_value(
227 serde::de::Unexpected::Char('\0'),
228 &"D-Bus string type must not contain interior null bytes",
229 ));
230 }
231 self.0.pos += 1; // skip trailing null byte
232 let s = str::from_utf8(slice).map_err(Error::Utf8)?;
233 self.0.sig_parser.skip_char()?;
234
235 visitor.visit_borrowed_str(s)
236 }
237
238 fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value>
239 where
240 V: Visitor<'de>,
241 {
242 Err(de::Error::custom(
243 "D-Bus format does not support optional values",
244 ))
245 }
246
247 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
248 where
249 V: Visitor<'de>,
250 {
251 visitor.visit_unit()
252 }
253
254 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
255 where
256 V: Visitor<'de>,
257 {
258 visitor.visit_unit()
259 }
260
261 fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
262 where
263 V: Visitor<'de>,
264 {
265 visitor.visit_newtype_struct(self)
266 }
267
268 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
269 where
270 V: Visitor<'de>,
271 {
272 match self.0.sig_parser.next_char()? {
273 VARIANT_SIGNATURE_CHAR => {
274 let value_de = ValueDeserializer::new(self);
275
276 visitor.visit_seq(value_de)
277 }
278 ARRAY_SIGNATURE_CHAR => {
279 self.0.sig_parser.skip_char()?;
280 let next_signature_char = self.0.sig_parser.next_char()?;
281 let array_de = ArrayDeserializer::new(self)?;
282
283 if next_signature_char == DICT_ENTRY_SIG_START_CHAR {
284 visitor.visit_map(ArrayMapDeserializer(array_de))
285 } else {
286 visitor.visit_seq(ArraySeqDeserializer(array_de))
287 }
288 }
289 STRUCT_SIG_START_CHAR => {
290 let signature = self.0.sig_parser.next_signature()?;
291 let alignment = alignment_for_signature(&signature, EncodingFormat::DBus)?;
292 self.0.parse_padding(alignment)?;
293
294 self.0.sig_parser.skip_char()?;
295
296 self.0.container_depths = self.0.container_depths.inc_structure()?;
297 let v = visitor.visit_seq(StructureDeserializer { de: self });
298 self.0.container_depths = self.0.container_depths.dec_structure();
299
300 v
301 }
302 u8::SIGNATURE_CHAR => {
303 // Empty struct: encoded as a `0u8`.
304 let _: u8 = serde::Deserialize::deserialize(&mut *self)?;
305
306 visitor.visit_seq(StructureDeserializer { de: self })
307 }
308 c => Err(de::Error::invalid_type(
309 de::Unexpected::Char(c),
310 &format!(
311 "`{VARIANT_SIGNATURE_CHAR}`, `{ARRAY_SIGNATURE_CHAR}` or `{STRUCT_SIG_START_CHAR}`",
312 )
313 .as_str(),
314 )),
315 }
316 }
317
318 fn deserialize_enum<V>(
319 self,
320 name: &'static str,
321 _variants: &'static [&'static str],
322 visitor: V,
323 ) -> Result<V::Value>
324 where
325 V: Visitor<'de>,
326 {
327 let signature = self.0.sig_parser.next_signature()?;
328 let alignment = alignment_for_signature(&signature, self.0.ctxt.format())?;
329 self.0.parse_padding(alignment)?;
330
331 let non_unit = if self.0.sig_parser.next_char()? == STRUCT_SIG_START_CHAR {
332 // This means we've a non-unit enum. Let's skip the `(`.
333 self.0.sig_parser.skip_char()?;
334
335 true
336 } else {
337 false
338 };
339
340 let v = visitor.visit_enum(crate::de::Enum {
341 de: &mut *self,
342 name,
343 phantom: PhantomData,
344 })?;
345
346 if non_unit {
347 // For non-unit enum, we need to skip the closing paren.
348 self.0.sig_parser.skip_char()?;
349 }
350
351 Ok(v)
352 }
353
354 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
355 where
356 V: Visitor<'de>,
357 {
358 if self.0.sig_parser.next_char()? == <&str>::SIGNATURE_CHAR {
359 self.deserialize_str(visitor)
360 } else {
361 self.deserialize_u32(visitor)
362 }
363 }
364
365 fn is_human_readable(&self) -> bool {
366 false
367 }
368}
369
370struct ArrayDeserializer<'d, 'de, 'sig, 'f, B> {
371 de: &'d mut Deserializer<'de, 'sig, 'f, B>,
372 len: usize,
373 start: usize,
374 // alignment of element
375 element_alignment: usize,
376 // where value signature starts
377 element_signature_len: usize,
378}
379
380impl<'d, 'de, 'sig, 'f, B> ArrayDeserializer<'d, 'de, 'sig, 'f, B>
381where
382 B: byteorder::ByteOrder,
383{
384 fn new(de: &'d mut Deserializer<'de, 'sig, 'f, B>) -> Result<Self> {
385 de.0.parse_padding(ARRAY_ALIGNMENT_DBUS)?;
386 de.0.container_depths = de.0.container_depths.inc_array()?;
387
388 let len = B::read_u32(de.0.next_slice(4)?) as usize;
389 let element_signature = de.0.sig_parser.next_signature()?;
390 let element_alignment = alignment_for_signature(&element_signature, EncodingFormat::DBus)?;
391 let mut element_signature_len = element_signature.len();
392
393 // D-Bus requires padding for the first element even when there is no first element
394 // (i-e empty array) so we parse padding already.
395 de.0.parse_padding(element_alignment)?;
396 let start = de.0.pos;
397
398 if de.0.sig_parser.next_char()? == DICT_ENTRY_SIG_START_CHAR {
399 de.0.sig_parser.skip_char()?;
400 element_signature_len -= 1;
401 }
402
403 Ok(Self {
404 de,
405 len,
406 start,
407 element_alignment,
408 element_signature_len,
409 })
410 }
411
412 fn next<T>(&mut self, seed: T, sig_parser: SignatureParser<'_>) -> Result<T::Value>
413 where
414 T: DeserializeSeed<'de>,
415 {
416 let ctxt = EncodingContext::new_dbus(self.de.0.ctxt.position() + self.de.0.pos);
417
418 let mut de = Deserializer::<B>(crate::DeserializerCommon {
419 ctxt,
420 sig_parser,
421 bytes: subslice(self.de.0.bytes, self.de.0.pos..)?,
422 fds: self.de.0.fds,
423 pos: 0,
424 container_depths: self.de.0.container_depths,
425 b: PhantomData,
426 });
427 let v = seed.deserialize(&mut de);
428 self.de.0.pos += de.0.pos;
429 // No need for retaking the container depths as the child can't be incomplete.
430
431 if self.de.0.pos > self.start + self.len {
432 return Err(serde::de::Error::invalid_length(
433 self.len,
434 &format!(">= {}", self.de.0.pos - self.start).as_str(),
435 ));
436 }
437
438 v
439 }
440
441 fn next_element<T>(
442 &mut self,
443 seed: T,
444 sig_parser: SignatureParser<'_>,
445 ) -> Result<Option<T::Value>>
446 where
447 T: DeserializeSeed<'de>,
448 {
449 if self.done() {
450 self.de
451 .0
452 .sig_parser
453 .skip_chars(self.element_signature_len)?;
454 self.de.0.container_depths = self.de.0.container_depths.dec_array();
455
456 return Ok(None);
457 }
458
459 self.de.0.parse_padding(self.element_alignment)?;
460
461 self.next(seed, sig_parser).map(Some)
462 }
463
464 fn done(&self) -> bool {
465 self.de.0.pos == self.start + self.len
466 }
467}
468
469fn deserialize_ay<'de, B>(de: &mut Deserializer<'de, '_, '_, B>) -> Result<&'de [u8]>
470where
471 B: byteorder::ByteOrder,
472{
473 if de.0.sig_parser.next_signature()? != "ay" {
474 return Err(de::Error::invalid_type(unexp:de::Unexpected::Seq, &"ay"));
475 }
476
477 de.0.sig_parser.skip_char()?;
478 let ad: ArrayDeserializer<'_, '_, '_, '_, …> = ArrayDeserializer::new(de)?;
479 let len: usize = ad.len;
480 de.0.sig_parser.skip_char()?;
481 de.0.next_slice(len)
482}
483
484struct ArraySeqDeserializer<'d, 'de, 'sig, 'f, B>(ArrayDeserializer<'d, 'de, 'sig, 'f, B>);
485
486impl<'d, 'de, 'sig, 'f, B> SeqAccess<'de> for ArraySeqDeserializer<'d, 'de, 'sig, 'f, B>
487where
488 B: byteorder::ByteOrder,
489{
490 type Error = Error;
491
492 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
493 where
494 T: DeserializeSeed<'de>,
495 {
496 let sig_parser: SignatureParser<'_> = self.0.de.0.sig_parser.clone();
497 self.0.next_element(seed, sig_parser)
498 }
499}
500
501struct ArrayMapDeserializer<'d, 'de, 'sig, 'f, B>(ArrayDeserializer<'d, 'de, 'sig, 'f, B>);
502
503impl<'d, 'de, 'sig, 'f, B> MapAccess<'de> for ArrayMapDeserializer<'d, 'de, 'sig, 'f, B>
504where
505 B: byteorder::ByteOrder,
506{
507 type Error = Error;
508
509 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
510 where
511 K: DeserializeSeed<'de>,
512 {
513 let sig_parser: SignatureParser<'_> = self.0.de.0.sig_parser.clone();
514 self.0.next_element(seed, sig_parser)
515 }
516
517 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
518 where
519 V: DeserializeSeed<'de>,
520 {
521 let mut sig_parser: SignatureParser<'_> = self.0.de.0.sig_parser.clone();
522 // Skip key signature (always 1 char)
523 sig_parser.skip_char()?;
524 self.0.next(seed, sig_parser)
525 }
526}
527
528#[derive(Debug)]
529struct StructureDeserializer<'d, 'de, 'sig, 'f, B> {
530 de: &'d mut Deserializer<'de, 'sig, 'f, B>,
531}
532
533impl<'d, 'de, 'sig, 'f, B> SeqAccess<'de> for StructureDeserializer<'d, 'de, 'sig, 'f, B>
534where
535 B: byteorder::ByteOrder,
536{
537 type Error = Error;
538
539 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
540 where
541 T: DeserializeSeed<'de>,
542 {
543 let v: Result::Value>, …> = seed.deserialize(&mut *self.de).map(op:Some);
544
545 if self.de.0.sig_parser.next_char()? == STRUCT_SIG_END_CHAR {
546 // Last item in the struct
547 self.de.0.sig_parser.skip_char()?;
548 }
549
550 v
551 }
552}
553
554#[derive(Debug)]
555struct ValueDeserializer<'d, 'de, 'sig, 'f, B> {
556 de: &'d mut Deserializer<'de, 'sig, 'f, B>,
557 stage: ValueParseStage,
558 sig_start: usize,
559}
560
561impl<'d, 'de, 'sig, 'f, B> ValueDeserializer<'d, 'de, 'sig, 'f, B>
562where
563 B: byteorder::ByteOrder,
564{
565 fn new(de: &'d mut Deserializer<'de, 'sig, 'f, B>) -> Self {
566 let sig_start: usize = de.0.pos;
567 ValueDeserializer::<B> {
568 de,
569 stage: ValueParseStage::Signature,
570 sig_start,
571 }
572 }
573}
574
575impl<'d, 'de, 'sig, 'f, B> SeqAccess<'de> for ValueDeserializer<'d, 'de, 'sig, 'f, B>
576where
577 B: byteorder::ByteOrder,
578{
579 type Error = Error;
580
581 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
582 where
583 T: DeserializeSeed<'de>,
584 {
585 match self.stage {
586 ValueParseStage::Signature => {
587 self.stage = ValueParseStage::Value;
588
589 seed.deserialize(&mut *self.de).map(Some)
590 }
591 ValueParseStage::Value => {
592 self.stage = ValueParseStage::Done;
593
594 let sig_len = self.de.0.bytes[self.sig_start] as usize;
595 // skip length byte
596 let sig_start = self.sig_start + 1;
597 let sig_end = sig_start + sig_len;
598 // Skip trailing nul byte
599 let value_start = sig_end + 1;
600
601 let slice = subslice(self.de.0.bytes, sig_start..sig_end)?;
602 let signature = Signature::try_from(slice)?;
603 let sig_parser = SignatureParser::new(signature);
604
605 let ctxt = EncodingContext::new(
606 EncodingFormat::DBus,
607 self.de.0.ctxt.position() + value_start,
608 );
609 let mut de = Deserializer::<B>(crate::DeserializerCommon {
610 ctxt,
611 sig_parser,
612 bytes: subslice(self.de.0.bytes, value_start..)?,
613 fds: self.de.0.fds,
614 pos: 0,
615 container_depths: self.de.0.container_depths.inc_variant()?,
616 b: PhantomData,
617 });
618
619 let v = seed.deserialize(&mut de).map(Some);
620 self.de.0.pos += de.0.pos;
621
622 v
623 }
624 ValueParseStage::Done => Ok(None),
625 }
626 }
627}
628
629impl<'de, 'd, 'sig, 'f, B> EnumAccess<'de>
630 for crate::de::Enum<B, &'d mut Deserializer<'de, 'sig, 'f, B>>
631where
632 B: byteorder::ByteOrder,
633{
634 type Error = Error;
635 type Variant = Self;
636
637 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
638 where
639 V: DeserializeSeed<'de>,
640 {
641 seed.deserialize(&mut *self.de).map(|v: ::Value| (v, self))
642 }
643}
644