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 & 0b0111_1111 == 0 || 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 {} from &[u8]", length
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() + is_extensible as usize;
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 - (is_extensible as usize) < RC {
456                result[i - is_extensible as usize] = 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    fn decode_any(&mut self) -> Result<Any, Self::Error> {
485        panic!("Not every type can be decoded as Any in OER.")
486    }
487
488    fn decode_bit_string(
489        &mut self,
490        _: Tag,
491        constraints: Constraints,
492    ) -> Result<BitString, Self::Error> {
493        self.parse_bit_string(&constraints)
494    }
495
496    /// One octet is used to present bool, false is 0x0 and true is value up to 0xff
497    /// In COER, only 0x0 and 0xff are valid values
498    fn decode_bool(&mut self, _: Tag) -> Result<bool, Self::Error> {
499        let byte = self.parse_one_byte()?;
500        Ok(match byte {
501            0 => false,
502            0xFF => true,
503            _ if self.options.encoding_rules.is_oer() => true,
504            _ => {
505                return Err(DecodeError::from_kind(
506                    DecodeErrorKind::InvalidBool { value: byte },
507                    self.codec(),
508                ))
509            }
510        })
511    }
512
513    fn decode_enumerated<E: Enumerated>(&mut self, _: Tag) -> Result<E, Self::Error> {
514        let byte = self.parse_one_byte()?;
515        if byte < 128 {
516            // Short form, use value directly as unsigned integer
517            E::from_discriminant(isize::from(byte))
518                .ok_or_else(|| DecodeError::discriminant_value_not_found(byte.into(), self.codec()))
519        } else {
520            // Long form, value as signed integer. Previous byte is length of the subsequent octets
521            let length = byte & 0x7fu8;
522            let discriminant: isize = self
523                .decode_integer_from_bytes(true, Some(length.into()))
524                .map_err(|e| {
525                    if matches!(&*e.kind, DecodeErrorKind::IntegerOverflow { .. }) {
526                        DecodeError::length_exceeds_platform_width(
527                            "Enumerated discriminant value too large for this platform."
528                                .to_string(),
529                            self.codec(),
530                        )
531                    } else {
532                        e
533                    }
534                })?;
535
536            if (0..128).contains(&discriminant) && self.options.encoding_rules.is_coer() {
537                return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
538                    msg: "Enumerated discriminant should have been encoded in short form."
539                        .to_string(),
540                }
541                .into());
542            }
543            E::from_discriminant(discriminant).ok_or_else(|| {
544                DecodeError::discriminant_value_not_found(discriminant, self.codec())
545            })
546        }
547    }
548
549    fn decode_integer<I: crate::types::IntegerType>(
550        &mut self,
551        _: Tag,
552        constraints: Constraints,
553    ) -> Result<I, Self::Error> {
554        self.decode_integer_with_constraints::<I>(&constraints)
555    }
556
557    fn decode_real<R: crate::types::RealType>(
558        &mut self,
559        _: Tag,
560        _: Constraints,
561    ) -> Result<R, Self::Error> {
562        let octets = self.extract_data_by_length(R::BYTE_WIDTH)?;
563        R::try_from_ieee754_bytes(octets)
564            .map_err(|_| DecodeError::from_kind(DecodeErrorKind::InvalidRealEncoding, self.codec()))
565    }
566
567    /// Null contains no data, so we just skip
568    fn decode_null(&mut self, _: Tag) -> Result<(), Self::Error> {
569        Ok(())
570    }
571
572    fn decode_object_identifier(&mut self, _: Tag) -> Result<ObjectIdentifier, Self::Error> {
573        let length = self.decode_length()?;
574        let ber_decoder = crate::ber::de::Decoder::new(&[], crate::ber::de::DecoderOptions::ber());
575        ber_decoder.decode_object_identifier_from_bytes(self.extract_data_by_length(length)?)
576    }
577
578    fn decode_sequence<const RC: usize, const EC: usize, D, DF: FnOnce() -> D, F>(
579        &mut self,
580        _: Tag,
581        default_initializer_fn: Option<DF>,
582        decode_fn: F,
583    ) -> Result<D, Self::Error>
584    where
585        D: Constructed<RC, EC>,
586        F: FnOnce(&mut Self::AnyDecoder<RC, EC>) -> Result<D, Self::Error>,
587    {
588        // If there are no fields then the sequence is empty
589        // Or if all fields are optional and default and there is no data
590        if D::FIELDS.is_empty()
591            || D::FIELDS.len() == D::FIELDS.number_of_optional_and_default_fields()
592                && self.input.is_empty()
593        {
594            if let Some(default_initializer_fn) = default_initializer_fn {
595                return Ok((default_initializer_fn)());
596            }
597            return Err(DecodeError::from_kind(
598                DecodeErrorKind::UnexpectedEmptyInput,
599                self.codec(),
600            ));
601        }
602        // ### PREAMBLE ###
603        let (bitmap, extensible_present) = self.parse_preamble::<RC, EC, D>()?;
604        // ### ENDS
605        let mut fields = ([None; RC], 0);
606        D::FIELDS
607            .optional_and_default_fields()
608            .zip(bitmap)
609            .enumerate()
610            .for_each(|(i, (field, is_present))| {
611                if is_present {
612                    fields.0[i] = Some(field);
613                } else {
614                    fields.0[i] = None;
615                }
616            });
617
618        let value = {
619            let mut sequence_decoder = Decoder::new(self.input, self.options);
620            sequence_decoder.extension_fields = D::EXTENDED_FIELDS;
621            sequence_decoder.extensions_present = extensible_present.then_some(None);
622            sequence_decoder.fields = fields;
623            let value = decode_fn(&mut sequence_decoder)?;
624
625            self.input = sequence_decoder.input;
626            value
627        };
628
629        Ok(value)
630    }
631
632    fn decode_sequence_of<D: Decode>(
633        &mut self,
634        _: Tag,
635        _: Constraints,
636    ) -> Result<Vec<D>, Self::Error> {
637        let length_of_quantity = self.decode_length()?;
638        let coer = self.options.encoding_rules.is_coer();
639        let length_bytes = self.extract_data_by_length(length_of_quantity)?;
640        if coer && length_bytes.first() == Some(&0) && length_bytes.len() > 1 {
641            return Err(CoerDecodeErrorKind::NotValidCanonicalEncoding {
642                msg: "Quantity value in 'sequence/set of' should not have leading zeroes in COER"
643                    .to_string(),
644            }
645            .into());
646        }
647        let length = usize::try_from_unsigned_bytes(length_bytes, self.codec())?;
648        let mut sequence_of: Vec<D> = Vec::with_capacity(length);
649        let mut decoder = Self::new(self.input, self.options);
650        for _ in 0..length {
651            let value = D::decode(&mut decoder)?;
652            self.input = decoder.input;
653            sequence_of.push(value);
654        }
655        Ok(sequence_of)
656    }
657
658    fn decode_set_of<D: Decode + Eq + core::hash::Hash>(
659        &mut self,
660        tag: Tag,
661        constraints: Constraints,
662    ) -> Result<SetOf<D>, Self::Error> {
663        self.decode_sequence_of(tag, constraints)
664            .map(|seq| SetOf::from_vec(seq))
665    }
666
667    fn decode_octet_string<'b, T: From<&'b [u8]> + From<Vec<u8>>>(
668        &'b mut self,
669        _: Tag,
670        constraints: Constraints,
671    ) -> Result<T, Self::Error> {
672        if let Some(size) = constraints.size() {
673            // Fixed size, only data is included
674            if size.constraint.is_fixed() && size.extensible.is_none() {
675                let data =
676                    self.extract_data_by_length(*size.constraint.as_start().ok_or_else(|| {
677                        DecodeError::size_constraint_not_satisfied(
678                            None,
679                            "Fixed size constraint should have value when decoding Octet String"
680                                .to_string(),
681                            self.codec(),
682                        )
683                    })?)?;
684                return Ok(T::from(data));
685            }
686        }
687        let length = self.decode_length()?;
688        let data = self.extract_data_by_length(length)?;
689        Ok(T::from(data))
690    }
691
692    fn decode_utf8_string(
693        &mut self,
694        tag: Tag,
695        constraints: Constraints,
696    ) -> Result<String, Self::Error> {
697        self.decode_octet_string(tag, constraints)
698            .and_then(|bytes| {
699                String::from_utf8(bytes).map_err(|e| {
700                    DecodeError::string_conversion_failed(
701                        Tag::UTF8_STRING,
702                        e.to_string(),
703                        self.codec(),
704                    )
705                })
706            })
707    }
708
709    fn decode_visible_string(
710        &mut self,
711        _: Tag,
712        constraints: Constraints,
713    ) -> Result<VisibleString, Self::Error> {
714        self.parse_known_multiplier_string(&constraints)
715    }
716
717    fn decode_general_string(
718        &mut self,
719        _: Tag,
720        constraints: Constraints,
721    ) -> Result<GeneralString, Self::Error> {
722        self.parse_known_multiplier_string(&constraints)
723    }
724
725    fn decode_graphic_string(
726        &mut self,
727        _: Tag,
728        constraints: Constraints,
729    ) -> Result<GraphicString, Self::Error> {
730        self.parse_known_multiplier_string(&constraints)
731    }
732
733    fn decode_ia5_string(
734        &mut self,
735        _: Tag,
736        constraints: Constraints,
737    ) -> Result<Ia5String, Self::Error> {
738        self.parse_known_multiplier_string(&constraints)
739    }
740
741    fn decode_printable_string(
742        &mut self,
743        _: Tag,
744        constraints: Constraints,
745    ) -> Result<PrintableString, Self::Error> {
746        self.parse_known_multiplier_string(&constraints)
747    }
748
749    fn decode_numeric_string(
750        &mut self,
751        _: Tag,
752        constraints: Constraints,
753    ) -> Result<NumericString, Self::Error> {
754        self.parse_known_multiplier_string(&constraints)
755    }
756
757    fn decode_teletex_string(
758        &mut self,
759        _: Tag,
760        constraints: Constraints,
761    ) -> Result<TeletexString, Self::Error> {
762        self.parse_known_multiplier_string(&constraints)
763    }
764
765    fn decode_bmp_string(
766        &mut self,
767        _: Tag,
768        constraints: Constraints,
769    ) -> Result<BmpString, Self::Error> {
770        self.parse_known_multiplier_string(&constraints)
771    }
772    fn decode_optional_with_explicit_prefix<D: Decode>(
773        &mut self,
774        tag: Tag,
775    ) -> Result<Option<D>, Self::Error> {
776        self.decode_optional_with_tag(tag)
777    }
778
779    fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error> {
780        // Whether we have a choice here
781        if D::TAG == Tag::EOC {
782            D::decode(self)
783        } else {
784            D::decode_with_tag(self, tag)
785        }
786    }
787
788    fn decode_utc_time(&mut self, tag: Tag) -> Result<UtcTime, Self::Error> {
789        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
790            .map_err(|_| {
791                DecodeError::string_conversion_failed(
792                    Tag::UTF8_STRING,
793                    "UTCTime should be UTF8 encoded.".to_string(),
794                    self.codec(),
795                )
796            })?;
797        crate::der::de::Decoder::parse_canonical_utc_time_string(&string)
798    }
799
800    fn decode_generalized_time(&mut self, tag: Tag) -> Result<GeneralizedTime, Self::Error> {
801        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
802            .map_err(|_| {
803                DecodeError::string_conversion_failed(
804                    Tag::UTF8_STRING,
805                    "GeneralizedTime should be UTF8 encoded".to_string(),
806                    self.codec(),
807                )
808            })?;
809        crate::der::de::Decoder::parse_canonical_generalized_time_string(string)
810    }
811
812    fn decode_date(&mut self, tag: Tag) -> Result<types::Date, Self::Error> {
813        let string = String::from_utf8(self.decode_octet_string(tag, Constraints::default())?)
814            .map_err(|_| {
815                DecodeError::string_conversion_failed(
816                    Tag::UTF8_STRING,
817                    "DATE should be UTF8 encoded".to_string(),
818                    self.codec(),
819                )
820            })?;
821        crate::der::de::Decoder::parse_date_string(&string)
822    }
823
824    fn decode_set<const RC: usize, const EC: usize, FIELDS, SET, D, F>(
825        &mut self,
826        _: Tag,
827        decode_fn: D,
828        field_fn: F,
829    ) -> Result<SET, Self::Error>
830    where
831        SET: Decode + Constructed<RC, EC>,
832        FIELDS: Decode,
833        D: Fn(&mut Self::AnyDecoder<RC, EC>, usize, Tag) -> Result<FIELDS, Self::Error>,
834        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>,
835    {
836        let (bitmap, extensible_present) = self.parse_preamble::<RC, EC, SET>()?;
837
838        let mut field_map: ([Option<Field>; RC], usize) = ([None; RC], 0);
839        for (i, (field, is_present)) in SET::FIELDS
840            .canonised()
841            .optional_and_default_fields()
842            .zip(bitmap)
843            .enumerate()
844        {
845            if is_present {
846                field_map.0[i] = Some(field);
847            } else {
848                field_map.0[i] = None;
849            }
850        }
851
852        let fields = {
853            let extended_fields_len = SET::EXTENDED_FIELDS.map_or(0, |fields| fields.len());
854            let mut fields = Vec::with_capacity(SET::FIELDS.len() + extended_fields_len);
855            let mut set_decoder = Decoder::new(self.input, self.options);
856            set_decoder.extension_fields = SET::EXTENDED_FIELDS;
857            set_decoder.extensions_present = extensible_present.then_some(None);
858            set_decoder.fields = field_map;
859
860            let mut opt_index = 0;
861            for field in SET::FIELDS.canonised().iter() {
862                if field.is_optional_or_default() {
863                    // Safe unwrap, we just created the field_map
864                    if field_map.0.get(opt_index).unwrap().is_some() {
865                        fields.push(decode_fn(&mut set_decoder, field.index, field.tag)?);
866                    }
867                    opt_index += 1;
868                } else {
869                    fields.push(decode_fn(&mut set_decoder, field.index, field.tag)?);
870                }
871            }
872            for (indice, field) in SET::EXTENDED_FIELDS
873                .iter()
874                .flat_map(Fields::iter)
875                .enumerate()
876            {
877                fields.push(decode_fn(
878                    &mut set_decoder,
879                    indice + SET::FIELDS.len(),
880                    field.tag,
881                )?);
882            }
883
884            self.input = set_decoder.input;
885            fields
886        };
887
888        field_fn(fields)
889    }
890
891    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
892    where
893        D: DecodeChoice,
894    {
895        let is_extensible = constraints.extensible();
896        let tag: Tag = self.parse_tag()?;
897        let is_root_extension = crate::types::TagTree::tag_contains(&tag, D::VARIANTS);
898        let is_extended_extension =
899            crate::types::TagTree::tag_contains(&tag, D::EXTENDED_VARIANTS.unwrap_or(&[]));
900        if is_root_extension {
901            D::from_tag(self, tag)
902        } else if is_extensible && is_extended_extension {
903            let options = self.options;
904            let length = self.decode_length()?;
905            let bytes = self.extract_data_by_length(length)?;
906            let mut decoder = Decoder::<0, 0>::new(bytes, options);
907            D::from_tag(&mut decoder, tag)
908        } else {
909            return Err(OerDecodeErrorKind::invalid_tag_variant_on_choice(
910                tag,
911                is_extensible,
912            ));
913        }
914    }
915
916    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
917        self.decode_optional_with_tag(D::TAG)
918    }
919
920    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error> {
921        let is_present = self.require_field(tag)?;
922        if is_present {
923            D::decode_with_tag(self, tag).map(Some)
924        } else {
925            Ok(None)
926        }
927    }
928
929    fn decode_optional_with_constraints<D: Decode>(
930        &mut self,
931        constraints: Constraints,
932    ) -> Result<Option<D>, Self::Error> {
933        let is_present = self.require_field(D::TAG)?;
934        if is_present {
935            D::decode_with_constraints(self, constraints).map(Some)
936        } else {
937            Ok(None)
938        }
939    }
940
941    fn decode_optional_with_tag_and_constraints<D: Decode>(
942        &mut self,
943        tag: Tag,
944        constraints: Constraints,
945    ) -> Result<Option<D>, Self::Error> {
946        let is_present = self.require_field(tag)?;
947        if is_present {
948            D::decode_with_tag_and_constraints(self, tag, constraints).map(Some)
949        } else {
950            Ok(None)
951        }
952    }
953    fn decode_extension_addition_with_explicit_tag_and_constraints<D>(
954        &mut self,
955        tag: Tag,
956        constraints: Constraints,
957    ) -> Result<Option<D>, Self::Error>
958    where
959        D: Decode,
960    {
961        self.decode_extension_addition_with_tag_and_constraints::<D>(tag, constraints)
962    }
963
964    fn decode_extension_addition_with_tag_and_constraints<D>(
965        &mut self,
966        _tag: Tag,
967        constraints: Constraints,
968    ) -> Result<Option<D>, Self::Error>
969    where
970        D: Decode,
971    {
972        if !self.parse_extension_header()? {
973            return Ok(None);
974        }
975
976        let extension_is_present = self.extension_is_present()?.is_some();
977
978        if !extension_is_present {
979            return Ok(None);
980        }
981
982        // Values of the extensions are only left, encoded as Open type
983        let options = self.options;
984        let bytes: Cow<[u8]> =
985            self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
986        let mut decoder = Decoder::<0, 0>::new(&bytes, options);
987        D::decode_with_constraints(&mut decoder, constraints).map(Some)
988    }
989
990    fn decode_extension_addition_group<
991        const RC: usize,
992        const EC: usize,
993        D: Decode + Constructed<RC, EC>,
994    >(
995        &mut self,
996    ) -> Result<Option<D>, Self::Error> {
997        if !self.parse_extension_header()? {
998            return Ok(None);
999        }
1000
1001        let extension_is_present = self.extension_is_present()?.is_some();
1002
1003        if !extension_is_present {
1004            return Ok(None);
1005        }
1006
1007        // Values of the extensions are only left, inner type encoded as Open type
1008        let options = self.options;
1009        let bytes: Cow<[u8]> =
1010            self.decode_octet_string(Tag::OCTET_STRING, Constraints::default())?;
1011        let mut decoder = Decoder::<0, 0>::new(&bytes, options);
1012        D::decode(&mut decoder).map(Some)
1013    }
1014}
1015
1016#[cfg(test)]
1017#[allow(clippy::assertions_on_constants)]
1018mod tests {
1019    use num_bigint::BigUint;
1020    // Max length for data type can be 2^1016, below presented as byte array of unsigned int
1021    const MAX_LENGTH: [u8; 127] = [0xff; 127];
1022    const MAX_LENGTH_LENGTH: usize = MAX_LENGTH.len();
1023    use super::*;
1024    use crate::macros::{constraints, value_constraint};
1025    use crate::types::constraints::Constraints;
1026    use bitvec::prelude::BitSlice;
1027    use num_bigint::BigInt;
1028
1029    #[test]
1030    fn test_decode_bool() {
1031        let decoded: bool = crate::oer::decode(&[0xffu8]).unwrap();
1032        assert!(decoded);
1033        let decoded: bool = crate::oer::decode(&[0u8]).unwrap();
1034        assert!(!decoded);
1035        let decoded: bool = crate::oer::decode(&[0xffu8, 0xff]).unwrap();
1036        assert!(decoded);
1037        let decoded: bool = crate::oer::decode(&[0x33u8, 0x0]).unwrap();
1038        assert!(decoded);
1039    }
1040
1041    #[test]
1042    fn test_decode_length_invalid() {
1043        let data = &[0xffu8];
1044        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1045        // Length determinant is > 127 without subsequent bytes
1046        assert!(decoder.decode_length().is_err());
1047        // Still missing some data
1048        let data = &[0xffu8, 0xff];
1049        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1050        // Length determinant is > 127 without subsequent bytes
1051        assert!(decoder.decode_length().is_err());
1052    }
1053
1054    #[test]
1055    fn test_decode_length_valid() {
1056        // Max length
1057        let max_length: BigUint = BigUint::from(2u8).pow(1016u32) - BigUint::from(1u8);
1058        assert_eq!(max_length.to_bytes_be(), MAX_LENGTH);
1059        assert_eq!(max_length.to_bytes_be().len(), MAX_LENGTH_LENGTH);
1060        // Unfortunately we cannot support lengths > 2^64 - 1 at the moment
1061        // Nor larger than BitSlice::<usize>::MAX_BITS
1062        assert!(max_length > usize::MAX.into());
1063        assert!(usize::MAX > BitSlice::<usize>::MAX_BITS);
1064
1065        // # SHORT FORM
1066        let data = &[0x01u8, 0xff];
1067        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1068        assert_eq!(decoder.decode_length().unwrap(), 1);
1069        let data = &[0x03u8, 0xff, 0xff, 0xfe];
1070        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1071        assert_eq!(decoder.decode_length().unwrap(), 3);
1072        // Max for short form
1073        let mut data: [u8; 0x80] = [0xffu8; 0x80];
1074        data[0] = 0x7f; // length determinant
1075        let data = &data;
1076        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1077        assert_eq!(decoder.decode_length().unwrap(), 127);
1078
1079        // # LONG FORM
1080        // Length of the length should be 2 octets, 0x7f - 0x82 = 2, length is 258 octets
1081        let length: [u8; 1] = [0x82u8]; // first bit is 1, remaining tells length of the length
1082        let length_determinant: [u8; 0x02] = [0x01u8, 0x02];
1083        let data: [u8; 258] = [0xffu8; 258];
1084        let mut combined: [u8; 261] = [0x0; 261];
1085        combined[..1].copy_from_slice(&length);
1086        combined[1..=2].copy_from_slice(&length_determinant);
1087        combined[3..].copy_from_slice(&data);
1088
1089        let data = &combined;
1090        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1091        assert_eq!(decoder.decode_length().unwrap(), 258usize);
1092    }
1093    #[test]
1094    fn test_long_form_length_decode() {
1095        let vc = &[
1096            0x81, 0x80, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1097            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1098            0xff, 0xff, 0xff, 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,
1106        ];
1107        let mut decoder = Decoder::<0, 0>::new(vc, DecoderOptions::oer());
1108        let number = BigInt::from(256).pow(127) - 1;
1109        let constraints = Constraints::default();
1110        let new_number: BigInt = decoder
1111            .decode_integer_with_constraints(&constraints)
1112            .unwrap();
1113        assert_eq!(new_number, number);
1114
1115        // Test maximum possible length
1116        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap()]; // first bit is 1, remaining tells length of the length
1117        let length_determinant: [u8; (usize::BITS / 8u32) as usize] =
1118            [0xff; (usize::BITS / 8u32) as usize];
1119        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize] =
1120            [0x0; 1 + (usize::BITS / 8u32) as usize];
1121        combined[..1].copy_from_slice(&length);
1122        combined[1..=(usize::BITS / 8u32) as usize].copy_from_slice(&length_determinant);
1123        let data = &combined;
1124        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1125        let new_length = decoder.decode_length().unwrap();
1126        assert_eq!(new_length, usize::MAX);
1127        // Test length > usize::MAX
1128        let length: [u8; 1] = [0x80u8 + u8::try_from(usize::BITS / 8u32).unwrap() + 1]; // first bit is 1, remaining tells length of the length
1129        let length_determinant: [u8; (usize::BITS / 8u32) as usize + 1] =
1130            [0xff; (usize::BITS / 8u32) as usize + 1];
1131        let mut combined: [u8; 1 + (usize::BITS / 8u32) as usize + 1] =
1132            [0x0; 1 + (usize::BITS / 8u32) as usize + 1];
1133        combined[..1].copy_from_slice(&length);
1134        combined[1..=(usize::BITS / 8u32 + 1) as usize].copy_from_slice(&length_determinant);
1135        let data = &combined;
1136        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1137        let new_length = decoder.decode_length();
1138        assert!(new_length.is_err());
1139    }
1140    #[test]
1141    fn test_integer_decode_with_constraints() {
1142        const CONSTRAINT_1: Constraints = constraints!(value_constraint!(0, 255));
1143        let data = &[0x01u8];
1144        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1145        let decoded_int: i32 = decoder
1146            .decode_integer_with_constraints(&CONSTRAINT_1)
1147            .unwrap();
1148        assert_eq!(decoded_int, 1);
1149
1150        let data = &[0xffu8];
1151        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1152        let decoded_int: i64 = decoder
1153            .decode_integer_with_constraints(&CONSTRAINT_1)
1154            .unwrap();
1155        assert_eq!(decoded_int, 255);
1156
1157        let data = &[0xffu8, 0xff];
1158        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1159        let decoded_int: BigInt = decoder
1160            .decode_integer_with_constraints(&CONSTRAINT_1)
1161            .unwrap();
1162        assert_eq!(decoded_int, 255.into());
1163
1164        let data = &[0x02u8, 0xff, 0x01];
1165        let mut decoder = Decoder::<0, 0>::new(data, DecoderOptions::oer());
1166        const CONSTRAINT_2: Constraints = Constraints::default();
1167        let decoded_int: BigInt = decoder
1168            .decode_integer_with_constraints(&CONSTRAINT_2)
1169            .unwrap();
1170        assert_eq!(decoded_int, BigInt::from(-255));
1171    }
1172}