rasn/
de.rs

1//! Generic ASN.1 decoding framework.
2
3use alloc::{boxed::Box, vec::Vec};
4
5use crate::error::DecodeError;
6use crate::types::{self, AsnType, Constraints, Enumerated, Tag};
7
8pub use nom::Needed;
9pub use rasn_derive::Decode;
10
11/// A **data type** that can decoded from any ASN.1 format.
12pub trait Decode: Sized + AsnType {
13    /// Decode this value from a given ASN.1 decoder.
14    ///
15    /// **Note for implementors** You typically do not need to implement this.
16    /// The default implementation will call `Decode::decode_with_tag` with
17    /// your types associated `AsnType::TAG`. You should only ever need to
18    /// implement this if you have a type that *cannot* be implicitly tagged,
19    /// such as a `CHOICE` type, which case you want to implement the decoding
20    /// in `decode`.
21    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
22        Self::decode_with_tag(decoder, Self::TAG)
23    }
24
25    /// Decode this value implicitly tagged with `tag` from a given ASN.1 decoder.
26    ///
27    /// **Note** For `CHOICE` and other types that cannot be implicitly tagged
28    /// this will **explicitly tag** the value, for all other types, it will
29    /// **implicitly** tag the value.
30    fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
31        Self::decode_with_tag_and_constraints(decoder, tag, Self::CONSTRAINTS)
32    }
33
34    fn decode_with_constraints<D: Decoder>(
35        decoder: &mut D,
36        constraints: Constraints,
37    ) -> Result<Self, D::Error> {
38        Self::decode_with_tag_and_constraints(decoder, Self::TAG, constraints)
39    }
40
41    fn decode_with_tag_and_constraints<D: Decoder>(
42        decoder: &mut D,
43        tag: Tag,
44        constraints: Constraints,
45    ) -> Result<Self, D::Error>;
46}
47
48/// A **data format** decode any ASN.1 data type.
49pub trait Decoder: Sized {
50    // TODO, when associated type defaults are stabilized, use this instead?
51    // type Error = crate::error::DecodeError;
52    type Error: Error + Into<crate::error::DecodeError> + From<crate::error::DecodeError>;
53
54    /// Returns codec variant of `Codec` that current decoder is decoding.
55    #[must_use]
56    fn codec(&self) -> crate::Codec;
57
58    /// Decode a unknown ASN.1 value identified by `tag` from the available input.
59    fn decode_any(&mut self) -> Result<types::Any, Self::Error>;
60    /// Decode a `BIT STRING` identified by `tag` from the available input.
61    fn decode_bit_string(
62        &mut self,
63        tag: Tag,
64        constraints: Constraints,
65    ) -> Result<types::BitString, Self::Error>;
66    /// Decode a `BOOL` identified by `tag` from the available input.
67    fn decode_bool(&mut self, tag: Tag) -> Result<bool, Self::Error>;
68    /// Decode an enumerated enum's discriminant identified by `tag` from the available input.
69    fn decode_enumerated<E: Enumerated>(&mut self, tag: Tag) -> Result<E, Self::Error>;
70    /// Decode a `INTEGER` identified by `tag` from the available input.
71    fn decode_integer<I: types::IntegerType>(
72        &mut self,
73        tag: Tag,
74        constraints: Constraints,
75    ) -> Result<I, Self::Error>;
76    /// Decode `NULL` identified by `tag` from the available input.
77    fn decode_null(&mut self, tag: Tag) -> Result<(), Self::Error>;
78    /// Decode a `OBJECT IDENTIFIER` identified by `tag` from the available input.
79    fn decode_object_identifier(
80        &mut self,
81        tag: Tag,
82    ) -> Result<types::ObjectIdentifier, Self::Error>;
83    /// Decode a `SEQUENCE` identified by `tag` from the available input. Returning
84    /// a new `Decoder` containing the sequence's contents to be decoded.
85    fn decode_sequence<D, DF, F>(
86        &mut self,
87        tag: Tag,
88        default_initializer_fn: Option<DF>,
89        decode_fn: F,
90    ) -> Result<D, Self::Error>
91    where
92        D: crate::types::Constructed,
93        DF: FnOnce() -> D,
94        F: FnOnce(&mut Self) -> Result<D, Self::Error>;
95    /// Decode a `SEQUENCE OF D` where `D: Decode` identified by `tag` from the available input.
96    fn decode_sequence_of<D: Decode>(
97        &mut self,
98        tag: Tag,
99        constraints: Constraints,
100    ) -> Result<Vec<D>, Self::Error>;
101    /// Decode a `SET OF D` where `D: Decode` identified by `tag` from the available input.
102    fn decode_set_of<D: Decode + Ord>(
103        &mut self,
104        tag: Tag,
105        constraints: Constraints,
106    ) -> Result<types::SetOf<D>, Self::Error>;
107    /// Decode a `OCTET STRING` identified by `tag` from the available input.
108    fn decode_octet_string(
109        &mut self,
110        tag: Tag,
111        constraints: Constraints,
112    ) -> Result<Vec<u8>, Self::Error>;
113    /// Decode a `UTF8 STRING` identified by `tag` from the available input.
114    fn decode_utf8_string(
115        &mut self,
116        tag: Tag,
117        constraints: Constraints,
118    ) -> Result<types::Utf8String, Self::Error>;
119
120    /// Decode a `VisibleString` identified by `tag` from the available input.
121    fn decode_visible_string(
122        &mut self,
123        tag: Tag,
124        constraints: Constraints,
125    ) -> Result<types::VisibleString, Self::Error>;
126
127    /// Decode a `Ia5String` identified by `tag` from the available input.
128    fn decode_general_string(
129        &mut self,
130        tag: Tag,
131        constraints: Constraints,
132    ) -> Result<types::GeneralString, Self::Error>;
133
134    /// Decode a `Ia5String` identified by `tag` from the available input.
135    fn decode_ia5_string(
136        &mut self,
137        tag: Tag,
138        constraints: Constraints,
139    ) -> Result<types::Ia5String, Self::Error>;
140
141    /// Decode a `PrintableString` identified by `tag` from the available input.
142    fn decode_printable_string(
143        &mut self,
144        tag: Tag,
145        constraints: Constraints,
146    ) -> Result<types::PrintableString, Self::Error>;
147
148    /// Decode a `NumericString` identified by `tag` from the available input.
149    fn decode_numeric_string(
150        &mut self,
151        tag: Tag,
152        constraints: Constraints,
153    ) -> Result<types::NumericString, Self::Error>;
154
155    /// Decode a `TeletexString` identified by `tag` from the available input.
156    fn decode_teletex_string(
157        &mut self,
158        tag: Tag,
159        constraints: Constraints,
160    ) -> Result<types::TeletexString, Self::Error>;
161
162    /// Decode a `BmpString` identified by `tag` from the available input.
163    fn decode_bmp_string(
164        &mut self,
165        tag: Tag,
166        constraints: Constraints,
167    ) -> Result<types::BmpString, Self::Error>;
168
169    /// Decode an ASN.1 value that has been explicitly prefixed with `tag` from the available input.
170    fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D, Self::Error>;
171    /// Decode a `UtcTime` identified by `tag` from the available input.
172    fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime, Self::Error>;
173    /// Decode a `GeneralizedTime` identified by `tag` from the available input.
174    fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime, Self::Error>;
175
176    /// Decode a `SET` identified by `tag` from the available input. Decoding
177    /// `SET`s works a little different than other methods, as you need to
178    /// provide two types `SET` and `FIELDS`, `SET` represents the complete type,
179    /// and `FIELDS` must represent a `CHOICE` with a variant for each field
180    /// from `SET`. As with `SET`s the field order is not guarenteed, so you'll
181    /// have map from `Vec<FIELDS>` to `SET` in `decode_operation`.
182    fn decode_set<FIELDS, SET, D, F>(
183        &mut self,
184        tag: Tag,
185        decode_fn: D,
186        field_fn: F,
187    ) -> Result<SET, Self::Error>
188    where
189        SET: Decode + crate::types::Constructed,
190        FIELDS: Decode,
191        D: Fn(&mut Self, usize, Tag) -> Result<FIELDS, Self::Error>,
192        F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>;
193
194    /// Decode an the optional value in a `SEQUENCE` or `SET`.
195    fn decode_choice<D>(&mut self, constraints: Constraints) -> Result<D, Self::Error>
196    where
197        D: crate::types::DecodeChoice;
198
199    /// Decode an the optional value in a `SEQUENCE` or `SET`.
200    fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error>;
201
202    /// Decode an the optional value in a `SEQUENCE` or `SET` with `tag`.
203    /// Passing the correct tag is required even when used with codecs where
204    /// the tag is not present.
205    fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error>;
206
207    /// Decode an the optional value in a `SEQUENCE` or `SET` with `constraints`.
208    fn decode_optional_with_constraints<D: Decode>(
209        &mut self,
210        constraints: Constraints,
211    ) -> Result<Option<D>, Self::Error>;
212
213    /// Decode an the optional value in a `SEQUENCE` or `SET` with `tag`
214    /// and `constraints`.
215    fn decode_optional_with_tag_and_constraints<D: Decode>(
216        &mut self,
217        tag: Tag,
218        constraints: Constraints,
219    ) -> Result<Option<D>, Self::Error>;
220
221    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET`.
222    fn decode_default<D: Decode, F: FnOnce() -> D>(
223        &mut self,
224        default_fn: F,
225    ) -> Result<D, Self::Error> {
226        self.decode_default_with_tag(D::TAG, default_fn)
227    }
228
229    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET` with `tag` and `default_fn`.
230    fn decode_default_with_tag<D: Decode, F: FnOnce() -> D>(
231        &mut self,
232        tag: Tag,
233        default_fn: F,
234    ) -> Result<D, Self::Error> {
235        Ok(self
236            .decode_optional_with_tag::<D>(tag)?
237            .unwrap_or_else(default_fn))
238    }
239
240    /// Decode a `DEFAULT` value with constraints in a `SEQUENCE` or `SET` with a given `default_fn`.
241    fn decode_default_with_constraints<D: Decode, F: FnOnce() -> D>(
242        &mut self,
243        default_fn: F,
244        constraints: Constraints,
245    ) -> Result<D, Self::Error> {
246        Ok(self
247            .decode_optional_with_constraints::<D>(constraints)?
248            .unwrap_or_else(default_fn))
249    }
250
251    /// Decode a `DEFAULT` value in a `SEQUENCE` or `SET` with `tag`, `constraints` and `default_fn`.
252    fn decode_default_with_tag_and_constraints<D: Decode, F: FnOnce() -> D>(
253        &mut self,
254        tag: Tag,
255        default_fn: F,
256        constraints: Constraints,
257    ) -> Result<D, Self::Error> {
258        Ok(self
259            .decode_optional_with_tag_and_constraints::<D>(tag, constraints)?
260            .unwrap_or_else(default_fn))
261    }
262
263    fn decode_extension_addition<D>(&mut self) -> Result<Option<D>, Self::Error>
264    where
265        D: Decode,
266    {
267        self.decode_extension_addition_with_constraints(Constraints::default())
268    }
269
270    /// Decode a `DEFAULT` value in a `SEQUENCE`'s or `SET`'s extension
271    fn decode_extension_addition_with_default<D: Decode, F: FnOnce() -> D>(
272        &mut self,
273        default_fn: F,
274    ) -> Result<D, Self::Error> {
275        self.decode_extension_addition_with_default_and_constraints(
276            default_fn,
277            Constraints::default(),
278        )
279    }
280
281    /// Decode a `DEFAULT` value with constraints in a `SEQUENCE`'s or `SET`'s extension
282    fn decode_extension_addition_with_default_and_constraints<D: Decode, F: FnOnce() -> D>(
283        &mut self,
284        default_fn: F,
285        constraints: Constraints,
286    ) -> Result<D, Self::Error> {
287        Ok(self
288            .decode_extension_addition_with_constraints::<D>(constraints)?
289            .unwrap_or_else(default_fn))
290    }
291
292    /// Decode an extension addition with constraints in a `SEQUENCE` or `SET`
293    fn decode_extension_addition_with_constraints<D>(
294        &mut self,
295        constraints: Constraints,
296    ) -> Result<Option<D>, Self::Error>
297    where
298        D: Decode;
299
300    fn decode_extension_addition_group<D: Decode + crate::types::Constructed>(
301        &mut self,
302    ) -> Result<Option<D>, Self::Error>;
303}
304
305/// A generic error that can occur while decoding ASN.1.
306/// Caller needs always to pass a `crate::Codec` variant to `Error` when implementing the decoder
307pub trait Error: core::fmt::Display {
308    /// Creates a new general error using `msg` when decoding ASN.1.
309    #[must_use]
310    fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self;
311    /// Creates a new error about needing more data to finish parsing.
312    #[must_use]
313    fn incomplete(needed: Needed, codec: crate::Codec) -> Self;
314    /// Creates a new error about exceeding the maximum allowed data for a type.
315    #[must_use]
316    fn exceeds_max_length(length: num_bigint::BigUint, codec: crate::Codec) -> Self;
317    /// Creates a new error about a missing field.
318    #[must_use]
319    fn missing_field(name: &'static str, codec: crate::Codec) -> Self;
320    /// Creates a new error about being unable to match any variant in a choice.
321    #[must_use]
322    fn no_valid_choice(name: &'static str, codec: crate::Codec) -> Self;
323    /// Creates a new error about being unable to decode a field in a compound
324    /// type, such as a set or sequence.
325    #[must_use]
326    fn field_error(name: &'static str, error: DecodeError, codec: crate::Codec) -> Self;
327    /// Creates a new error about finding a duplicate field.
328    #[must_use]
329    fn duplicate_field(name: &'static str, codec: crate::Codec) -> Self;
330    /// Create a new error about unknown field.
331    #[must_use]
332    fn unknown_field(index: usize, tag: Tag, codec: crate::Codec) -> Self;
333}
334
335impl Decode for () {
336    fn decode_with_tag_and_constraints<D: Decoder>(
337        decoder: &mut D,
338        tag: Tag,
339        _: Constraints,
340    ) -> Result<Self, D::Error> {
341        decoder.decode_null(tag)
342    }
343}
344
345impl<D: Decode> Decode for Option<D> {
346    fn decode<DE: Decoder>(decoder: &mut DE) -> Result<Self, DE::Error> {
347        decoder.decode_optional()
348    }
349
350    fn decode_with_tag<DE: Decoder>(decoder: &mut DE, tag: Tag) -> Result<Self, DE::Error> {
351        decoder.decode_optional_with_tag(tag)
352    }
353
354    fn decode_with_constraints<DE: Decoder>(
355        decoder: &mut DE,
356        constraints: Constraints,
357    ) -> Result<Self, DE::Error> {
358        decoder.decode_optional_with_constraints(constraints)
359    }
360
361    fn decode_with_tag_and_constraints<DE: Decoder>(
362        decoder: &mut DE,
363        tag: Tag,
364        constraints: Constraints,
365    ) -> Result<Self, DE::Error> {
366        decoder.decode_optional_with_tag_and_constraints(tag, constraints)
367    }
368}
369
370impl Decode for bool {
371    fn decode_with_tag_and_constraints<D: Decoder>(
372        decoder: &mut D,
373        tag: Tag,
374        _: Constraints,
375    ) -> Result<Self, D::Error> {
376        decoder.decode_bool(tag)
377    }
378}
379
380macro_rules! impl_integers {
381    ($($int:ty),+ $(,)?) => {
382        $(
383        impl Decode for $int {
384            fn decode_with_tag_and_constraints<D: Decoder>(decoder: &mut D, tag: Tag, constraints: Constraints) -> Result<Self, D::Error> {
385                decoder.decode_integer::<$int>(tag, constraints)
386            }
387        }
388        )+
389    }
390}
391
392impl_integers! {
393    i8,
394    i16,
395    i32,
396    i64,
397    isize,
398    u8,
399    u16,
400    u32,
401    u64,
402    usize,
403}
404
405impl<const START: i128, const END: i128> Decode for types::ConstrainedInteger<START, END> {
406    fn decode_with_tag_and_constraints<D: Decoder>(
407        decoder: &mut D,
408        tag: Tag,
409        constraints: Constraints,
410    ) -> Result<Self, D::Error> {
411        decoder
412            .decode_integer::<types::Integer>(tag, constraints)
413            .map(Self)
414    }
415}
416
417impl Decode for types::Integer {
418    fn decode_with_tag_and_constraints<D: Decoder>(
419        decoder: &mut D,
420        tag: Tag,
421        constraints: Constraints,
422    ) -> Result<Self, D::Error> {
423        decoder.decode_integer(tag, constraints)
424    }
425}
426
427impl<T: Decode> Decode for Box<T> {
428    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
429        T::decode(decoder).map(Box::new)
430    }
431
432    fn decode_with_tag<D: Decoder>(decoder: &mut D, tag: Tag) -> Result<Self, D::Error> {
433        T::decode_with_tag(decoder, tag).map(Box::new)
434    }
435
436    fn decode_with_constraints<DE: Decoder>(
437        decoder: &mut DE,
438        constraints: Constraints,
439    ) -> Result<Self, DE::Error> {
440        T::decode_with_constraints(decoder, constraints).map(Box::new)
441    }
442
443    fn decode_with_tag_and_constraints<DE: Decoder>(
444        decoder: &mut DE,
445        tag: Tag,
446        constraints: Constraints,
447    ) -> Result<Self, DE::Error> {
448        T::decode_with_tag_and_constraints(decoder, tag, constraints).map(Box::new)
449    }
450}
451
452impl Decode for types::OctetString {
453    fn decode_with_tag_and_constraints<D: Decoder>(
454        decoder: &mut D,
455        tag: Tag,
456        constraints: Constraints,
457    ) -> Result<Self, D::Error> {
458        decoder
459            .decode_octet_string(tag, constraints)
460            .map(Self::from)
461    }
462}
463
464impl Decode for types::ObjectIdentifier {
465    fn decode_with_tag_and_constraints<D: Decoder>(
466        decoder: &mut D,
467        tag: Tag,
468        _: Constraints,
469    ) -> Result<Self, D::Error> {
470        decoder.decode_object_identifier(tag)
471    }
472}
473
474impl Decode for types::Utf8String {
475    fn decode_with_tag_and_constraints<D: Decoder>(
476        decoder: &mut D,
477        tag: Tag,
478        constraints: Constraints,
479    ) -> Result<Self, D::Error> {
480        decoder.decode_utf8_string(tag, constraints)
481    }
482}
483
484impl Decode for types::UtcTime {
485    fn decode_with_tag_and_constraints<D: Decoder>(
486        decoder: &mut D,
487        tag: Tag,
488        _: Constraints,
489    ) -> Result<Self, D::Error> {
490        decoder.decode_utc_time(tag)
491    }
492}
493
494impl Decode for types::GeneralizedTime {
495    fn decode_with_tag_and_constraints<D: Decoder>(
496        decoder: &mut D,
497        tag: Tag,
498        _: Constraints,
499    ) -> Result<Self, D::Error> {
500        decoder.decode_generalized_time(tag)
501    }
502}
503
504impl Decode for types::Any {
505    fn decode_with_tag_and_constraints<D: Decoder>(
506        decoder: &mut D,
507        _: Tag,
508        _: Constraints,
509    ) -> Result<Self, D::Error> {
510        decoder.decode_any()
511    }
512}
513
514impl<T: Decode> Decode for alloc::vec::Vec<T> {
515    fn decode_with_tag_and_constraints<D: Decoder>(
516        decoder: &mut D,
517        tag: Tag,
518        constraints: Constraints,
519    ) -> Result<Self, D::Error> {
520        decoder.decode_sequence_of(tag, constraints)
521    }
522}
523
524impl<T: Decode + Ord> Decode for alloc::collections::BTreeSet<T> {
525    fn decode_with_tag_and_constraints<D: Decoder>(
526        decoder: &mut D,
527        tag: Tag,
528        constraints: Constraints,
529    ) -> Result<Self, D::Error> {
530        decoder.decode_set_of(tag, constraints)
531    }
532}
533
534impl<T: Decode + Default, const N: usize> Decode for [T; N] {
535    fn decode_with_tag_and_constraints<D: Decoder>(
536        decoder: &mut D,
537        tag: Tag,
538        constraints: Constraints,
539    ) -> Result<Self, D::Error> {
540        let sequence = decoder.decode_sequence_of(tag, constraints)?;
541        sequence.try_into().map_err(|seq: Vec<_>| {
542            D::Error::from(DecodeError::incorrect_item_number_in_sequence(
543                N,
544                seq.len(),
545                decoder.codec(),
546            ))
547        })
548    }
549}
550
551impl<T: AsnType, V: Decode> Decode for types::Implicit<T, V> {
552    fn decode_with_tag_and_constraints<D: Decoder>(
553        decoder: &mut D,
554        tag: Tag,
555        constraints: Constraints,
556    ) -> Result<Self, D::Error> {
557        Ok(Self::new(V::decode_with_tag_and_constraints(
558            decoder,
559            tag,
560            constraints,
561        )?))
562    }
563}
564
565impl<T: AsnType, V: Decode> Decode for types::Explicit<T, V> {
566    fn decode_with_tag_and_constraints<D: Decoder>(
567        decoder: &mut D,
568        tag: Tag,
569        _: Constraints,
570    ) -> Result<Self, D::Error> {
571        Ok(Self::new(decoder.decode_explicit_prefix(tag)?))
572    }
573}