rasn/oer/
de.rs

1//! Decoding Octet Encoding Rules data into Rust structures.
2
3// ITU-T X.696 (02/2021) version of OER decoding
4// In OER, without knowledge of the type of the value encoded, it is not possible to determine
5// the structure of the encoding. In particular, the end of the encoding cannot be determined from
6// the encoding itself without knowledge of the type being encoded ITU-T X.696 (6.2).
7
8use alloc::{
9    borrow::Cow,
10    string::{String, ToString},
11    vec::Vec,
12};
13
14use core::num::NonZeroUsize;
15use nom::Needed;
16
17use crate::{
18    de::{Decode, Error as _},
19    oer::EncodingRules,
20    types::{
21        self,
22        fields::{Field, Fields},
23        Any, BitString, BmpString, Constraints, Constructed, DecodeChoice, Enumerated,
24        GeneralString, GeneralizedTime, GraphicString, Ia5String, IntegerType, NumericString,
25        ObjectIdentifier, PrintableString, SetOf, Tag, TeletexString, UtcTime, VisibleString,
26    },
27    Codec,
28};
29
30use bitvec::{order::Msb0, view::BitView};
31
32use crate::error::{CoerDecodeErrorKind, DecodeError, DecodeErrorKind, OerDecodeErrorKind};
33
34/// Options for configuring the [`Decoder`].
35#[derive(Clone, Copy, Debug)]
36pub struct DecoderOptions {
37    encoding_rules: EncodingRules, // default COER
38}
39
40impl DecoderOptions {
41    /// Returns the default decoding rules options for [`EncodingRules::Oer`].
42    #[must_use]
43    pub const fn oer() -> Self {
44        Self {
45            encoding_rules: EncodingRules::Oer,
46        }
47    }
48
49    /// Returns the default decoding rules options for [`EncodingRules::Coer`].
50    #[must_use]
51    pub const fn coer() -> Self {
52        Self {
53            encoding_rules: EncodingRules::Coer,
54        }
55    }
56
57    #[must_use]
58    fn current_codec(self) -> Codec {
59        match self.encoding_rules {
60            EncodingRules::Oer => Codec::Oer,
61            EncodingRules::Coer => Codec::Coer,
62        }
63    }
64}
65
66/// Decodes Octet Encoding Rules (OER) data into Rust data structures.
67pub struct Decoder<'input, const RFC: usize = 0, const EFC: usize = 0> {
68    input: &'input [u8],
69    options: DecoderOptions,
70    fields: ([Option<Field>; RFC], usize),
71    extension_fields: Option<Fields<EFC>>,
72    extensions_present: Option<Option<([Option<Field>; EFC], usize)>>,
73}
74
75impl<'input, const RFC: usize, const EFC: usize> Decoder<'input, RFC, EFC> {
76    /// Creates a new Decoder from the given input and options.
77    #[must_use]
78    pub fn new(input: &'input [u8], options: DecoderOptions) -> Self {
79        Self {
80            input,
81            options,
82            fields: ([None; RFC], 0),
83            extension_fields: <_>::default(),
84            extensions_present: <_>::default(),
85        }
86    }
87
88    #[must_use]
89    fn codec(&self) -> Codec {
90        self.options.current_codec()
91    }
92    /// Returns reference to the remaining input data that has not been parsed.
93    #[must_use]
94    pub fn remaining(&self) -> &'input [u8] {
95        self.input
96    }
97
98    fn parse_one_byte(&mut self) -> Result<u8, DecodeError> {
99        let (first, rest) = self.input.split_first().ok_or_else(|| {
100            DecodeError::parser_fail(
101                "Unexpected end of data when parsing single byte from &[u8]".to_string(),
102                self.codec(),
103            )
104        })?;
105        self.input = rest;
106        Ok(*first)
107    }
108
109    fn parse_tag(&mut self) -> Result<Tag, DecodeError> {
110        // Seems like tag number
111        use crate::types::Class;
112        let first_byte = self.parse_one_byte()?;
113        let class = match first_byte >> 6 {
114            0b00 => Class::Universal,
115            0b01 => Class::Application,
116            0b10 => Class::Context,
117            0b11 => Class::Private,
118            class => return Err(OerDecodeErrorKind::InvalidTagClassOnChoice { class }.into()),
119        };
120        let tag_number = first_byte & 0b0011_1111;
121        if tag_number == 0b11_1111 {
122            // Long form
123            let mut tag_number = 0u32;
124            let mut next_byte = self.parse_one_byte()?;
125            // The first octet cannot have last 7 bits set to 0
126            if next_byte.trailing_zeros() >= 7 || next_byte == 0 {
127                return Err(OerDecodeErrorKind::invalid_tag_number_on_choice(u32::from(
128                    next_byte & 0b1000_0000,
129                )));
130            }
131            loop {
132                // Constructs tag number from multiple 7-bit sized chunks
133                tag_number = tag_number
134                    .checked_shl(7)
135                    .ok_or(OerDecodeErrorKind::invalid_tag_number_on_choice(tag_number))?
136                    | u32::from(next_byte & 0b0111_1111);
137                // The zero-first-bit marks the octet as last
138                if next_byte & 0b1000_0000 == 0 {
139                    break;
140                }
141                next_byte = self.parse_one_byte()?;
142            }
143            Ok(Tag::new(class, tag_number))
144        } else {
145            Ok(Tag::new(class, u32::from(tag_number)))
146        }
147    }
148
149    /// There is a short form and long form for length determinant in OER encoding.
150    /// In short form one octet is used and the leftmost bit is always zero; length is less than 128
151    /// Max length for data type could be 2^1016 - 1 octets, however on this implementation it is limited to `usize::MAX`
152    fn decode_length(&mut self) -> Result<usize, DecodeError> {
153        let possible_length = self.parse_one_byte()?;
154        if possible_length < 128 {
155            Ok(usize::from(possible_length))
156        } else {
157            // We have the length of the length, mask and extract only 7 bis
158            let length = possible_length & 0x7fu8;
159            // Length of length cannot be zero
160            if length == 0 {
161                return Err(DecodeError::from_kind(
162                    DecodeErrorKind::ZeroLengthOfLength,
163                    self.codec(),
164                ));
165            }
166            let (data, rest) = self
167                .input
168                .split_at_checked(length as usize)
169                .ok_or_else(|| {
170                    DecodeError::parser_fail(
171                        alloc::format!("Unexpected end of data when parsing length by length of length {length} from &[u8]"
172                            ),
173                        self.codec(),
174                    )
175                })?;
176            self.input = rest;
177
178            if self.options.encoding_rules.is_coer() && data.first() == Some(&0) {
179                return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
180                    msg: "Length value should not have leading zeroes in COER".to_string(),
181                }
182                .into());
183            }
184            let length = usize::try_from_unsigned_bytes(data, self.codec())?;
185            if length < 128 && self.options.encoding_rules.is_coer() {
186                return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
187                    msg: "Length determinant could have been encoded in short form.".to_string(),
188                }
189                .into());
190            }
191            Ok(length)
192        }
193    }
194
195    /// Extracts data from input by length and updates the input
196    /// 'length' is the length of the data in bytes (octets)
197    /// Returns the data
198    fn extract_data_by_length(&mut self, length: usize) -> Result<&'input [u8], DecodeError> {
199        if length == 0 {
200            return Ok(&[]);
201        }
202        let (data, rest) = self.input.split_at_checked(length).ok_or_else(|| {
203            DecodeError::incomplete(
204                Needed::Size(NonZeroUsize::new(length - self.input.len()).unwrap()),
205                self.codec(),
206            )
207        })?;
208        self.input = rest;
209        Ok(data)
210    }
211
212    fn decode_integer_from_bytes<I: crate::types::IntegerType>(
213        &mut self,
214        signed: bool,
215        length: Option<usize>,
216    ) -> Result<I, DecodeError> {
217        let final_length = match length {
218            Some(l) => l,
219            None => self.decode_length()?,
220        };
221
222        let codec = self.codec();
223        let coer = self.options.encoding_rules.is_coer();
224        let data = self.extract_data_by_length(final_length)?;
225        // // Constrained data can correctly include leading zeros, unconstrained not
226        if coer && !signed && data.first() == Some(&0) && length.is_none() {
227            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
228                msg: "Leading zeros are not allowed on unsigned Integer value in COER.".to_string(),
229            }
230            .into());
231        }
232        if signed {
233            Ok(I::try_from_signed_bytes(data, codec)?)
234        } else {
235            Ok(I::try_from_unsigned_bytes(data, codec)?)
236        }
237    }
238
239    fn decode_integer_with_constraints<I: crate::types::IntegerType>(
240        &mut self,
241        constraints: &Constraints,
242    ) -> Result<I, DecodeError> {
243        // Only 'value' constraint is OER visible for integer
244        if let Some(value) = constraints.value() {
245            let (signed, octets) = if value.extensible.is_some() {
246                (true, None)
247            } else {
248                (value.constraint.get_sign(), value.constraint.get_range())
249            };
250            let integer = self.decode_integer_from_bytes::<I>(signed, octets.map(usize::from))?;
251            // if the value is too large for a i128, the constraint isn't satisfied
252            if let Some(constraint_integer) = integer.to_i128() {
253                if value.constraint.contains(&constraint_integer) {
254                    Ok(integer)
255                } else {
256                    Err(DecodeError::value_constraint_not_satisfied(
257                        integer.to_bigint().unwrap_or_default(),
258                        value.constraint.value,
259                        self.codec(),
260                    ))
261                }
262            } else {
263                Err(DecodeError::value_constraint_not_satisfied(
264                    integer.to_bigint().unwrap_or_default(),
265                    value.constraint.value,
266                    self.codec(),
267                ))
268            }
269            // })
270        } else {
271            // No constraints
272            self.decode_integer_from_bytes::<I>(true, None)
273        }
274    }
275
276    fn parse_bit_string(&mut self, constraints: &Constraints) -> Result<BitString, DecodeError> {
277        if let Some(size) = constraints.size() {
278            // Fixed size, only data is included
279            if size.constraint.is_fixed() && size.extensible.is_none() {
280                let length = size.constraint.as_start().ok_or_else(|| {
281                    Err(DecodeError::size_constraint_not_satisfied(
282                        None,
283                        "Fixed size constraint should have value".to_string(),
284                        self.codec(),
285                    ))
286                });
287                return match length {
288                    Ok(length) => {
289                        let bytes_required = (*length).div_ceil(8);
290                        let data = &self
291                            .extract_data_by_length(bytes_required)?
292                            .view_bits::<Msb0>()[..*length];
293                        Ok(data.into())
294                    }
295                    Err(e) => e,
296                };
297            }
298        }
299        let length = self.decode_length()?;
300        if length == 0 {
301            return Ok(BitString::new());
302        }
303
304        let num_unused_bits = self.parse_one_byte()?;
305        if length == 1 && num_unused_bits > 0 {
306            return Err(OerDecodeErrorKind::invalid_bit_string(
307                "Length includes only initial octet. There cannot be unused bits on the subsequent octects as there isn't any.".to_string(),
308            ));
309        }
310        if num_unused_bits > 7 {
311            return Err(OerDecodeErrorKind::invalid_bit_string(
312                "Marked number of unused bits should be less than 8 when decoding OER".to_string(),
313            ));
314        }
315        // Remove one from length as one describes trailing zeros...
316        let data_bit_length: usize = (&length - 1usize).checked_mul(8).ok_or_else(|| {
317            DecodeError::length_exceeds_platform_width(
318                "Total length exceeds BitSlice max usize when decoding BitString".to_string(),
319                self.codec(),
320            )
321        })?;
322        let data = &self.extract_data_by_length(length - 1)?.view_bits::<Msb0>()
323            [..(data_bit_length - num_unused_bits as usize)];
324        Ok(data.into())
325    }
326
327    fn parse_known_multiplier_string<
328        T: crate::types::strings::StaticPermittedAlphabet
329            + crate::types::AsnType
330            + for<'a> TryFrom<&'a [u8], Error = crate::error::strings::PermittedAlphabetError>,
331    >(
332        &mut self,
333        constraints: &Constraints,
334    ) -> Result<T, DecodeError> {
335        if let Some(size) = constraints.size() {
336            // Fixed size, only data is included
337            if size.constraint.is_fixed() && size.extensible.is_none() {
338                let data = self.extract_data_by_length(*size.constraint.as_start().unwrap())?;
339                return T::try_from(data)
340                    .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()));
341            }
342        }
343        let length = self.decode_length()?;
344        T::try_from(self.extract_data_by_length(length)?)
345            .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
346    }
347
348    #[track_caller]
349    fn require_field(&mut self, tag: Tag) -> Result<bool, DecodeError> {
350        let (fields, index) = &mut self.fields;
351        let Some(field) = fields.get(*index) else {
352            return Err(DecodeError::missing_tag_class_or_value_in_sequence_or_set(
353                tag.class,
354                tag.value,
355                self.codec(),
356            ));
357        };
358
359        *index += 1;
360        match field {
361            Some(field) if field.tag_tree.smallest_tag() == tag => Ok(true),
362            None => Ok(false),
363            _ => Err(DecodeError::missing_tag_class_or_value_in_sequence_or_set(
364                tag.class,
365                tag.value,
366                self.codec(),
367            )),
368        }
369    }
370
371    fn extension_is_present(&mut self) -> Result<Option<&Field>, DecodeError> {
372        let codec = self.codec();
373        let Some(Some((fields, index))) = self.extensions_present.as_mut() else {
374            return Err(DecodeError::type_not_extensible(codec));
375        };
376
377        let field = fields
378            .get(*index)
379            .ok_or_else(|| DecodeError::type_not_extensible(codec))?;
380
381        *index += 1;
382        Ok(field.as_ref())
383    }
384
385    fn parse_extension_header(&mut self) -> Result<bool, DecodeError> {
386        match self.extensions_present {
387            Some(Some(_)) => return Ok(true),
388            Some(None) => (),
389            None => return Ok(false),
390        }
391        let extensions_length = self.decode_length()?;
392        // If length is 0, then there is only initial octet
393        if extensions_length < 1u8.into() {
394            return Err(OerDecodeErrorKind::invalid_extension_header(
395                "Extension length should be at least 1 byte".to_string(),
396            ));
397        }
398        let extension_fields = self
399            .extension_fields
400            .ok_or_else(|| DecodeError::type_not_extensible(self.codec()))?;
401        // Must be at least 8 bits at this point or error is already raised
402        let bitfield_bytes = self.extract_data_by_length(extensions_length)?;
403        let (first_byte, bitfield) = bitfield_bytes.split_first().ok_or_else(|| {
404            OerDecodeErrorKind::invalid_extension_header("Missing initial octet".to_string())
405        })?;
406        let unused_bits = *first_byte as usize;
407
408        if unused_bits > 7 || unused_bits > bitfield.len() * 8 {
409            return Err(OerDecodeErrorKind::invalid_extension_header(
410                "Invalid extension bitfield initial octet".to_string(),
411            ));
412        }
413        let mut fields: [Option<Field>; EFC] = [None; EFC];
414        for (i, field) in extension_fields.iter().enumerate() {
415            let byte_idx = i / 8;
416            let bit_idx = 7 - (i & 7); // This gives us MSB0 ordering within each byte
417            let is_set = byte_idx < bitfield.len() && (bitfield[byte_idx] & (1 << bit_idx)) != 0;
418
419            if field.is_not_optional_or_default() && !is_set {
420                return Err(DecodeError::required_extension_not_present(
421                    field.tag,
422                    self.codec(),
423                ));
424            } else if is_set {
425                fields[i] = Some(field);
426            }
427        }
428
429        self.extensions_present = Some(Some((fields, 0)));
430        Ok(true)
431    }
432
433    fn parse_preamble<const RC: usize, const EC: usize, D>(
434        &mut self,
435    ) -> Result<([bool; RC], bool), DecodeError>
436    where
437        D: Constructed<RC, EC>,
438    {
439        let is_extensible = D::IS_EXTENSIBLE;
440        let preamble_width =
441            D::FIELDS.number_of_optional_and_default_fields() + usize::from(is_extensible);
442        let bytes = self.extract_data_by_length(preamble_width.div_ceil(8))?;
443
444        let mut result = [false; RC];
445        let mut extensible_present = false;
446
447        // Process each preamble bit we need
448        for i in 0..preamble_width {
449            let byte_idx = i / 8;
450            let bit_idx = 7 - (i & 7);
451            let is_set: bool = (bytes[byte_idx] & (1 << bit_idx)) != 0;
452
453            if i == 0 && is_extensible {
454                extensible_present = is_set;
455            } else if i - usize::from(is_extensible) < RC {
456                result[i - usize::from(is_extensible)] = is_set;
457            }
458        }
459
460        // Check that remaining bits are zero
461        let remaining_bits_start = preamble_width;
462        for i in remaining_bits_start..bytes.len() * 8 {
463            let byte_idx = i / 8;
464            let bit_idx = 7 - (i & 7);
465            if (bytes[byte_idx] & (1 << bit_idx)) != 0 {
466                return Err(OerDecodeErrorKind::invalid_preamble(
467                    "Preamble unused bits should be all zero.".to_string(),
468                ));
469            }
470        }
471
472        Ok((result, extensible_present))
473    }
474}
475impl<'input, const RFC: usize, const EFC: usize> crate::Decoder for Decoder<'input, RFC, EFC> {
476    type Ok = ();
477    type Error = DecodeError;
478    type AnyDecoder<const R: usize, const E: usize> = Decoder<'input, R, E>;
479
480    fn codec(&self) -> Codec {
481        self.codec()
482    }
483
484    /// In OER, an alias for decoding an open type and obtaining the underlying type's encoded bytes.
485    fn decode_any(&mut self, tag: Tag) -> Result<Any, Self::Error> {
486        Ok(Any::new(
487            self.decode_octet_string(tag, Constraints::default())?,
488        ))
489    }
490
491    fn decode_bit_string(
492        &mut self,
493        _: Tag,
494        constraints: Constraints,
495    ) -> Result<BitString, Self::Error> {
496        self.parse_bit_string(&constraints)
497    }
498
499    /// One octet is used to present bool, false is 0x0 and true is value up to 0xff
500    /// In COER, only 0x0 and 0xff are valid values
501    fn decode_bool(&mut self, _: Tag) -> Result<bool, Self::Error> {
502        let byte = self.parse_one_byte()?;
503        Ok(match byte {
504            0 => false,
505            0xFF => true,
506            _ if self.options.encoding_rules.is_oer() => true,
507            _ => {
508                return Err(DecodeError::from_kind(
509                    DecodeErrorKind::InvalidBool { value: byte },
510                    self.codec(),
511                ))
512            }
513        })
514    }
515
516    fn decode_enumerated<E: Enumerated>(&mut self, _: Tag) -> Result<E, Self::Error> {
517        let byte = self.parse_one_byte()?;
518        if byte < 128 {
519            // Short form, use value directly as unsigned integer
520            E::from_discriminant(isize::from(byte))
521                .ok_or_else(|| DecodeError::discriminant_value_not_found(byte.into(), self.codec()))
522        } else {
523            // Long form, value as signed integer. Previous byte is length of the subsequent octets
524            let length = byte & 0x7fu8;
525            let discriminant: isize = self
526                .decode_integer_from_bytes(true, Some(length.into()))
527                .map_err(|e| {
528                    if matches!(&*e.kind, DecodeErrorKind::IntegerOverflow { .. }) {
529                        DecodeError::length_exceeds_platform_width(
530                            "Enumerated discriminant value too large for this platform."
531                                .to_string(),
532                            self.codec(),
533                        )
534                    } else {
535                        e
536                    }
537                })?;
538
539            if (0..128).contains(&discriminant) && self.options.encoding_rules.is_coer() {
540                return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
541                    msg: "Enumerated discriminant should have been encoded in short form."
542                        .to_string(),
543                }
544                .into());
545            }
546            E::from_discriminant(discriminant).ok_or_else(|| {
547                DecodeError::discriminant_value_not_found(discriminant, self.codec())
548            })
549        }
550    }
551
552    fn decode_integer<I: crate::types::IntegerType>(
553        &mut self,
554        _: Tag,
555        constraints: Constraints,
556    ) -> Result<I, Self::Error> {
557        self.decode_integer_with_constraints::<I>(&constraints)
558    }
559
560    fn decode_real<R: crate::types::RealType>(
561        &mut self,
562        _: Tag,
563        _: Constraints,
564    ) -> Result<R, Self::Error> {
565        let octets = self.extract_data_by_length(R::BYTE_WIDTH)?;
566        R::try_from_ieee754_bytes(octets)
567            .map_err(|_| DecodeError::from_kind(DecodeErrorKind::InvalidRealEncoding, self.codec()))
568    }
569
570    /// Null contains no data, so we just skip
571    fn decode_null(&mut self, _: Tag) -> Result<(), Self::Error> {
572        Ok(())
573    }
574
575    fn decode_object_identifier(&mut self, _: Tag) -> Result<ObjectIdentifier, Self::Error> {
576        let length = self.decode_length()?;
577        let ber_decoder = crate::ber::de::Decoder::new(&[], crate::ber::de::DecoderOptions::ber());
578        ber_decoder.decode_object_identifier_from_bytes(self.extract_data_by_length(length)?)
579    }
580
581    fn decode_sequence<const RC: usize, const EC: usize, D, DF: FnOnce() -> D, F>(
582        &mut self,
583        _: Tag,
584        default_initializer_fn: Option<DF>,
585        decode_fn: F,
586    ) -> Result<D, Self::Error>
587    where
588        D: Constructed<RC, EC>,
589        F: FnOnce(&mut Self::AnyDecoder<RC, EC>) -> Result<D, Self::Error>,
590    {
591        // If there are no fields then the sequence is empty
592        // Or if all fields are optional and default and there is no data
593        if D::FIELDS.is_empty()
594            || D::FIELDS.len() == D::FIELDS.number_of_optional_and_default_fields()
595                && self.input.is_empty()
596        {
597            if let Some(default_initializer_fn) = default_initializer_fn {
598                return Ok((default_initializer_fn)());
599            }
600            return Err(DecodeError::from_kind(
601                DecodeErrorKind::UnexpectedEmptyInput,
602                self.codec(),
603            ));
604        }
605        // ### PREAMBLE ###
606        let (bitmap, extensible_present) = self.parse_preamble::<RC, EC, D>()?;
607        // ### ENDS
608        let mut fields = ([None; RC], 0);
609        D::FIELDS
610            .optional_and_default_fields()
611            .zip(bitmap)
612            .enumerate()
613            .for_each(|(i, (field, is_present))| {
614                if is_present {
615                    fields.0[i] = Some(field);
616                } else {
617                    fields.0[i] = None;
618                }
619            });
620
621        let value = {
622            let mut sequence_decoder = Decoder::new(self.input, self.options);
623            sequence_decoder.extension_fields = D::EXTENDED_FIELDS;
624            sequence_decoder.extensions_present = extensible_present.then_some(None);
625            sequence_decoder.fields = fields;
626            let value = decode_fn(&mut sequence_decoder)?;
627
628            self.input = sequence_decoder.input;
629            value
630        };
631
632        Ok(value)
633    }
634
635    fn decode_sequence_of<D: Decode>(
636        &mut self,
637        _: Tag,
638        _: Constraints,
639    ) -> Result<Vec<D>, Self::Error> {
640        let length_of_quantity = self.decode_length()?;
641        let coer = self.options.encoding_rules.is_coer();
642        let length_bytes = self.extract_data_by_length(length_of_quantity)?;
643        if coer && length_bytes.first() == Some(&0) && length_bytes.len() > 1 {
644            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
645                msg: "Quantity value in 'sequence/set of' should not have leading zeroes in COER"
646                    .to_string(),
647            }
648            .into());
649        }
650        let length = usize::try_from_unsigned_bytes(length_bytes, self.codec())?;
651        let mut sequence_of: Vec<D> = Vec::with_capacity(length);
652        let mut decoder = Self::new(self.input, self.options);
653        for _ in 0..length {
654            let value = D::decode(&mut decoder)?;
655            self.input = decoder.input;
656            sequence_of.push(value);
657        }
658        Ok(sequence_of)
659    }
660
661    fn decode_set_of<D: Decode + Eq + core::hash::Hash>(
662        &mut self,
663        tag: Tag,
664        constraints: Constraints,
665    ) -> Result<SetOf<D>, Self::Error> {
666        self.decode_sequence_of(tag, constraints)
667            .map(|seq| SetOf::from_vec(seq))
668    }
669
670    fn decode_octet_string<'b, T: From<&'b [u8]> + From<Vec<u8>>>(
671        &'b mut self,
672        _: Tag,
673        constraints: Constraints,
674    ) -> Result<T, Self::Error> {
675        if let Some(size) = constraints.size() {
676            // Fixed size, only data is included
677            if size.constraint.is_fixed() && size.extensible.is_none() {
678                let data =
679                    self.extract_data_by_length(*size.constraint.as_start().ok_or_else(|| {
680                        DecodeError::size_constraint_not_satisfied(
681                            None,
682                            "Fixed size constraint should have value when decoding Octet String"
683                                .to_string(),
684                            self.codec(),
685                        )
686                    })?)?;
687                return Ok(T::from(data));
688            }
689        }
690        let length = self.decode_length()?;
691        let data = self.extract_data_by_length(length)?;
692        Ok(T::from(data))
693    }
694
695    fn decode_utf8_string(
696        &mut self,
697        tag: Tag,
698        constraints: Constraints,
699    ) -> Result<String, Self::Error> {
700        self.decode_octet_string(tag, constraints)
701            .and_then(|bytes| {
702                String::from_utf8(bytes).map_err(|e| {
703                    DecodeError::string_conversion_failed(
704                        Tag::UTF8_STRING,
705                        e.to_string(),
706                        self.codec(),
707                    )
708                })
709            })
710    }
711
712    fn decode_visible_string(
713        &mut self,
714        _: Tag,
715        constraints: Constraints,
716    ) -> Result<VisibleString, Self::Error> {
717        self.parse_known_multiplier_string(&constraints)
718    }
719
720    fn decode_general_string(
721        &mut self,
722        _: Tag,
723        constraints: Constraints,
724    ) -> Result<GeneralString, Self::Error> {
725        self.parse_known_multiplier_string(&constraints)
726    }
727
728    fn decode_graphic_string(
729        &mut self,
730        _: Tag,
731        constraints: Constraints,
732    ) -> Result<GraphicString, Self::Error> {
733        self.parse_known_multiplier_string(&constraints)
734    }
735
736    fn decode_ia5_string(
737        &mut self,
738        _: Tag,
739        constraints: Constraints,
740    ) -> Result<Ia5String, Self::Error> {
741        self.parse_known_multiplier_string(&constraints)
742    }
743
744    fn decode_printable_string(
745        &mut self,
746        _: Tag,
747        constraints: Constraints,
748    ) -> Result<PrintableString, Self::Error> {
749        self.parse_known_multiplier_string(&constraints)
750    }
751
752    fn decode_numeric_string(
753        &mut self,
754        _: Tag,
755        constraints: Constraints,
756    ) -> Result<NumericString, Self::Error> {
757        self.parse_known_multiplier_string(&constraints)
758    }
759
760    fn decode_teletex_string(
761        &mut self,
762        _: Tag,
763        constraints: Constraints,
764    ) -> Result<TeletexString, Self::Error> {
765        self.parse_known_multiplier_string(&constraints)
766    }
767
768    fn decode_bmp_string(
769        &mut self,
770        _: Tag,
771        constraints: Constraints,
772    ) -> Result<BmpString, Self::Error> {
773        self.parse_known_multiplier_string(&constraints)
774    }
775    fn decode_optional_with_explicit_prefix<D: Decode>(
776        &mut self,
777        tag: Tag,
778    ) -> Result<Option<D>, Self::Error> {
779        self.decode_optional_with_tag(tag)
780    }
781
782    fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error> {
783        // Whether we have a choice here
784        if D::IS_CHOICE {
785            D::decode(self)
786        } else {
787            D::decode_with_tag(self, tag)
788        }
789    }
790
791    fn decode_utc_time(&mut self, tag: Tag) -> Result<UtcTime, Self::Error> {
792        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
793            .map_err(|_| {
794                DecodeError::string_conversion_failed(
795                    Tag::UTF8_STRING,
796                    "UTCTime should be UTF8 encoded.".to_string(),
797                    self.codec(),
798                )
799            })?;
800        crate::der::de::Decoder::parse_canonical_utc_time_string(&string)
801    }
802
803    fn decode_generalized_time(&mut self, tag: Tag) -> Result<GeneralizedTime, Self::Error> {
804        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
805            .map_err(|_| {
806                DecodeError::string_conversion_failed(
807                    Tag::UTF8_STRING,
808                    "GeneralizedTime should be UTF8 encoded".to_string(),
809                    self.codec(),
810                )
811            })?;
812        crate::der::de::Decoder::parse_canonical_generalized_time_string(string)
813    }
814
815    fn decode_date(&mut self, tag: Tag) -> Result<types::Date, Self::Error> {
816        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
817            .map_err(|_| {
818                DecodeError::string_conversion_failed(
819                    Tag::UTF8_STRING,
820                    "DATE should be UTF8 encoded".to_string(),
821                    self.codec(),
822                )
823            })?;
824        crate::der::de::Decoder::parse_date_string(&string)
825    }
826
827    fn decode_set<const RC: usize, const EC: usize, FIELDS, SET, D, F>(
828        &mut self,
829        _: Tag,
830        decode_fn: D,
831        field_fn: F,
832    ) -> Result<SET, Self::Error>
833    where
834        SET: Decode + Constructed<RC, EC>,
835        FIELDS: Decode,
836        D: Fn(&mut Self::AnyDecoder<RC, EC>, usize, Tag) -> Result<FIELDS, Self::Error>,
837        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>,
838    {
839        let (bitmap, extensible_present) = self.parse_preamble::<RC, EC, SET>()?;
840
841        let mut field_map: ([Option<Field>; RC], usize) = ([None; RC], 0);
842        for (i, (field, is_present)) in SET::FIELDS
843            .canonised()
844            .optional_and_default_fields()
845            .zip(bitmap)
846            .enumerate()
847        {
848            if is_present {
849                field_map.0[i] = Some(field);
850            } else {
851                field_map.0[i] = None;
852            }
853        }
854
855        let fields = {
856            let extended_fields_len = SET::EXTENDED_FIELDS.map_or(0, |fields| fields.len());
857            let mut fields = Vec::with_capacity(SET::FIELDS.len() + extended_fields_len);
858            let mut set_decoder = Decoder::new(self.input, self.options);
859            set_decoder.extension_fields = SET::EXTENDED_FIELDS;
860            set_decoder.extensions_present = extensible_present.then_some(None);
861            set_decoder.fields = field_map;
862
863            let mut opt_index = 0;
864            for field in SET::FIELDS.canonised().iter() {
865                if field.is_optional_or_default() {
866                    // Safe unwrap, we just created the field_map
867                    if field_map.0.get(opt_index).unwrap().is_some() {
868                        fields.push(decode_fn(&mut set_decoder, field.index, field.tag)?);
869                    }
870                    opt_index += 1;
871                } else {
872                    fields.push(decode_fn(&mut set_decoder, field.index, field.tag)?);
873                }
874            }
875            for (indice, field) in SET::EXTENDED_FIELDS
876                .iter()
877                .flat_map(Fields::iter)
878                .enumerate()
879            {
880                fields.push(decode_fn(
881                    &mut set_decoder,
882                    indice + SET::FIELDS.len(),
883                    field.tag,
884                )?);
885            }
886
887            self.input = set_decoder.input;
888            fields
889        };
890
891        field_fn(fields)
892    }
893
894    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
895    where
896        D: DecodeChoice,
897    {
898        let is_extensible = constraints.extensible();
899        let tag: Tag = self.parse_tag()?;
900        let is_root_extension = crate::types::TagTree::tag_contains(&tag, D::VARIANTS);
901        let is_extended_extension =
902            crate::types::TagTree::tag_contains(&tag, D::EXTENDED_VARIANTS.unwrap_or(&[]));
903        if is_root_extension {
904            D::from_tag(self, tag)
905        } else if is_extensible && is_extended_extension {
906            let options = self.options;
907            let length = self.decode_length()?;
908            let bytes = self.extract_data_by_length(length)?;
909            let mut decoder = Decoder::<0, 0>::new(bytes, options);
910            D::from_tag(&mut decoder, tag)
911        } else {
912            Err(OerDecodeErrorKind::invalid_tag_variant_on_choice(
913                tag,
914                is_extensible,
915            ))
916        }
917    }
918
919    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
920        self.decode_optional_with_tag(D::TAG)
921    }
922
923    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error> {
924        let is_present = self.require_field(tag)?;
925        if is_present {
926            D::decode_with_tag(self, tag).map(Some)
927        } else {
928            Ok(None)
929        }
930    }
931
932    fn decode_optional_with_constraints<D: Decode>(
933        &mut self,
934        constraints: Constraints,
935    ) -> Result<Option<D>, Self::Error> {
936        let is_present = self.require_field(D::TAG)?;
937        if is_present {
938            D::decode_with_constraints(self, constraints).map(Some)
939        } else {
940            Ok(None)
941        }
942    }
943
944    fn decode_optional_with_tag_and_constraints<D: Decode>(
945        &mut self,
946        tag: Tag,
947        constraints: Constraints,
948    ) -> Result<Option<D>, Self::Error> {
949        let is_present = self.require_field(tag)?;
950        if is_present {
951            D::decode_with_tag_and_constraints(self, tag, constraints).map(Some)
952        } else {
953            Ok(None)
954        }
955    }
956    fn decode_extension_addition_with_explicit_tag_and_constraints<D>(
957        &mut self,
958        tag: Tag,
959        constraints: Constraints,
960    ) -> Result<Option<D>, Self::Error>
961    where
962        D: Decode,
963    {
964        self.decode_extension_addition_with_tag_and_constraints::<D>(tag, constraints)
965    }
966
967    fn decode_extension_addition_with_tag_and_constraints<D>(
968        &mut self,
969        _tag: Tag,
970        constraints: Constraints,
971    ) -> Result<Option<D>, Self::Error>
972    where
973        D: Decode,
974    {
975        if !self.parse_extension_header()? {
976            return Ok(None);
977        }
978
979        let extension_is_present = self.extension_is_present()?.is_some();
980
981        if !extension_is_present {
982            return Ok(None);
983        }
984
985        // Values of the extensions are only left, encoded as Open type
986        let options = self.options;
987        let bytes: Cow<[u8]> =
988            self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
989        let mut decoder = Decoder::<0, 0>::new(&bytes, options);
990        D::decode_with_constraints(&mut decoder, constraints).map(Some)
991    }
992
993    fn decode_extension_addition_group<
994        const RC: usize,
995        const EC: usize,
996        D: Decode + Constructed<RC, EC>,
997    >(
998        &mut self,
999    ) -> Result<Option<D>, Self::Error> {
1000        if !self.parse_extension_header()? {
1001            return Ok(None);
1002        }
1003
1004        let extension_is_present = self.extension_is_present()?.is_some();
1005
1006        if !extension_is_present {
1007            return Ok(None);
1008        }
1009
1010        // Values of the extensions are only left, inner type encoded as Open type
1011        let options = self.options;
1012        let bytes: Cow<[u8]> =
1013            self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
1014        let mut decoder = Decoder::<0, 0>::new(&bytes, options);
1015        D::decode(&mut decoder).map(Some)
1016    }
1017}
1018
1019#[cfg(test)]
1020#[allow(clippy::assertions_on_constants)]
1021mod tests {
1022    use num_bigint::BigUint;
1023    // Max length for data type can be 2^1016, below presented as byte array of unsigned int
1024    const MAX_LENGTH: [u8; 127] = [0xff; 127];
1025    const MAX_LENGTH_LENGTH: usize = MAX_LENGTH.len();
1026    use super::*;
1027    use crate::types::constraints::Constraints;
1028    use bitvec::prelude::BitSlice;
1029    use num_bigint::BigInt;
1030
1031    #[test]
1032    fn test_decode_bool() {
1033        let decoded: bool = crate::oer::decode(&[0xffu8]).unwrap();
1034        assert!(decoded);
1035        let decoded: bool = crate::oer::decode(&[0u8]).unwrap();
1036        assert!(!decoded);
1037        let decoded: bool = crate::oer::decode(&[0xffu8, 0xff]).unwrap();
1038        assert!(decoded);
1039        let decoded: bool = crate::oer::decode(&[0x33u8, 0x0]).unwrap();
1040        assert!(decoded);
1041    }
1042
1043    #[test]
1044    fn test_decode_length_invalid() {
1045        let data = &[0xffu8];
1046        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1047        // Length determinant is > 127 without subsequent bytes
1048        assert!(decoder.decode_length().is_err());
1049        // Still missing some data
1050        let data = &[0xffu8, 0xff];
1051        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1052        // Length determinant is > 127 without subsequent bytes
1053        assert!(decoder.decode_length().is_err());
1054    }
1055
1056    #[test]
1057    fn test_decode_length_valid() {
1058        // Max length
1059        let max_length: BigUint = BigUint::from(2u8).pow(1016u32) - BigUint::from(1u8);
1060        assert_eq!(max_length.to_bytes_be(), MAX_LENGTH);
1061        assert_eq!(max_length.to_bytes_be().len(), MAX_LENGTH_LENGTH);
1062        // Unfortunately we cannot support lengths > 2^64 - 1 at the moment
1063        // Nor larger than BitSlice::<usize>::MAX_BITS
1064        assert!(max_length > usize::MAX.into());
1065        assert!(usize::MAX > BitSlice::<usize>::MAX_BITS);
1066
1067        // # SHORT FORM
1068        let data = &[0x01u8, 0xff];
1069        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1070        assert_eq!(decoder.decode_length().unwrap(), 1);
1071        let data = &[0x03u8, 0xff, 0xff, 0xfe];
1072        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1073        assert_eq!(decoder.decode_length().unwrap(), 3);
1074        // Max for short form
1075        let mut data: [u8; 0x80] = [0xffu8; 0x80];
1076        data[0] = 0x7f; // length determinant
1077        let data = &data;
1078        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1079        assert_eq!(decoder.decode_length().unwrap(), 127);
1080
1081        // # LONG FORM
1082        // Length of the length should be 2 octets, 0x7f - 0x82 = 2, length is 258 octets
1083        let length: [u8; 1] = [0x82u8]; // first bit is 1, remaining tells length of the length
1084        let length_determinant: [u8; 0x02] = [0x01u8, 0x02];
1085        let data: [u8; 258] = [0xffu8; 258];
1086        let mut combined: [u8; 261] = [0x0; 261];
1087        combined[..1].copy_from_slice(&length);
1088        combined[1..=2].copy_from_slice(&length_determinant);
1089        combined[3..].copy_from_slice(&data);
1090
1091        let data = &combined;
1092        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1093        assert_eq!(decoder.decode_length().unwrap(), 258usize);
1094    }
1095    #[test]
1096    fn test_long_form_length_decode() {
1097        let vc = &[
1098            0x81, 0x80, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1099            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1100            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1101            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1102            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1103            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1104            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1105            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1106            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1107            0xff, 0xff, 0xff, 0xff,
1108        ];
1109        let mut decoder = Decoder::<0, 0>::new(vc, DecoderOptions::oer());
1110        let number = BigInt::from(256).pow(127) - 1;
1111        let constraints = Constraints::default();
1112        let new_number: BigInt = decoder
1113            .decode_integer_with_constraints(&constraints)
1114            .unwrap();
1115        assert_eq!(new_number, number);
1116
1117        // Test maximum possible length
1118        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap()]; // first bit is 1, remaining tells length of the length
1119        let length_determinant: [u8; (usize::BITS / 8u32) as usize] =
1120            [0xff; (usize::BITS / 8u32) as usize];
1121        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize] =
1122            [0x0; 1 + (usize::BITS / 8u32) as usize];
1123        combined[..1].copy_from_slice(&length);
1124        combined[1..=(usize::BITS / 8u32) as usize].copy_from_slice(&length_determinant);
1125        let data = &combined;
1126        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1127        let new_length = decoder.decode_length().unwrap();
1128        assert_eq!(new_length, usize::MAX);
1129        // Test length > usize::MAX
1130        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap() + 1]; // first bit is 1, remaining tells length of the length
1131        let length_determinant: [u8; (usize::BITS / 8u32) as usize + 1] =
1132            [0xff; (usize::BITS / 8u32) as usize + 1];
1133        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize + 1] =
1134            [0x0; 1 + (usize::BITS / 8u32) as usize + 1];
1135        combined[..1].copy_from_slice(&length);
1136        combined[1..=(usize::BITS / 8u32 + 1) as usize].copy_from_slice(&length_determinant);
1137        let data = &combined;
1138        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1139        let new_length = decoder.decode_length();
1140        assert!(new_length.is_err());
1141    }
1142    #[test]
1143    fn test_integer_decode_with_constraints() {
1144        const CONSTRAINT_1: Constraints = constraints!(value_constraint!(0, 255));
1145        let data = &[0x01u8];
1146        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1147        let decoded_int: i32 = decoder
1148            .decode_integer_with_constraints(&CONSTRAINT_1)
1149            .unwrap();
1150        assert_eq!(decoded_int, 1);
1151
1152        let data = &[0xffu8];
1153        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1154        let decoded_int: i64 = decoder
1155            .decode_integer_with_constraints(&CONSTRAINT_1)
1156            .unwrap();
1157        assert_eq!(decoded_int, 255);
1158
1159        let data = &[0xffu8, 0xff];
1160        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1161        let decoded_int: BigInt = decoder
1162            .decode_integer_with_constraints(&CONSTRAINT_1)
1163            .unwrap();
1164        assert_eq!(decoded_int, 255.into());
1165
1166        let data = &[0x02u8, 0xff, 0x01];
1167        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1168        const CONSTRAINT_2: Constraints = Constraints::default();
1169        let decoded_int: BigInt = decoder
1170            .decode_integer_with_constraints(&CONSTRAINT_2)
1171            .unwrap();
1172        assert_eq!(decoded_int, BigInt::from(-255));
1173    }
1174}