1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::{
asn1::*, ByteSlice, Choice, Decodable, DecodeValue, Error, ErrorKind, FixedTag, Header, Length,
Result, Tag, TagMode, TagNumber,
};
#[derive(Clone, Debug)]
pub struct Decoder<'a> {
bytes: Option<ByteSlice<'a>>,
position: Length,
}
impl<'a> Decoder<'a> {
pub fn new(bytes: &'a [u8]) -> Result<Self> {
Ok(Self {
bytes: Some(ByteSlice::new(bytes)?),
position: Length::ZERO,
})
}
pub fn decode<T: Decodable<'a>>(&mut self) -> Result<T> {
if self.is_failed() {
return Err(self.error(ErrorKind::Failed));
}
T::decode(self).map_err(|e| {
self.bytes.take();
e.nested(self.position)
})
}
pub fn error(&mut self, kind: ErrorKind) -> Error {
self.bytes.take();
kind.at(self.position)
}
pub fn value_error(&mut self, tag: Tag) -> Error {
self.error(tag.value_error().kind())
}
pub fn is_failed(&self) -> bool {
self.bytes.is_none()
}
pub fn position(&self) -> Length {
self.position
}
pub fn peek_byte(&self) -> Option<u8> {
self.remaining()
.ok()
.and_then(|bytes| bytes.get(0).cloned())
}
pub fn peek_tag(&self) -> Result<Tag> {
match self.peek_byte() {
Some(byte) => byte.try_into(),
None => {
let actual_len = self.input_len()?;
let expected_len = (actual_len + Length::ONE)?;
Err(ErrorKind::Incomplete {
expected_len,
actual_len,
}
.into())
}
}
}
pub fn peek_header(&self) -> Result<Header> {
Header::decode(&mut self.clone())
}
pub fn finish<T>(self, value: T) -> Result<T> {
if self.is_failed() {
Err(ErrorKind::Failed.at(self.position))
} else if !self.is_finished() {
Err(ErrorKind::TrailingData {
decoded: self.position,
remaining: self.remaining_len()?,
}
.at(self.position))
} else {
Ok(value)
}
}
pub fn is_finished(&self) -> bool {
self.remaining().map(|rem| rem.is_empty()).unwrap_or(false)
}
pub fn any(&mut self) -> Result<Any<'a>> {
self.decode()
}
pub fn any_optional(&mut self) -> Result<Option<Any<'a>>> {
self.decode()
}
pub fn int8(&mut self) -> Result<i8> {
self.decode()
}
pub fn int16(&mut self) -> Result<i16> {
self.decode()
}
pub fn uint8(&mut self) -> Result<u8> {
self.decode()
}
pub fn uint16(&mut self) -> Result<u16> {
self.decode()
}
#[cfg(feature = "bigint")]
#[cfg_attr(docsrs, doc(cfg(feature = "bigint")))]
pub fn uint_bytes(&mut self) -> Result<UIntBytes<'a>> {
self.decode()
}
pub fn bit_string(&mut self) -> Result<BitString<'a>> {
self.decode()
}
pub fn context_specific<T>(
&mut self,
tag_number: TagNumber,
tag_mode: TagMode,
) -> Result<Option<T>>
where
T: DecodeValue<'a> + FixedTag,
{
Ok(match tag_mode {
TagMode::Explicit => ContextSpecific::<T>::decode_explicit(self, tag_number)?,
TagMode::Implicit => ContextSpecific::<T>::decode_implicit(self, tag_number)?,
}
.map(|field| field.value))
}
pub fn generalized_time(&mut self) -> Result<GeneralizedTime> {
self.decode()
}
pub fn ia5_string(&mut self) -> Result<Ia5String<'a>> {
self.decode()
}
pub fn null(&mut self) -> Result<Null> {
self.decode()
}
pub fn octet_string(&mut self) -> Result<OctetString<'a>> {
self.decode()
}
#[cfg(feature = "oid")]
#[cfg_attr(docsrs, doc(cfg(feature = "oid")))]
pub fn oid(&mut self) -> Result<ObjectIdentifier> {
self.decode()
}
pub fn optional<T: Choice<'a>>(&mut self) -> Result<Option<T>> {
self.decode()
}
pub fn printable_string(&mut self) -> Result<PrintableString<'a>> {
self.decode()
}
pub fn utc_time(&mut self) -> Result<UtcTime> {
self.decode()
}
pub fn utf8_string(&mut self) -> Result<Utf8String<'a>> {
self.decode()
}
pub fn sequence<F, T>(&mut self, f: F) -> Result<T>
where
F: FnOnce(&mut Decoder<'a>) -> Result<T>,
{
Tag::try_from(self.byte()?)?.assert_eq(Tag::Sequence)?;
let len = Length::decode(self)?;
self.decode_nested(len, f)
}
pub(crate) fn byte(&mut self) -> Result<u8> {
match self.bytes(1u8)? {
[byte] => Ok(*byte),
_ => {
let actual_len = self.input_len()?;
let expected_len = (actual_len + Length::ONE)?;
Err(self.error(ErrorKind::Incomplete {
expected_len,
actual_len,
}))
}
}
}
pub(crate) fn bytes(&mut self, len: impl TryInto<Length>) -> Result<&'a [u8]> {
if self.is_failed() {
return Err(self.error(ErrorKind::Failed));
}
let len = len
.try_into()
.map_err(|_| self.error(ErrorKind::Overflow))?;
match self.remaining()?.get(..len.try_into()?) {
Some(result) => {
self.position = (self.position + len)?;
Ok(result)
}
None => {
let actual_len = self.input_len()?;
let expected_len = (actual_len + len)?;
Err(self.error(ErrorKind::Incomplete {
expected_len,
actual_len,
}))
}
}
}
pub(crate) fn input_len(&self) -> Result<Length> {
Ok(self.bytes.ok_or(ErrorKind::Failed)?.len())
}
pub(crate) fn remaining_len(&self) -> Result<Length> {
self.remaining()?.len().try_into()
}
fn decode_nested<F, T>(&mut self, length: Length, f: F) -> Result<T>
where
F: FnOnce(&mut Self) -> Result<T>,
{
let start_pos = self.position();
let end_pos = (start_pos + length)?;
let bytes = match self.bytes {
Some(slice) => {
slice
.as_bytes()
.get(..end_pos.try_into()?)
.ok_or(ErrorKind::Incomplete {
expected_len: end_pos,
actual_len: self.input_len()?,
})?
}
None => return Err(self.error(ErrorKind::Failed)),
};
let mut nested_decoder = Self {
bytes: Some(ByteSlice::new(bytes)?),
position: start_pos,
};
self.position = end_pos;
let result = f(&mut nested_decoder)?;
nested_decoder.finish(result)
}
fn remaining(&self) -> Result<&'a [u8]> {
let pos = usize::try_from(self.position)?;
match self.bytes.and_then(|slice| slice.as_bytes().get(pos..)) {
Some(result) => Ok(result),
None => {
let actual_len = self.input_len()?;
let expected_len = (actual_len + Length::ONE)?;
Err(ErrorKind::Incomplete {
expected_len,
actual_len,
}
.at(self.position))
}
}
}
}
#[cfg(test)]
mod tests {
use super::Decoder;
use crate::{Decodable, ErrorKind, Length, Tag};
use hex_literal::hex;
const EXAMPLE_MSG: &[u8] = &hex!("02012A00");
#[test]
fn empty_message() {
let mut decoder = Decoder::new(&[]).unwrap();
let err = bool::decode(&mut decoder).err().unwrap();
assert_eq!(Some(Length::ZERO), err.position());
match err.kind() {
ErrorKind::Incomplete {
expected_len,
actual_len,
} => {
assert_eq!(expected_len, 1u8.into());
assert_eq!(actual_len, 0u8.into());
}
other => panic!("unexpected error kind: {:?}", other),
}
}
#[test]
fn invalid_field_length() {
let mut decoder = Decoder::new(&EXAMPLE_MSG[..2]).unwrap();
let err = i8::decode(&mut decoder).err().unwrap();
assert_eq!(Some(Length::from(2u8)), err.position());
match err.kind() {
ErrorKind::Incomplete {
expected_len,
actual_len,
} => {
assert_eq!(expected_len, 3u8.into());
assert_eq!(actual_len, 2u8.into());
}
other => panic!("unexpected error kind: {:?}", other),
}
}
#[test]
fn trailing_data() {
let mut decoder = Decoder::new(EXAMPLE_MSG).unwrap();
let x = decoder.decode().unwrap();
assert_eq!(42i8, x);
let err = decoder.finish(x).err().unwrap();
assert_eq!(Some(Length::from(3u8)), err.position());
assert_eq!(
ErrorKind::TrailingData {
decoded: 3u8.into(),
remaining: 1u8.into()
},
err.kind()
);
}
#[test]
fn peek_tag() {
let decoder = Decoder::new(EXAMPLE_MSG).unwrap();
assert_eq!(decoder.position(), Length::ZERO);
assert_eq!(decoder.peek_tag().unwrap(), Tag::Integer);
assert_eq!(decoder.position(), Length::ZERO); }
#[test]
fn peek_header() {
let decoder = Decoder::new(EXAMPLE_MSG).unwrap();
assert_eq!(decoder.position(), Length::ZERO);
let header = decoder.peek_header().unwrap();
assert_eq!(header.tag, Tag::Integer);
assert_eq!(header.length, Length::ONE);
assert_eq!(decoder.position(), Length::ZERO); }
}