der/reader.rs
1//! Reader trait.
2
3#[cfg(feature = "pem")]
4pub(crate) mod pem;
5pub(crate) mod slice;
6
7mod position;
8
9use crate::{
10 Decode, DecodeValue, Encode, EncodingRules, Error, ErrorKind, FixedTag, Header, Length, Tag,
11 TagMode, TagNumber, asn1::ContextSpecific,
12};
13
14#[cfg(feature = "alloc")]
15use alloc::vec::Vec;
16
17#[cfg(feature = "ber")]
18use crate::length::indefinite::read_eoc;
19
20/// Maximum nesting depth for readers and BER indefinite-length scanning.
21pub(crate) const MAX_NESTING_DEPTH: usize = 64;
22
23/// Reader trait which reads DER-encoded input.
24pub trait Reader<'r>: Clone {
25 /// Does this reader support the `read_slice` method? (i.e. can it borrow from his input?)
26 const CAN_READ_SLICE: bool;
27
28 /// Get the [`EncodingRules`] which should be applied when decoding the input.
29 fn encoding_rules(&self) -> EncodingRules;
30
31 /// Get the length of the input.
32 fn input_len(&self) -> Length;
33
34 /// Get the position within the buffer.
35 fn position(&self) -> Length;
36
37 /// Read nested data of the given length.
38 ///
39 /// # Errors
40 /// If `f` returns an error.
41 fn read_nested<T, F, E>(&mut self, len: Length, f: F) -> Result<T, E>
42 where
43 E: From<Error>,
44 F: FnOnce(&mut Self) -> Result<T, E>;
45
46 /// Attempt to read data borrowed directly from the input as a slice,
47 /// updating the internal cursor position.
48 ///
49 /// # Errors
50 /// - `Err(ErrorKind::Incomplete)` if there is not enough data
51 /// - `Err(ErrorKind::Reader)` if the reader can't borrow from the input
52 fn read_slice(&mut self, len: Length) -> Result<&'r [u8], Error>;
53
54 /// Attempt to decode an ASN.1 `CONTEXT-SPECIFIC` field with the
55 /// provided [`TagNumber`].
56 ///
57 /// # Errors
58 /// If a decoding error occurred.
59 fn context_specific<T>(
60 &mut self,
61 tag_number: TagNumber,
62 tag_mode: TagMode,
63 ) -> Result<Option<T>, T::Error>
64 where
65 T: DecodeValue<'r> + FixedTag + 'r,
66 {
67 Ok(match tag_mode {
68 TagMode::Explicit => ContextSpecific::<T>::decode_explicit(self, tag_number)?,
69 TagMode::Implicit => ContextSpecific::<T>::decode_implicit(self, tag_number)?,
70 }
71 .map(|field| field.value))
72 }
73
74 /// Decode a value which impls the [`Decode`] trait.
75 ///
76 /// # Errors
77 /// Returns `T::Error` if a decoding error occurred.
78 fn decode<T: Decode<'r>>(&mut self) -> Result<T, T::Error> {
79 T::decode(self)
80 }
81
82 /// Drain the given amount of data from the reader, discarding it.
83 ///
84 /// # Errors
85 /// If an error occurred reading the given `amount` of data.
86 fn drain(&mut self, mut amount: Length) -> Result<(), Error> {
87 const BUFFER_SIZE: usize = 16;
88 let mut buffer = [0u8; BUFFER_SIZE];
89
90 while amount > Length::ZERO {
91 let amount_usize = usize::try_from(amount)?;
92
93 let nbytes_drained = if amount_usize >= BUFFER_SIZE {
94 self.read_into(&mut buffer)?;
95 Length::try_from(BUFFER_SIZE)?
96 } else {
97 self.read_into(&mut buffer[..amount_usize])?;
98 amount
99 };
100
101 amount = (amount - nbytes_drained)?;
102 }
103
104 Ok(())
105 }
106
107 /// Return an error with the given [`ErrorKind`], annotating it with
108 /// context about where the error occurred.
109 fn error(&mut self, kind: ErrorKind) -> Error {
110 kind.at(self.position())
111 }
112
113 /// Finish decoding, returning `Ok(())` if there is no
114 /// remaining data, or an error otherwise.
115 ///
116 /// # Errors
117 /// If there is trailing data remaining in the reader.
118 fn finish(self) -> Result<(), Error> {
119 if !self.is_finished() {
120 Err(ErrorKind::TrailingData {
121 decoded: self.position(),
122 remaining: self.remaining_len(),
123 }
124 .at(self.position()))
125 } else {
126 Ok(())
127 }
128 }
129
130 /// Have we read all input data?
131 fn is_finished(&self) -> bool {
132 self.remaining_len().is_zero()
133 }
134
135 /// Offset within the original input stream.
136 ///
137 /// This is used for error reporting, and doesn't need to be overridden
138 /// by any reader implementations (except for the built-in `NestedReader`,
139 /// which consumes nested input messages)
140 fn offset(&self) -> Length {
141 self.position()
142 }
143
144 /// Peek at the next byte of input without modifying the cursor.
145 fn peek_byte(&self) -> Option<u8> {
146 let mut byte = [0];
147 self.peek_into(&mut byte).ok().map(|_| byte[0])
148 }
149
150 /// Peek at the decoded data without updating the internal state, writing into the provided
151 /// output buffer. Attempts to fill the entire buffer.
152 ///
153 /// # Errors
154 /// If there is not enough data.
155 fn peek_into(&self, buf: &mut [u8]) -> Result<(), Error> {
156 let mut reader = self.clone();
157 reader.read_into(buf)?;
158 Ok(())
159 }
160
161 /// Peek forward in the input data, attempting to decode a [`Header`] from
162 /// the data at the current position in the decoder.
163 ///
164 /// Does not modify the decoder's state.
165 ///
166 /// # Errors
167 /// If [`Header::peek`] returns an error.
168 #[deprecated(since = "0.8.0", note = "use `Header::peek` instead")]
169 fn peek_header(&self) -> Result<Header, Error> {
170 Header::peek(self)
171 }
172
173 /// Peek at the next tag in the reader.
174 ///
175 /// # Errors
176 /// If [`Tag::peek`] returns an error.
177 #[deprecated(since = "0.8.0", note = "use `Tag::peek` instead")]
178 fn peek_tag(&self) -> Result<Tag, Error> {
179 Tag::peek(self)
180 }
181
182 /// Read a single byte.
183 ///
184 /// # Errors
185 /// If the byte could not be read.
186 fn read_byte(&mut self) -> Result<u8, Error> {
187 let mut buf = [0];
188 self.read_into(&mut buf)?;
189 Ok(buf[0])
190 }
191
192 /// Attempt to read input data, writing it into the provided buffer, and
193 /// returning a slice on success.
194 ///
195 /// # Errors
196 /// - `ErrorKind::Incomplete` if there is not enough data
197 fn read_into<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o [u8], Error> {
198 let input = self.read_slice(buf.len().try_into()?)?;
199 buf.copy_from_slice(input);
200 Ok(buf)
201 }
202
203 /// Read a byte vector of the given length.
204 ///
205 /// # Errors
206 /// If a read error occurred.
207 #[cfg(feature = "alloc")]
208 fn read_vec(&mut self, len: Length) -> Result<Vec<u8>, Error> {
209 let mut bytes = vec![0u8; usize::try_from(len)?];
210 self.read_into(&mut bytes)?;
211 Ok(bytes)
212 }
213
214 /// Get the number of bytes still remaining in the buffer.
215 fn remaining_len(&self) -> Length {
216 debug_assert!(self.position() <= self.input_len());
217 self.input_len().saturating_sub(self.position())
218 }
219
220 /// Read an ASN.1 `SEQUENCE`, creating a nested [`Reader`] for the body and
221 /// calling the provided closure with it.
222 ///
223 /// # Errors
224 /// If `f` returns an error, or if a decoding error occurred.
225 fn sequence<F, T, E>(&mut self, f: F) -> Result<T, E>
226 where
227 F: FnOnce(&mut Self) -> Result<T, E>,
228 E: From<Error>,
229 {
230 let header = Header::decode(self)?;
231 header.tag().assert_eq(Tag::Sequence)?;
232 read_value(self, header, |r, _| f(r))
233 }
234
235 /// Obtain a slice of bytes containing a complete TLV production suitable for parsing later.
236 ///
237 /// # Errors
238 /// If a decoding error occurred, or a length calculation overflowed.
239 fn tlv_bytes(&mut self) -> Result<&'r [u8], Error> {
240 let header = Header::peek(self)?;
241 let header_len = header.encoded_len()?;
242 self.read_slice((header_len + header.length())?)
243 }
244}
245
246/// Read a value (i.e. the "V" part of a "TLV" field) using the provided header.
247///
248/// This calls the provided function `f` with a nested reader created using
249/// [`Reader::read_nested`].
250pub(crate) fn read_value<'r, R, T, F, E>(reader: &mut R, header: Header, f: F) -> Result<T, E>
251where
252 R: Reader<'r>,
253 E: From<Error>,
254 F: FnOnce(&mut R, Header) -> Result<T, E>,
255{
256 #[cfg(feature = "ber")]
257 let header = header.with_length(header.length().sans_eoc());
258
259 let ret = reader.read_nested(header.length(), |r| f(r, header))?;
260
261 // Consume EOC marker if the length is indefinite.
262 #[cfg(feature = "ber")]
263 if header.length().is_indefinite() {
264 read_eoc(reader)?;
265 }
266
267 Ok(ret)
268}