Coverage Report

Created: 2025-12-28 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/yasna-0.5.2/src/reader/mod.rs
Line
Count
Source
1
// Copyright 2016 Masaki Hara
2
// Copyright 2017,2019 Fortanix, Inc.
3
//
4
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7
// option. This file may not be copied, modified, or distributed
8
// except according to those terms.
9
10
#![allow(missing_docs)]
11
12
use alloc::vec::Vec;
13
use alloc::string::String;
14
use alloc::borrow::ToOwned;
15
16
mod error;
17
18
#[cfg(feature = "num-bigint")]
19
use num_bigint::{BigInt,BigUint,Sign};
20
#[cfg(feature = "bit-vec")]
21
use bit_vec::BitVec;
22
23
use super::{PCBit,Tag,TAG_CLASSES};
24
use super::tags::{TAG_EOC,TAG_BOOLEAN,TAG_INTEGER,TAG_OCTETSTRING};
25
use super::tags::{TAG_NULL,TAG_OID,TAG_UTF8STRING,TAG_SEQUENCE,TAG_SET,TAG_ENUM};
26
use super::tags::{TAG_NUMERICSTRING,TAG_PRINTABLESTRING,TAG_VISIBLESTRING,TAG_IA5STRING,TAG_BMPSTRING};
27
use super::models::{ObjectIdentifier,TaggedDerValue};
28
#[cfg(feature = "time")]
29
use super::models::{UTCTime,GeneralizedTime};
30
pub use self::error::*;
31
32
/// Parses DER/BER-encoded data.
33
///
34
/// [`parse_ber`] and [`parse_der`] are shorthands
35
/// for this function.
36
0
pub fn parse_ber_general<'a, T, F>(buf: &'a [u8], mode: BERMode, callback: F)
37
0
        -> ASN1Result<T>
38
0
        where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
39
0
    let mut reader_impl = BERReaderImpl::new(buf, mode);
40
    let result;
41
    {
42
0
        result = callback(BERReader::new(&mut reader_impl))?;
43
    }
44
0
    reader_impl.end_of_buf()?;
45
0
    return Ok(result);
46
0
}
47
48
/// Parses BER-encoded data.
49
///
50
/// This function uses the loan pattern: `callback` is called back with
51
/// a [`BERReader`], from which the ASN.1 value is read.
52
///
53
/// If you want to accept only DER-encoded data, use [`parse_der`].
54
///
55
/// # Examples
56
///
57
/// ```
58
/// use yasna;
59
/// let data = &[48, 128, 2, 1, 10, 1, 1, 255, 0, 0];
60
/// let asn = yasna::parse_ber(data, |reader| {
61
///     reader.read_sequence(|reader| {
62
///         let i = reader.next().read_i64()?;
63
///         let b = reader.next().read_bool()?;
64
///         return Ok((i, b));
65
///     })
66
/// }).unwrap();
67
/// println!("{:?} = [48, 128, 2, 1, 10, 1, 1, 255, 0, 0]", asn);
68
/// ```
69
0
pub fn parse_ber<'a, T, F>(buf: &'a [u8], callback: F)
70
0
        -> ASN1Result<T>
71
0
        where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
72
0
    parse_ber_general(buf, BERMode::Ber, callback)
73
0
}
74
75
/// Parses DER-encoded data.
76
///
77
/// This function uses the loan pattern: `callback` is called back with
78
/// a [`BERReader`], from which the ASN.1 value is read.
79
///
80
/// If you want to parse BER-encoded data in general,
81
/// use [`parse_ber`].
82
///
83
/// # Examples
84
///
85
/// ```
86
/// use yasna;
87
/// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
88
/// let asn = yasna::parse_der(data, |reader| {
89
///     reader.read_sequence(|reader| {
90
///         let i = reader.next().read_i64()?;
91
///         let b = reader.next().read_bool()?;
92
///         return Ok((i, b));
93
///     })
94
/// }).unwrap();
95
/// println!("{:?} = [48, 6, 2, 1, 10, 1, 1, 255]", asn);
96
/// ```
97
0
pub fn parse_der<'a, T, F>(buf: &'a [u8], callback: F)
98
0
        -> ASN1Result<T>
99
0
        where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
100
0
    parse_ber_general(buf, BERMode::Der, callback)
101
0
}
102
103
/// Used by [`BERReader`] to determine whether or not to enforce
104
/// DER restrictions when parsing.
105
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
106
pub enum BERMode {
107
    /// Use BER (Basic Encoding Rules).
108
    Ber,
109
    /// Use DER (Distinguished Encoding Rules).
110
    Der,
111
}
112
113
#[derive(Debug)]
114
struct BERReaderImpl<'a> {
115
    buf: &'a [u8],
116
    pos: usize,
117
    mode: BERMode,
118
    depth: usize,
119
}
120
121
const PC_BITS : [PCBit; 2] = [PCBit::Primitive, PCBit::Constructed];
122
123
#[derive(Debug)]
124
enum Contents<'a, 'b> where 'a: 'b {
125
    Primitive(&'a [u8]),
126
    Constructed(&'b mut BERReaderImpl<'a>),
127
}
128
129
const BER_READER_STACK_DEPTH : usize = 100;
130
131
impl<'a> BERReaderImpl<'a> {
132
0
    fn new(buf: &'a [u8], mode: BERMode) -> Self {
133
0
        return BERReaderImpl {
134
0
            buf,
135
0
            pos: 0,
136
0
            mode,
137
0
            depth: 0,
138
0
        };
139
0
    }
140
141
0
    fn with_pos(buf: &'a [u8], pos: usize, mode: BERMode) -> Self {
142
0
        return BERReaderImpl {
143
0
            buf,
144
0
            pos,
145
0
            mode,
146
0
            depth: 0,
147
0
        };
148
0
    }
149
150
0
    fn read_u8(&mut self) -> ASN1Result<u8> {
151
0
        if self.pos < self.buf.len() {
152
0
            let ret = self.buf[self.pos];
153
0
            self.pos += 1;
154
0
            return Ok(ret);
155
        } else {
156
0
            return Err(ASN1Error::new(ASN1ErrorKind::Eof));
157
        }
158
0
    }
159
160
0
    fn end_of_buf(&mut self) -> ASN1Result<()> {
161
0
        if self.pos != self.buf.len() {
162
0
            return Err(ASN1Error::new(ASN1ErrorKind::Extra));
163
0
        }
164
0
        return Ok(());
165
0
    }
166
167
0
    fn end_of_contents(&mut self) -> ASN1Result<()> {
168
0
        let (tag, pcbit) = self.read_identifier()?;
169
0
        if tag != TAG_EOC || pcbit != PCBit::Primitive {
170
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
171
0
        }
172
0
        let b = self.read_u8()?;
173
0
        if b != 0 {
174
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
175
0
        }
176
0
        return Ok(());
177
0
    }
178
179
0
    fn read_identifier(&mut self) -> ASN1Result<(Tag, PCBit)> {
180
0
        let tagbyte = self.read_u8()?;
181
0
        let tag_class = TAG_CLASSES[(tagbyte >> 6) as usize];
182
0
        let pcbit = PC_BITS[((tagbyte >> 5) & 1) as usize];
183
0
        let mut tag_number = (tagbyte & 31) as u64;
184
0
        if tag_number == 31 {
185
0
            tag_number = 0;
186
            loop {
187
0
                let b = self.read_u8()? as u64;
188
0
                let x =
189
0
                    tag_number.checked_mul(128).ok_or(
190
0
                        ASN1Error::new(ASN1ErrorKind::IntegerOverflow))?;
191
0
                tag_number = x + (b & 127);
192
0
                if (b & 128) == 0 {
193
0
                    break;
194
0
                }
195
            }
196
0
            if tag_number < 31 {
197
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
198
0
            }
199
0
        }
200
0
        let tag = Tag {
201
0
            tag_class,
202
0
            tag_number,
203
0
        };
204
0
        return Ok((tag, pcbit));
205
0
    }
206
207
0
    fn lookahead_tag(&self) -> ASN1Result<Tag> {
208
0
        let mut pos = self.pos;
209
0
        let mut read_u8 = || {
210
0
            if pos < self.buf.len() {
211
0
                let ret = self.buf[pos];
212
0
                pos += 1;
213
0
                return Ok(ret);
214
            } else {
215
0
                return Err(ASN1Error::new(ASN1ErrorKind::Eof));
216
            }
217
0
        };
218
0
        let tagbyte = read_u8()?;
219
0
        let tag_class = TAG_CLASSES[(tagbyte >> 6) as usize];
220
0
        let mut tag_number = (tagbyte & 31) as u64;
221
0
        if tag_number == 31 {
222
0
            tag_number = 0;
223
            loop {
224
0
                let b = read_u8()? as u64;
225
0
                let x =
226
0
                    tag_number.checked_mul(128).ok_or(
227
0
                        ASN1Error::new(ASN1ErrorKind::IntegerOverflow))?;
228
0
                tag_number = x + (b & 127);
229
0
                if (b & 128) == 0 {
230
0
                    break;
231
0
                }
232
            }
233
0
            if tag_number < 31 {
234
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
235
0
            }
236
0
        }
237
0
        let tag = Tag {
238
0
            tag_class,
239
0
            tag_number,
240
0
        };
241
0
        return Ok(tag);
242
0
    }
243
244
0
    fn read_length(&mut self) -> ASN1Result<Option<usize>> {
245
0
        let lbyte = self.read_u8()? as usize;
246
0
        if lbyte == 128 {
247
0
            return Ok(None);
248
0
        }
249
0
        if lbyte == 255 {
250
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
251
0
        }
252
0
        if (lbyte & 128) == 0 {
253
0
            return Ok(Some(lbyte));
254
0
        }
255
0
        let mut length : usize = 0;
256
0
        for _ in 0..(lbyte & 127) {
257
0
            let x = length.checked_mul(256).ok_or(
258
0
                ASN1Error::new(ASN1ErrorKind::Eof))?;
259
0
            length = x + (self.read_u8()? as usize);
260
        }
261
0
        if self.mode == BERMode::Der && length < 128 {
262
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
263
0
        }
264
0
        return Ok(Some(length));
265
0
    }
266
267
0
    fn read_general<T, F>(&mut self, tag: Tag, callback: F) -> ASN1Result<T>
268
0
            where F: for<'b> FnOnce(Contents<'a, 'b>) -> ASN1Result<T> {
269
0
        if self.depth > BER_READER_STACK_DEPTH {
270
0
            return Err(ASN1Error::new(ASN1ErrorKind::StackOverflow));
271
0
        }
272
0
        let old_pos = self.pos;
273
0
        let (tag2, pcbit) = self.read_identifier()?;
274
0
        if tag2 != tag {
275
0
            self.pos = old_pos;
276
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
277
0
        }
278
0
        let length_spec = self.read_length()?;
279
0
        let old_buf = self.buf;
280
0
        match length_spec {
281
0
            Some(length) => {
282
0
                let limit = match self.pos.checked_add(length) {
283
0
                    Some(l) => l,
284
0
                    None => return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow)),
285
                };
286
287
0
                if old_buf.len() < limit {
288
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Eof));
289
0
                }
290
0
                self.buf = &old_buf[..limit];
291
            },
292
            None => {
293
0
                if pcbit != PCBit::Constructed {
294
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
295
0
                }
296
0
                if self.mode == BERMode::Der {
297
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
298
0
                }
299
            },
300
        };
301
0
        self.depth += 1;
302
0
        let result = callback(match pcbit {
303
            PCBit::Primitive => {
304
0
                let buf = &self.buf[self.pos..];
305
0
                self.pos = self.buf.len();
306
0
                Contents::Primitive(&buf)
307
            },
308
0
            PCBit::Constructed => Contents::Constructed(self),
309
0
        })?;
310
0
        self.depth -= 1;
311
0
        match length_spec {
312
            Some(_) => {
313
0
                self.end_of_buf()?;
314
            },
315
            None => {
316
0
                self.end_of_contents()?;
317
            },
318
        };
319
0
        self.buf = old_buf;
320
0
        return Ok(result);
321
0
    }
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<yasna::models::oid::ObjectIdentifier, <yasna::reader::BERReader>::read_oid::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<(alloc::vec::Vec<u8>, bool), <yasna::reader::BERReader>::read_bigint_bytes::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<bool, <yasna::reader::BERReader>::read_bool::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<(), <yasna::reader::BERReader>::read_bytes_impl::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<(), <yasna::reader::BERReader>::read_bitvec_impl::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<(), <yasna::reader::BERReader>::read_null::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<i64, <yasna::reader::BERReader>::read_integer::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_general::<u64, <yasna::reader::BERReader>::read_u64::{closure#0}>
322
323
0
    fn skip_general(&mut self) -> ASN1Result<(Tag, PCBit, usize)> {
324
0
        let mut skip_depth = 0;
325
0
        let mut skip_tag = None;
326
0
        let mut data_pos = None;
327
0
        while skip_depth > 0 || skip_tag == None {
328
0
            let old_pos = self.pos;
329
0
            let (tag, pcbit) = self.read_identifier()?;
330
0
            if tag == TAG_EOC {
331
0
                if skip_depth == 0 {
332
0
                    self.pos = old_pos;
333
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
334
0
                }
335
0
                skip_depth -= 1;
336
                // EOC is a pair of zero bytes, consume the second.
337
0
                if self.read_u8()? != 0 {
338
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
339
0
                }
340
0
                continue;
341
0
            }
342
0
            if skip_depth == 0 {
343
0
                skip_tag = Some((tag, pcbit));
344
0
            }
345
0
            if let Some(length) = self.read_length()? {
346
0
                if skip_depth == 0 {
347
0
                    data_pos = Some(self.pos);
348
0
                }
349
0
                let limit = self.pos+length;
350
0
                if self.buf.len() < limit {
351
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Eof));
352
0
                }
353
0
                self.pos = limit;
354
            } else {
355
0
                if skip_depth == 0 {
356
0
                    data_pos = Some(self.pos);
357
0
                }
358
0
                if pcbit != PCBit::Constructed || self.mode == BERMode::Der {
359
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
360
0
                }
361
0
                skip_depth += 1;
362
            }
363
        }
364
0
        return Ok((skip_tag.unwrap().0, skip_tag.unwrap().1, data_pos.unwrap()));
365
0
    }
366
367
0
    fn read_with_buffer<'b, T, F>(&'b mut self, callback: F)
368
0
            -> ASN1Result<(T, &'a [u8])>
369
0
            where F: FnOnce(&mut Self) -> ASN1Result<T> {
370
0
        let old_pos = self.pos;
371
0
        let result = callback(self)?;
372
0
        let new_pos = self.pos;
373
0
        let buf = &self.buf[old_pos..new_pos];
374
0
        return Ok((result, buf));
375
0
    }
376
377
0
    fn read_optional<T, F>(&mut self, callback: F) -> ASN1Result<Option<T>>
378
0
            where F: FnOnce(&mut Self) -> ASN1Result<T> {
379
0
        let old_pos = self.pos;
380
0
        match callback(self) {
381
0
            Ok(result) => Ok(Some(result)),
382
0
            Err(e) =>
383
0
                if old_pos == self.pos {
384
0
                    Ok(None)
385
                } else {
386
0
                    Err(e)
387
                },
388
        }
389
0
    }
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_optional::<(), <yasna::reader::BERReader>::read_bytes_impl::{closure#0}::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReaderImpl>::read_optional::<(), <yasna::reader::BERReader>::read_bitvec_impl::{closure#0}::{closure#0}>
390
391
}
392
393
/// A reader object for BER/DER-encoded ASN.1 data.
394
///
395
/// The two main sources of `BERReaderSeq` are:
396
///
397
/// - The [`parse_ber`]/[`parse_der`] function,
398
///   the starting point of DER serialization.
399
/// - The [`next`](BERReaderSeq::next) method of [`BERReaderSeq`].
400
///
401
/// # Examples
402
///
403
/// ```
404
/// use yasna;
405
/// let data = &[2, 1, 10];
406
/// let asn = yasna::parse_der(data, |reader| {
407
///     reader.read_i64()
408
/// }).unwrap();
409
/// assert_eq!(asn, 10);
410
/// ```
411
#[derive(Debug)]
412
pub struct BERReader<'a, 'b> where 'a: 'b {
413
    inner: &'b mut BERReaderImpl<'a>,
414
    implicit_tag: Option<Tag>,
415
}
416
417
impl<'a, 'b> BERReader<'a, 'b> {
418
0
    fn new(inner: &'b mut BERReaderImpl<'a>) -> Self {
419
0
        BERReader {
420
0
            inner,
421
0
            implicit_tag: None,
422
0
        }
423
0
    }
424
425
0
    fn read_general<T, F>(self, tag: Tag, callback: F) -> ASN1Result<T>
426
0
            where F: for<'c> FnOnce(Contents<'a, 'c>) -> ASN1Result<T> {
427
0
        let tag = self.implicit_tag.unwrap_or(tag);
428
0
        self.inner.read_general(tag, callback)
429
0
    }
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<yasna::models::oid::ObjectIdentifier, <yasna::reader::BERReader>::read_oid::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<(alloc::vec::Vec<u8>, bool), <yasna::reader::BERReader>::read_bigint_bytes::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<bool, <yasna::reader::BERReader>::read_bool::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<(), <yasna::reader::BERReader>::read_bytes_impl::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<(), <yasna::reader::BERReader>::read_bitvec_impl::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<(), <yasna::reader::BERReader>::read_null::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<i64, <yasna::reader::BERReader>::read_integer::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_general::<u64, <yasna::reader::BERReader>::read_u64::{closure#0}>
430
431
    /// Tells which format we are parsing, BER or DER.
432
0
    pub fn mode(&self) -> BERMode {
433
0
        self.inner.mode
434
0
    }
435
436
    /// Reads an ASN.1 BOOLEAN value as `bool`.
437
    ///
438
    /// # Examples
439
    ///
440
    /// ```
441
    /// use yasna;
442
    /// let data = &[1, 1, 255];
443
    /// let asn = yasna::parse_der(data, |reader| {
444
    ///     reader.read_bool()
445
    /// }).unwrap();
446
    /// assert_eq!(asn, true);
447
    /// ```
448
0
    pub fn read_bool(self) -> ASN1Result<bool> {
449
0
        let mode = self.mode();
450
0
        self.read_general(TAG_BOOLEAN, |contents| {
451
0
            let buf = match contents {
452
0
                Contents::Primitive(buf) => buf,
453
                Contents::Constructed(_) => {
454
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
455
                },
456
            };
457
0
            if buf.len() != 1 {
458
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
459
0
            }
460
0
            let b = buf[0];
461
0
            if mode == BERMode::Der && b != 0 && b != 255 {
462
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
463
0
            }
464
0
            return Ok(b != 0);
465
0
        })
466
0
    }
467
468
0
    fn read_integer(self, tag: Tag) -> ASN1Result<i64> {
469
0
        self.read_general(tag, |contents| {
470
0
            let buf = match contents {
471
0
                Contents::Primitive(buf) => buf,
472
                Contents::Constructed(_) => {
473
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
474
                },
475
            };
476
0
            if buf.len() == 0 {
477
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
478
0
            } else if buf.len() == 1 {
479
0
                return Ok(buf[0] as i8 as i64);
480
0
            }
481
0
            let mut x = ((buf[0] as i8 as i64) << 8) + (buf[1] as i64);
482
0
            if -128 <= x && x < 128 {
483
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
484
0
            }
485
0
            if buf.len() > 8 {
486
0
                return Err(ASN1Error::new(
487
0
                    ASN1ErrorKind::IntegerOverflow));
488
0
            }
489
0
            for &b in buf[2..].iter() {
490
0
                x = (x << 8) | (b as i64);
491
0
            }
492
0
            return Ok(x);
493
0
        })
494
0
    }
495
496
    /// Reads an ASN.1 ENUMERATED value as `i64`.
497
    ///
498
    /// # Examples
499
    ///
500
    /// ```
501
    /// use yasna;
502
    /// let data = &[10, 1, 13];
503
    /// let asn = yasna::parse_der(data, |reader| {
504
    ///     reader.read_enum()
505
    /// }).unwrap();
506
    /// assert_eq!(asn, 13);
507
    /// ```
508
    ///
509
    /// # Errors
510
    ///
511
    /// Except parse errors, it can raise integer overflow errors.
512
0
    pub fn read_enum(self) -> ASN1Result<i64> {
513
0
        self.read_integer(TAG_ENUM)
514
0
    }
515
516
    /// Reads an ASN.1 INTEGER value as `i64`.
517
    ///
518
    /// # Examples
519
    ///
520
    /// ```
521
    /// use yasna;
522
    /// let data = &[2, 4, 73, 150, 2, 210];
523
    /// let asn = yasna::parse_der(data, |reader| {
524
    ///     reader.read_i64()
525
    /// }).unwrap();
526
    /// assert_eq!(asn, 1234567890);
527
    /// ```
528
    ///
529
    /// # Errors
530
    ///
531
    /// Except parse errors, it can raise integer overflow errors.
532
0
    pub fn read_i64(self) -> ASN1Result<i64> {
533
0
        self.read_integer(TAG_INTEGER)
534
0
    }
535
536
    /// Reads an ASN.1 INTEGER value as `u64`.
537
    ///
538
    /// # Errors
539
    ///
540
    /// Except parse errors, it can raise integer overflow errors.
541
0
    pub fn read_u64(self) -> ASN1Result<u64> {
542
0
        self.read_general(TAG_INTEGER, |contents| {
543
0
            let buf = match contents {
544
0
                Contents::Primitive(buf) => buf,
545
                Contents::Constructed(_) => {
546
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
547
                },
548
            };
549
0
            if buf.len() == 0 {
550
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
551
0
            } else if buf[0] >= 128 {
552
0
                return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
553
0
            } else if buf.len() == 1 {
554
0
                return Ok(buf[0] as u64);
555
0
            }
556
0
            let mut x = ((buf[0] as u64) << 8) + (buf[1] as u64);
557
0
            if x < 128 {
558
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
559
0
            }
560
0
            if buf.len() > 9 || (buf.len() == 9 && buf[0] != 0) {
561
0
                return Err(ASN1Error::new(
562
0
                    ASN1ErrorKind::IntegerOverflow));
563
0
            }
564
0
            for &b in buf[2..].iter() {
565
0
                x = (x << 8) | (b as u64);
566
0
            }
567
0
            return Ok(x);
568
0
        })
569
0
    }
570
571
    /// Reads an ASN.1 INTEGER value as `i32`.
572
    ///
573
    /// # Errors
574
    ///
575
    /// Except parse errors, it can raise integer overflow errors.
576
0
    pub fn read_i32(self) -> ASN1Result<i32> {
577
0
        let val = self.read_i64()?;
578
0
        if -(1 << 31) <= val && val < (1 << 31) {
579
0
            return Ok(val as i32);
580
        } else {
581
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
582
        }
583
0
    }
584
585
    /// Reads an ASN.1 INTEGER value as `u32`.
586
    ///
587
    /// # Errors
588
    ///
589
    /// Except parse errors, it can raise integer overflow errors.
590
0
    pub fn read_u32(self) -> ASN1Result<u32> {
591
0
        let val = self.read_u64()?;
592
0
        if val < (1 << 32) {
593
0
            return Ok(val as u32);
594
        } else {
595
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
596
        }
597
0
    }
598
599
    /// Reads an ASN.1 INTEGER value as `i16`.
600
    ///
601
    /// # Errors
602
    ///
603
    /// Except parse errors, it can raise integer overflow errors.
604
0
    pub fn read_i16(self) -> ASN1Result<i16> {
605
0
        let val = self.read_i64()?;
606
0
        if -(1 << 15) <= val && val < (1 << 15) {
607
0
            return Ok(val as i16);
608
        } else {
609
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
610
        }
611
0
    }
612
613
    /// Reads an ASN.1 INTEGER value as `u16`.
614
    ///
615
    /// # Errors
616
    ///
617
    /// Except parse errors, it can raise integer overflow errors.
618
0
    pub fn read_u16(self) -> ASN1Result<u16> {
619
0
        let val = self.read_u64()?;
620
0
        if val < (1 << 16) {
621
0
            return Ok(val as u16);
622
        } else {
623
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
624
        }
625
0
    }
626
627
    /// Reads an ASN.1 INTEGER value as `i8`.
628
    ///
629
    /// # Errors
630
    ///
631
    /// Except parse errors, it can raise integer overflow errors.
632
0
    pub fn read_i8(self) -> ASN1Result<i8> {
633
0
        let val = self.read_i64()?;
634
0
        if -(1 << 7) <= val && val < (1 << 7) {
635
0
            return Ok(val as i8);
636
        } else {
637
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
638
        }
639
0
    }
640
641
    /// Reads an ASN.1 INTEGER value as `u8`.
642
    ///
643
    /// # Errors
644
    ///
645
    /// Except parse errors, it can raise integer overflow errors.
646
0
    pub fn read_u8(self) -> ASN1Result<u8> {
647
0
        let val = self.read_u64()?;
648
0
        if val < (1 << 8) {
649
0
            return Ok(val as u8);
650
        } else {
651
0
            return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
652
        }
653
0
    }
654
655
    #[cfg(feature = "num-bigint")]
656
    /// Reads an ASN.1 INTEGER value as `BigInt`.
657
    ///
658
    /// # Examples
659
    ///
660
    /// ```
661
    /// # fn main() {
662
    /// use yasna;
663
    /// use num_bigint::BigInt;
664
    /// let data = &[2, 4, 73, 150, 2, 210];
665
    /// let asn = yasna::parse_der(data, |reader| {
666
    ///     reader.read_bigint()
667
    /// }).unwrap();
668
    /// assert_eq!(&asn, &BigInt::parse_bytes(b"1234567890", 10).unwrap());
669
    /// # }
670
    /// ```
671
    ///
672
    /// # Features
673
    ///
674
    /// This method is enabled by `num` feature.
675
    ///
676
    /// ```toml
677
    /// [dependencies]
678
    /// yasna = { version = "*", features = ["num"] }
679
    /// ```
680
    pub fn read_bigint(self) -> ASN1Result<BigInt> {
681
        let (mut bytes, non_negative) = self.read_bigint_bytes()?;
682
        let sign = if non_negative {
683
            Sign::Plus
684
        } else {
685
            let mut carry: usize = 1;
686
            for b in bytes.iter_mut().rev() {
687
                let bval = 255 - (*b as usize);
688
                *b = (bval + carry) as u8;
689
                carry = (bval + carry) >> 8;
690
            }
691
            Sign::Minus
692
        };
693
        Ok(BigInt::from_bytes_be(sign, &bytes))
694
    }
695
696
    /// Reads an ASN.1 INTEGER value as `Vec<u8>` and a sign bit.
697
    ///
698
    /// The number given is in big endian byte ordering, and in two's
699
    /// complement.
700
    ///
701
    /// The sign bit is `true` if the number is positive,
702
    /// and false if it is negative.
703
    ///
704
    /// # Examples
705
    ///
706
    /// ```
707
    /// # fn main() {
708
    /// use yasna;
709
    /// let data = &[2, 4, 73, 150, 2, 210];
710
    /// let (bytes, nonnegative) = yasna::parse_der(data, |reader| {
711
    ///     reader.read_bigint_bytes()
712
    /// }).unwrap();
713
    /// assert_eq!(&bytes, &[73, 150, 2, 210]);
714
    /// assert_eq!(nonnegative, true);
715
    /// # }
716
    /// ```
717
0
    pub fn read_bigint_bytes(self) -> ASN1Result<(Vec<u8>, bool)> {
718
0
        self.read_general(TAG_INTEGER, |contents| {
719
0
            let buf = match contents {
720
0
                Contents::Primitive(buf) => buf,
721
                Contents::Constructed(_) => {
722
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
723
                },
724
            };
725
0
            if buf.len() == 0 {
726
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
727
0
            } else if buf.len() == 1 {
728
0
                return Ok((buf.to_vec(), buf[0] & 128 == 0));
729
0
            }
730
0
            let x2 = ((buf[0] as i8 as i32) << 8) + (buf[1] as i32);
731
0
            if -128 <= x2 && x2 < 128 {
732
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
733
0
            }
734
0
            let sign = 0 <= x2;
735
0
            Ok((buf.to_vec(), sign))
736
0
        })
737
0
    }
738
739
    #[cfg(feature = "num-bigint")]
740
    /// Reads an ASN.1 INTEGER value as `BigUint`.
741
    ///
742
    /// # Errors
743
    ///
744
    /// Except parse errors, it can raise integer overflow errors.
745
    ///
746
    /// # Features
747
    ///
748
    /// This method is enabled by `num` feature.
749
    ///
750
    /// ```toml
751
    /// [dependencies]
752
    /// yasna = { version = "*", features = ["num"] }
753
    /// ```
754
    pub fn read_biguint(self) -> ASN1Result<BigUint> {
755
        self.read_general(TAG_INTEGER, |contents| {
756
            let buf = match contents {
757
                Contents::Primitive(buf) => buf,
758
                Contents::Constructed(_) => {
759
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
760
                },
761
            };
762
            if buf.len() == 0 {
763
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
764
            } else if buf[0] >= 128 {
765
                return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
766
            } else if buf.len() == 1 {
767
                return Ok(BigUint::from(buf[0]));
768
            }
769
            let x2 = ((buf[0] as i8 as i32) << 8) + (buf[1] as i32);
770
            if -128 <= x2 && x2 < 128 {
771
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
772
            } else if x2 < 0 {
773
                return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
774
            }
775
            return Ok(BigUint::from_bytes_be(buf));
776
        })
777
    }
778
779
0
    fn read_bitvec_impl(self, unused_bits: &mut usize, bytes: &mut Vec<u8>)
780
0
            -> ASN1Result<()> {
781
        use super::tags::TAG_BITSTRING;
782
0
        if *unused_bits != 0 {
783
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
784
0
        }
785
0
        let mode = self.inner.mode;
786
0
        self.read_general(TAG_BITSTRING, |contents| {
787
0
            match contents {
788
0
                Contents::Primitive(buf) => {
789
0
                    if buf.len() == 0 {
790
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
791
0
                    }
792
0
                    if buf[0] >= 8 {
793
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
794
0
                    }
795
0
                    if buf[0] > 0 {
796
0
                        if buf.len() == 1 {
797
0
                            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
798
0
                        }
799
0
                        if mode == BERMode::Der &&
800
0
                            (buf[buf.len()-1] & ((1<<buf[0]) - 1)) != 0 {
801
0
                            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
802
0
                        }
803
0
                    }
804
0
                    bytes.extend_from_slice(&buf[1..]);
805
0
                    *unused_bits = buf[0] as usize;
806
0
                    return Ok(());
807
                },
808
0
                Contents::Constructed(inner) => {
809
0
                    if mode == BERMode::Der {
810
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
811
0
                    }
812
                    loop {
813
0
                        let result = inner.read_optional(|inner| {
814
0
                            BERReader::new(inner)
815
0
                                .read_bitvec_impl(unused_bits, bytes)
816
0
                        })?;
817
0
                        match result {
818
0
                            Some(()) => {},
819
0
                            None => { break; },
820
                        }
821
                    }
822
0
                    return Ok(());
823
                },
824
            };
825
0
        })
826
0
    }
827
828
    #[cfg(feature = "bit-vec")]
829
    /// Reads an ASN.1 BITSTRING value as `BitVec`.
830
    ///
831
    /// # Examples
832
    ///
833
    /// ```
834
    /// # fn main() {
835
    /// use yasna;
836
    /// use bit_vec::BitVec;
837
    /// let data = &[3, 5, 3, 206, 213, 116, 24];
838
    /// let asn = yasna::parse_der(data, |reader| {
839
    ///     reader.read_bitvec()
840
    /// }).unwrap();
841
    /// assert_eq!(
842
    ///     asn.into_iter().map(|b| b as usize).collect::<Vec<_>>(),
843
    ///     vec![1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1,
844
    ///         0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1]);
845
    /// # }
846
    /// ```
847
    ///
848
    /// # Features
849
    ///
850
    /// This method is enabled by `bit-vec` feature.
851
    ///
852
    /// ```toml
853
    /// [dependencies]
854
    /// yasna = { version = "*", features = ["bit-vec"] }
855
    /// ```
856
    pub fn read_bitvec(self) -> ASN1Result<BitVec> {
857
        let (bytes, len) = self.read_bitvec_bytes()?;
858
        let mut ret = BitVec::from_bytes(&bytes);
859
        ret.truncate(len);
860
        return Ok(ret);
861
    }
862
863
    /// Reads an ASN.1 BITSTRING value as `(Vec<u8>, usize)`.
864
    ///
865
    /// # Examples
866
    ///
867
    /// ```
868
    /// # fn main() {
869
    /// use yasna;
870
    /// let data = &[3, 4, 6, 117, 13, 64];
871
    /// let asn = yasna::parse_der(data, |reader| {
872
    ///     reader.read_bitvec_bytes()
873
    /// }).unwrap();
874
    /// assert_eq!(asn, (vec![117, 13, 64], 18));
875
    /// # }
876
    /// ```
877
    ///
878
    /// # Features
879
    ///
880
    /// This method is enabled by `bit-vec` feature.
881
    ///
882
    /// ```toml
883
    /// [dependencies]
884
    /// yasna = { version = "*", features = ["bit-vec"] }
885
    /// ```
886
0
    pub fn read_bitvec_bytes(self) -> ASN1Result<(Vec<u8>, usize)> {
887
0
        let mut unused_bits = 0;
888
0
        let mut bytes = Vec::new();
889
0
        self.read_bitvec_impl(&mut unused_bits, &mut bytes)?;
890
0
        let len = bytes.len() * 8 - unused_bits;
891
0
        return Ok((bytes, len));
892
0
    }
893
894
0
    fn read_bytes_impl(self, vec: &mut Vec<u8>) -> ASN1Result<()> {
895
0
        self.read_general(TAG_OCTETSTRING, |contents| {
896
0
            match contents {
897
0
                Contents::Primitive(buf) => {
898
0
                    vec.extend(buf);
899
0
                    return Ok(());
900
                },
901
0
                Contents::Constructed(inner) => {
902
0
                    if inner.mode == BERMode::Der {
903
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
904
0
                    }
905
                    loop {
906
0
                        let result = inner.read_optional(|inner| {
907
0
                            BERReader::new(inner).read_bytes_impl(vec)
908
0
                        })?;
909
0
                        match result {
910
0
                            Some(()) => {},
911
0
                            None => { break; },
912
                        }
913
                    }
914
0
                    return Ok(());
915
                },
916
            };
917
0
        })
918
0
    }
919
920
    /// Reads an ASN.1 OCTETSTRING value as `Vec<u8>`.
921
    ///
922
    /// # Examples
923
    ///
924
    /// ```
925
    /// use yasna;
926
    /// let data = &[36, 128, 4, 2, 72, 101, 4, 4, 108, 108, 111, 33, 0, 0];
927
    /// let asn = yasna::parse_ber(data, |reader| {
928
    ///     reader.read_bytes()
929
    /// }).unwrap();
930
    /// assert_eq!(&asn, b"Hello!");
931
    /// ```
932
0
    pub fn read_bytes(self) -> ASN1Result<Vec<u8>> {
933
0
        let mut ret = Vec::new();
934
0
        self.read_bytes_impl(&mut ret)?;
935
0
        return Ok(ret);
936
0
    }
937
938
    /// Reads the ASN.1 NULL value.
939
    ///
940
    /// # Examples
941
    ///
942
    /// ```
943
    /// use yasna;
944
    /// let data = &[5, 0];
945
    /// let asn = yasna::parse_der(data, |reader| {
946
    ///     reader.read_null()
947
    /// }).unwrap();
948
    /// assert_eq!(asn, ());
949
    /// ```
950
0
    pub fn read_null(self) -> ASN1Result<()> {
951
0
        self.read_general(TAG_NULL, |contents| {
952
0
            let buf = match contents {
953
0
                Contents::Primitive(buf) => buf,
954
                Contents::Constructed(_) => {
955
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
956
                },
957
            };
958
0
            if buf.len() != 0 {
959
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
960
0
            }
961
0
            return Ok(());
962
0
        })
963
0
    }
964
965
    /// Reads an ASN.1 object identifier.
966
    ///
967
    /// # Examples
968
    ///
969
    /// ```
970
    /// use yasna;
971
    /// let data = &[6, 8, 42, 134, 72, 134, 247, 13, 1, 1];
972
    /// let asn = yasna::parse_der(data, |reader| {
973
    ///     reader.read_oid()
974
    /// }).unwrap();
975
    /// assert_eq!(&*asn.components(), &[1, 2, 840, 113549, 1, 1]);
976
    /// ```
977
0
    pub fn read_oid(self) -> ASN1Result<ObjectIdentifier> {
978
0
        self.read_general(TAG_OID, |contents| {
979
0
            let buf = match contents {
980
0
                Contents::Primitive(buf) => buf,
981
                Contents::Constructed(_) => {
982
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
983
                },
984
            };
985
0
            let mut components = Vec::new();
986
0
            if buf.len() == 0 || buf[buf.len()-1] >= 128 {
987
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
988
0
            }
989
0
            let mut subid : u64 = 0;
990
0
            for &b in buf.iter() {
991
0
                if b == 128 {
992
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
993
0
                }
994
0
                subid = subid.checked_mul(128)
995
0
                    .ok_or(ASN1Error::new(
996
0
                        ASN1ErrorKind::IntegerOverflow))? + ((b & 127) as u64);
997
0
                if (b & 128) == 0 {
998
0
                    if components.len() == 0 {
999
0
                        let id0 = if subid < 40 {
1000
0
                            0
1001
0
                        } else if subid < 80 {
1002
0
                            1
1003
                        } else {
1004
0
                            2
1005
                        };
1006
0
                        let id1 = subid - 40 * id0;
1007
0
                        components.push(id0);
1008
0
                        components.push(id1);
1009
0
                    } else {
1010
0
                        components.push(subid);
1011
0
                    }
1012
0
                    subid = 0;
1013
0
                }
1014
            }
1015
0
            return Ok(ObjectIdentifier::new(components));
1016
0
        })
1017
0
    }
1018
1019
    /// Reads an ASN.1 UTF8String.
1020
    ///
1021
    /// # Examples
1022
    ///
1023
    /// ```
1024
    /// use yasna;
1025
    /// let data = &[
1026
    ///     12, 29, 103, 110, 97, 119, 32, 207, 129, 206, 191, 206,
1027
    ///     186, 206, 177, 206, 189, 206, 175, 206, 182, 207,
1028
    ///     137, 32, 240, 170, 152, 130, 227, 130, 139];
1029
    /// let asn = yasna::parse_der(data, |reader| {
1030
    ///     reader.read_utf8string()
1031
    /// }).unwrap();
1032
    /// assert_eq!(&asn, "gnaw ροκανίζω 𪘂る");
1033
    /// ```
1034
0
    pub fn read_utf8string(self) -> ASN1Result<String> {
1035
0
        self.read_tagged_implicit(TAG_UTF8STRING, |reader| {
1036
0
            let bytes = reader.read_bytes()?;
1037
0
            match String::from_utf8(bytes) {
1038
0
                Ok(string) => Ok(string),
1039
0
                Err(_) => Err(ASN1Error::new(ASN1ErrorKind::Invalid)),
1040
            }
1041
0
        })
1042
0
    }
1043
1044
    /// Reads an ASN.1 SEQUENCE value.
1045
    ///
1046
    /// This function uses the loan pattern: `callback` is called back with
1047
    /// a [`BERReaderSeq`], from which the contents of the
1048
    /// SEQUENCE is read.
1049
    ///
1050
    /// # Examples
1051
    ///
1052
    /// ```
1053
    /// use yasna;
1054
    /// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
1055
    /// let asn = yasna::parse_der(data, |reader| {
1056
    ///     reader.read_sequence(|reader| {
1057
    ///         let i = reader.next().read_i64()?;
1058
    ///         let b = reader.next().read_bool()?;
1059
    ///         return Ok((i, b));
1060
    ///     })
1061
    /// }).unwrap();
1062
    /// assert_eq!(asn, (10, true));
1063
    /// ```
1064
0
    pub fn read_sequence<T, F>(self, callback: F) -> ASN1Result<T>
1065
0
            where F: for<'c> FnOnce(
1066
0
                &mut BERReaderSeq<'a, 'c>) -> ASN1Result<T> {
1067
0
        self.read_general(TAG_SEQUENCE, |contents| {
1068
0
            let inner = match contents {
1069
                Contents::Primitive(_) => {
1070
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1071
                },
1072
0
                Contents::Constructed(inner) => inner,
1073
            };
1074
0
            return callback(&mut BERReaderSeq { inner, });
1075
0
        })
1076
0
    }
1077
1078
    /// Reads an ASN.1 SEQUENCE OF value.
1079
    ///
1080
    /// This function uses the loan pattern: `callback` is called back with
1081
    /// a [`BERReader`], from which the contents of the
1082
    /// SEQUENCE OF is read.
1083
    ///
1084
    /// This function doesn't return values. Instead, use mutable values to
1085
    /// maintain read values. `collect_set_of` can be an alternative.
1086
    ///
1087
    /// # Examples
1088
    ///
1089
    /// ```
1090
    /// use yasna;
1091
    /// let data = &[48, 7, 2, 1, 10, 2, 2, 255, 127];
1092
    /// let asn = yasna::parse_der(data, |reader| {
1093
    ///     let mut numbers = Vec::new();
1094
    ///     reader.read_sequence_of(|reader| {
1095
    ///         numbers.push(reader.read_i64()?);
1096
    ///         return Ok(());
1097
    ///     })?;
1098
    ///     return Ok(numbers);
1099
    /// }).unwrap();
1100
    /// assert_eq!(&asn, &[10, -129]);
1101
    /// ```
1102
0
    pub fn read_sequence_of<F>(self, mut callback: F) -> ASN1Result<()>
1103
0
            where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<()> {
1104
0
        self.read_sequence(|reader| {
1105
            loop {
1106
0
                if let None = reader.read_optional(|reader| {
1107
0
                    callback(reader)
1108
0
                })? {
1109
0
                    break;
1110
0
                }
1111
            }
1112
0
            return Ok(());
1113
0
        })
1114
0
    }
1115
1116
    /// Collects an ASN.1 SEQUENCE OF value.
1117
    ///
1118
    /// This function uses the loan pattern: `callback` is called back with
1119
    /// a [`BERReader`], from which the contents of the
1120
    /// SEQUENCE OF is read.
1121
    ///
1122
    /// If you don't like `Vec`, you can use `read_sequence_of` instead.
1123
    ///
1124
    /// # Examples
1125
    ///
1126
    /// ```
1127
    /// use yasna;
1128
    /// let data = &[48, 7, 2, 1, 10, 2, 2, 255, 127];
1129
    /// let asn = yasna::parse_der(data, |reader| {
1130
    ///     reader.collect_sequence_of(|reader| {
1131
    ///         reader.read_i64()
1132
    ///     })
1133
    /// }).unwrap();
1134
    /// assert_eq!(&asn, &[10, -129]);
1135
    /// ```
1136
0
    pub fn collect_sequence_of<T, F>(self, mut callback: F)
1137
0
            -> ASN1Result<Vec<T>>
1138
0
            where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<T> {
1139
0
        let mut collection = Vec::new();
1140
0
        self.read_sequence_of(|reader| {
1141
0
            collection.push(callback(reader)?);
1142
0
            return Ok(());
1143
0
        })?;
1144
0
        return Ok(collection);
1145
0
    }
1146
1147
    /// Reads an ASN.1 SET value.
1148
    ///
1149
    /// This function uses the loan pattern: `callback` is called back with
1150
    /// a [`BERReaderSet`], from which the contents of the
1151
    /// SET are read.
1152
    ///
1153
    /// For SET OF values, use `read_set_of` instead.
1154
    ///
1155
    /// # Examples
1156
    ///
1157
    /// ```
1158
    /// use yasna;
1159
    /// use yasna::tags::{TAG_INTEGER,TAG_BOOLEAN};
1160
    /// let data = &[49, 6, 1, 1, 255, 2, 1, 10];
1161
    /// let asn = yasna::parse_der(data, |reader| {
1162
    ///     reader.read_set(|reader| {
1163
    ///         let i = reader.next(&[TAG_INTEGER])?.read_i64()?;
1164
    ///         let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1165
    ///         return Ok((i, b));
1166
    ///     })
1167
    /// }).unwrap();
1168
    /// assert_eq!(asn, (10, true));
1169
    /// ```
1170
0
    pub fn read_set<T, F>(self, callback: F) -> ASN1Result<T>
1171
0
            where F: for<'c> FnOnce(
1172
0
                &mut BERReaderSet<'a, 'c>) -> ASN1Result<T> {
1173
0
        self.read_general(TAG_SET, |contents| {
1174
0
            let inner = match contents {
1175
                Contents::Primitive(_) => {
1176
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1177
                },
1178
0
                Contents::Constructed(inner) => inner,
1179
            };
1180
0
            let mut elements = Vec::new();
1181
            loop {
1182
0
                let old_pos = inner.pos;
1183
0
                if let Some(tag) = inner.read_optional(|inner| {
1184
0
                    inner.skip_general().map(|t| t.0)
1185
0
                })? {
1186
0
                    let new_pos = inner.pos;
1187
0
                    // TODO: this should store the P/C bit as well
1188
0
                    elements.push((tag, &inner.buf[..new_pos], old_pos));
1189
0
                } else {
1190
0
                    break;
1191
                }
1192
            }
1193
0
            if inner.mode == BERMode::Der {
1194
0
                for i in 1..elements.len() {
1195
0
                    if elements[i] <= elements[i-1] {
1196
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1197
0
                    }
1198
                }
1199
0
            }
1200
0
            let mut new_impl = BERReaderImpl::new(&[], inner.mode);
1201
0
            let result = callback(&mut BERReaderSet {
1202
0
                impl_ref: &mut new_impl,
1203
0
                elements: &mut elements,
1204
0
            })?;
1205
0
            if elements.len() > 0 {
1206
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1207
0
            }
1208
0
            return Ok(result);
1209
0
        })
1210
0
    }
1211
1212
    /// Reads an ASN.1 SET OF value.
1213
    ///
1214
    /// This function uses the loan pattern: `callback` is called back with
1215
    /// a [`BERReader`], from which the contents of the
1216
    /// SET OF are read.
1217
    ///
1218
    /// This function doesn't return values. Instead, use mutable values to
1219
    /// maintain read values. `collect_set_of` can be an alternative.
1220
    ///
1221
    /// This function doesn't sort the elements. In DER, it is assumed that
1222
    /// the elements occur in an order determined by DER encodings of them.
1223
    ///
1224
    /// For SET values, use `read_set` instead.
1225
    ///
1226
    /// # Examples
1227
    ///
1228
    /// ```
1229
    /// use yasna;
1230
    /// let data = &[49, 7, 2, 1, 10, 2, 2, 255, 127];
1231
    /// let asn = yasna::parse_der(data, |reader| {
1232
    ///     let mut numbers = Vec::new();
1233
    ///     reader.read_set_of(|reader| {
1234
    ///         numbers.push(reader.read_i64()?);
1235
    ///         return Ok(());
1236
    ///     })?;
1237
    ///     return Ok(numbers);
1238
    /// }).unwrap();
1239
    /// assert_eq!(asn, vec![10, -129]);
1240
    /// ```
1241
0
    pub fn read_set_of<F>(self, mut callback: F) -> ASN1Result<()>
1242
0
            where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<()> {
1243
0
        self.read_general(TAG_SET, |contents| {
1244
0
            let inner = match contents {
1245
                Contents::Primitive(_) => {
1246
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1247
                },
1248
0
                Contents::Constructed(inner) => inner,
1249
            };
1250
0
            let mut last_buf = None;
1251
0
            while let Some((_, buf)) = inner.read_optional(|inner| {
1252
0
                    inner.read_with_buffer(|inner| {
1253
0
                        callback(BERReader::new(inner))
1254
0
                    })
1255
0
            })? {
1256
0
                if let Some(last_buf) = last_buf {
1257
0
                    if inner.mode == BERMode::Der && buf < last_buf {
1258
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1259
0
                    }
1260
0
                }
1261
0
                last_buf = Some(buf);
1262
            }
1263
0
            return Ok(());
1264
0
        })
1265
0
    }
1266
1267
    /// Collects an ASN.1 SET OF value.
1268
    ///
1269
    /// This function uses the loan pattern: `callback` is called back with
1270
    /// a [`BERReader`], from which the contents of the
1271
    /// SET OF is read.
1272
    ///
1273
    /// If you don't like `Vec`, you can use `read_set_of` instead.
1274
    ///
1275
    /// This function doesn't sort the elements. In DER, it is assumed that
1276
    /// the elements occur in an order determined by DER encodings of them.
1277
    ///
1278
    /// # Examples
1279
    ///
1280
    /// ```
1281
    /// use yasna;
1282
    /// let data = &[49, 7, 2, 1, 10, 2, 2, 255, 127];
1283
    /// let asn = yasna::parse_der(data, |reader| {
1284
    ///     reader.collect_set_of(|reader| {
1285
    ///         reader.read_i64()
1286
    ///     })
1287
    /// }).unwrap();
1288
    /// assert_eq!(asn, vec![10, -129]);
1289
    /// ```
1290
0
    pub fn collect_set_of<T, F>(self, mut callback: F) -> ASN1Result<Vec<T>>
1291
0
            where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<T> {
1292
0
        let mut collection = Vec::new();
1293
0
        self.read_set_of(|reader| {
1294
0
            collection.push(callback(reader)?);
1295
0
            return Ok(());
1296
0
        })?;
1297
0
        return Ok(collection);
1298
0
    }
1299
1300
    /// Reads an ASN.1 NumericString.
1301
    ///
1302
    /// # Examples
1303
    ///
1304
    /// ```
1305
    /// use yasna;
1306
    /// let data = &[18, 7, 49, 50, 56, 32, 50, 53, 54];
1307
    /// let asn = yasna::parse_der(data, |reader| {
1308
    ///     reader.read_numeric_string()
1309
    /// }).unwrap();
1310
    /// assert_eq!(&asn, "128 256");
1311
    /// ```
1312
0
    pub fn read_numeric_string(self) -> ASN1Result<String> {
1313
0
        self.read_tagged_implicit(TAG_NUMERICSTRING, |reader| {
1314
0
            let bytes = reader.read_bytes()?;
1315
0
            for &byte in bytes.iter() {
1316
0
                if !(byte == b' ' || (b'0' <= byte && byte <= b'9')) {
1317
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1318
0
                }
1319
            }
1320
0
            return Ok(String::from_utf8(bytes).unwrap());
1321
0
        })
1322
0
    }
1323
1324
    /// Reads an ASN.1 PrintableString.
1325
    ///
1326
    /// # Examples
1327
    ///
1328
    /// ```
1329
    /// use yasna;
1330
    /// let data = &[19, 9, 67, 111, 46, 44, 32, 76, 116, 100, 46];
1331
    /// let asn = yasna::parse_der(data, |reader| {
1332
    ///     reader.read_printable_string()
1333
    /// }).unwrap();
1334
    /// assert_eq!(&asn, "Co., Ltd.");
1335
    /// ```
1336
0
    pub fn read_printable_string(self) -> ASN1Result<String> {
1337
0
        self.read_tagged_implicit(TAG_PRINTABLESTRING, |reader| {
1338
0
            let bytes = reader.read_bytes()?;
1339
0
            for &byte in bytes.iter() {
1340
                if !(
1341
0
                    byte == b' ' ||
1342
0
                    (b'\'' <= byte && byte <= b':' && byte != b'*') ||
1343
0
                    byte == b'=' ||
1344
0
                    (b'A' <= byte && byte <= b'Z') ||
1345
0
                    (b'a' <= byte && byte <= b'z')) {
1346
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1347
0
                }
1348
            }
1349
0
            return Ok(String::from_utf8(bytes).unwrap());
1350
0
        })
1351
0
    }
1352
1353
    /// Reads an ASN.1 IA5String.
1354
    ///
1355
    /// # Examples
1356
    ///
1357
    /// ```
1358
    /// use yasna;
1359
    /// let data = &[22, 9, 0x41, 0x53, 0x43, 0x49, 0x49, 0x20, 0x70, 0x6C, 0x7A];
1360
    /// let asn = yasna::parse_der(data, |reader| {
1361
    ///     reader.read_ia5_string()
1362
    /// }).unwrap();
1363
    /// assert_eq!(&asn, "ASCII plz");
1364
    /// ```
1365
0
    pub fn read_ia5_string(self) -> ASN1Result<String> {
1366
0
        self.read_tagged_implicit(TAG_IA5STRING, |reader| {
1367
0
            let bytes = reader.read_bytes()?;
1368
1369
0
            match String::from_utf8(bytes) {
1370
0
                Ok(string) => {
1371
0
                    if !string.is_ascii() {
1372
0
                        return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1373
0
                    }
1374
0
                    Ok(string)
1375
                }
1376
0
                Err(_) => Err(ASN1Error::new(ASN1ErrorKind::Invalid))
1377
            }
1378
0
        })
1379
0
    }
1380
1381
    /// Reads an ASN.1 BMPString.
1382
    ///
1383
    /// # Examples
1384
    ///
1385
    /// ```
1386
    /// use yasna;
1387
    /// let data = &[30, 14, 0x00, 0xA3, 0x03, 0xC0, 0x00, 0x20, 0x00, 0x71, 0x00, 0x75, 0x00, 0x75, 0x00, 0x78];
1388
    /// let asn = yasna::parse_der(data, |reader| {
1389
    ///     reader.read_bmp_string()
1390
    /// }).unwrap();
1391
    /// assert_eq!(&asn, "£π quux");
1392
    /// ```
1393
0
    pub fn read_bmp_string(self) -> ASN1Result<String> {
1394
0
        self.read_tagged_implicit(TAG_BMPSTRING, |reader| {
1395
0
            let bytes = reader.read_bytes()?;
1396
1397
0
            if bytes.len() % 2 != 0 {
1398
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1399
0
            }
1400
1401
0
            let utf16 : Vec<u16> = bytes.chunks(2).map(|c| (c[0] as u16) * 256 + c[1] as u16).collect();
1402
1403
0
            Ok(String::from_utf16_lossy(&utf16))
1404
0
        })
1405
0
    }
1406
1407
    #[cfg(feature = "time")]
1408
    /// Reads an ASN.1 UTCTime.
1409
    ///
1410
    /// # Examples
1411
    ///
1412
    /// ```
1413
    /// use yasna;
1414
    /// let data = &[
1415
    ///     23, 15, 56, 50, 48, 49, 48, 50, 48,
1416
    ///     55, 48, 48, 45, 48, 53, 48, 48];
1417
    /// let asn = yasna::parse_ber(data, |reader| {
1418
    ///     reader.read_utctime()
1419
    /// }).unwrap();
1420
    /// assert_eq!(asn.datetime().unix_timestamp(), 378820800);
1421
    /// ```
1422
    ///
1423
    /// # Features
1424
    ///
1425
    /// This method is enabled by `time` feature.
1426
    ///
1427
    /// ```toml
1428
    /// [dependencies]
1429
    /// yasna = { version = "*", features = ["time"] }
1430
    /// ```
1431
0
    pub fn read_utctime(self) -> ASN1Result<UTCTime> {
1432
        use super::tags::TAG_UTCTIME;
1433
0
        let mode = self.inner.mode;
1434
0
        self.read_tagged_implicit(TAG_UTCTIME, |reader| {
1435
0
            let bytes = reader.read_bytes()?;
1436
0
            let datetime = UTCTime::parse(&bytes).ok_or_else(
1437
0
                || ASN1Error::new(ASN1ErrorKind::Invalid))?;
1438
0
            if mode == BERMode::Der && &datetime.to_bytes() != &bytes {
1439
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1440
0
            }
1441
0
            return Ok(datetime);
1442
0
        })
1443
0
    }
1444
1445
    #[cfg(feature = "time")]
1446
    /// Reads an ASN.1 GeneralizedTime.
1447
    ///
1448
    /// # Examples
1449
    ///
1450
    /// ```
1451
    /// use yasna;
1452
    /// let data = &[
1453
    ///     24, 17, 49, 57, 56, 53, 49, 49, 48, 54,
1454
    ///     50, 49, 46, 49, 52, 49, 53, 57, 90];
1455
    /// let asn = yasna::parse_ber(data, |reader| {
1456
    ///     reader.read_generalized_time()
1457
    /// }).unwrap();
1458
    /// assert_eq!(asn.datetime().unix_timestamp(), 500159309);
1459
    /// ```
1460
    ///
1461
    /// # Features
1462
    ///
1463
    /// This method is enabled by `time` feature.
1464
    ///
1465
    /// ```toml
1466
    /// [dependencies]
1467
    /// yasna = { version = "*", features = ["time"] }
1468
    /// ```
1469
0
    pub fn read_generalized_time(self) -> ASN1Result<GeneralizedTime> {
1470
        use super::tags::TAG_GENERALIZEDTIME;
1471
0
        let mode = self.inner.mode;
1472
0
        self.read_tagged_implicit(TAG_GENERALIZEDTIME, |reader| {
1473
0
            let bytes = reader.read_bytes()?;
1474
0
            let datetime = GeneralizedTime::parse(&bytes).ok_or_else(
1475
0
                || ASN1Error::new(ASN1ErrorKind::Invalid))?;
1476
0
            if mode == BERMode::Der && &datetime.to_bytes() != &bytes {
1477
0
                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1478
0
            }
1479
0
            return Ok(datetime);
1480
0
        })
1481
0
    }
1482
1483
    /// Reads an ASN.1 VisibleString.
1484
    ///
1485
    /// # Examples
1486
    ///
1487
    /// ```
1488
    /// use yasna;
1489
    /// let data = &[26, 3, 72, 105, 33];
1490
    /// let asn = yasna::parse_der(data, |reader| {
1491
    ///     reader.read_visible_string()
1492
    /// }).unwrap();
1493
    /// assert_eq!(&asn, "Hi!");
1494
    /// ```
1495
0
    pub fn read_visible_string(self) -> ASN1Result<String> {
1496
0
        self.read_tagged_implicit(TAG_VISIBLESTRING, |reader| {
1497
0
            let bytes = reader.read_bytes()?;
1498
0
            for &byte in bytes.iter() {
1499
0
                if !(b' ' <= byte && byte <= b'~') {
1500
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1501
0
                }
1502
            }
1503
0
            return Ok(String::from_utf8(bytes).unwrap());
1504
0
        })
1505
0
    }
1506
1507
    /// Reads a (explicitly) tagged value.
1508
    ///
1509
    /// # Examples
1510
    ///
1511
    /// ```
1512
    /// use yasna::{self,Tag};
1513
    /// let data = &[163, 3, 2, 1, 10];
1514
    /// let asn = yasna::parse_der(data, |reader| {
1515
    ///     reader.read_tagged(Tag::context(3), |reader| {
1516
    ///         reader.read_i64()
1517
    ///     })
1518
    /// }).unwrap();
1519
    /// assert_eq!(asn, 10);
1520
    /// ```
1521
0
    pub fn read_tagged<T, F>(self, tag: Tag, callback: F) -> ASN1Result<T>
1522
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1523
0
        self.read_general(tag, |contents| {
1524
0
            let inner = match contents {
1525
                Contents::Primitive(_) => {
1526
0
                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1527
                },
1528
0
                Contents::Constructed(inner) => inner,
1529
            };
1530
0
            callback(BERReader::new(inner))
1531
0
        })
1532
0
    }
1533
1534
    /// Reads an implicitly tagged value.
1535
    ///
1536
    /// # Examples
1537
    ///
1538
    /// ```
1539
    /// use yasna::{self,Tag};
1540
    /// let data = &[131, 1, 10];
1541
    /// let asn = yasna::parse_der(data, |reader| {
1542
    ///     reader.read_tagged_implicit(Tag::context(3), |reader| {
1543
    ///         reader.read_i64()
1544
    ///     })
1545
    /// }).unwrap();
1546
    /// assert_eq!(asn, 10);
1547
    /// ```
1548
0
    pub fn read_tagged_implicit<T, F>(self, tag: Tag, callback: F)
1549
0
            -> ASN1Result<T>
1550
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1551
0
        let tag = self.implicit_tag.unwrap_or(tag);
1552
0
        return callback(BERReader {
1553
0
            inner: self.inner,
1554
0
            implicit_tag: Some(tag),
1555
0
        });
1556
0
    }
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_bmp_string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_ia5_string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_utf8string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_numeric_string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_visible_string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<alloc::string::String, <yasna::reader::BERReader>::read_printable_string::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<yasna::models::time::GeneralizedTime, <yasna::reader::BERReader>::read_generalized_time::{closure#0}>
Unexecuted instantiation: <yasna::reader::BERReader>::read_tagged_implicit::<yasna::models::time::UTCTime, <yasna::reader::BERReader>::read_utctime::{closure#0}>
1557
1558
    /// Lookaheads the tag in the next value. Used to parse CHOICE values.
1559
    ///
1560
    /// # Examples
1561
    ///
1562
    /// ```
1563
    /// use yasna;
1564
    /// use yasna::tags::*;
1565
    /// let data = &[48, 5, 2, 1, 10, 5, 0];
1566
    /// let asn = yasna::parse_der(data, |reader| {
1567
    ///     reader.collect_sequence_of(|reader| {
1568
    ///         let tag = reader.lookahead_tag()?;
1569
    ///         let choice;
1570
    ///         if tag == TAG_INTEGER {
1571
    ///             choice = Some(reader.read_i64()?);
1572
    ///         } else {
1573
    ///             reader.read_null()?;
1574
    ///             choice = None;
1575
    ///         }
1576
    ///         return Ok(choice);
1577
    ///     })
1578
    /// }).unwrap();
1579
    /// assert_eq!(&asn, &[Some(10), None]);
1580
    /// ```
1581
0
    pub fn lookahead_tag(&self) -> ASN1Result<Tag> {
1582
0
        self.inner.lookahead_tag()
1583
0
    }
1584
1585
0
    pub fn read_with_buffer<T, F>(self, callback: F)
1586
0
            -> ASN1Result<(T, &'a [u8])>
1587
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1588
0
        let implicit_tag = self.implicit_tag;
1589
0
        self.inner.read_with_buffer(|inner| {
1590
0
            callback(BERReader {
1591
0
                inner,
1592
0
                implicit_tag,
1593
0
            })
1594
0
        })
1595
0
    }
1596
1597
    /// Read an arbitrary (tag, value) pair as a TaggedDerValue.
1598
    /// The length is not included in the returned payload. If the
1599
    /// payload has indefinite-length encoding, the EOC bytes are
1600
    /// included in the returned payload.
1601
    ///
1602
    /// # Examples
1603
    ///
1604
    /// ```
1605
    /// use yasna;
1606
    /// use yasna::models::TaggedDerValue;
1607
    /// use yasna::tags::TAG_OCTETSTRING;
1608
    /// let data = b"\x04\x06Hello!";
1609
    /// let res = yasna::parse_der(data, |reader| reader.read_tagged_der()).unwrap();
1610
    /// assert_eq!(res, TaggedDerValue::from_tag_and_bytes(TAG_OCTETSTRING, b"Hello!".to_vec()));
1611
    /// ```
1612
0
    pub fn read_tagged_der(self) -> ASN1Result<TaggedDerValue> {
1613
0
        let (tag, pcbit, data_pos) = self.inner.skip_general()?;
1614
0
        Ok(TaggedDerValue::from_tag_pc_and_bytes(
1615
0
                tag,
1616
0
                pcbit,
1617
0
                self.inner.buf[data_pos..self.inner.pos].to_vec()))
1618
0
    }
1619
1620
    /// Reads a DER object as raw bytes. Tag and length are included
1621
    /// in the returned buffer. For indefinite length encoding, EOC bytes
1622
    /// are included in the returned buffer as well.
1623
    ///
1624
    /// # Examples
1625
    ///
1626
    /// ```
1627
    /// use yasna;
1628
    /// let data = b"\x04\x06Hello!";
1629
    /// let res = yasna::parse_der(data, |reader| reader.read_der()).unwrap();
1630
    /// assert_eq!(res, data);
1631
    /// ```
1632
0
    pub fn read_der(self) -> ASN1Result<Vec<u8>> {
1633
0
        Ok(self.inner.read_with_buffer(|inner| {
1634
0
            inner.skip_general()
1635
0
        })?.1.to_owned())
1636
0
    }
1637
}
1638
1639
/// A reader object for a sequence of BER/DER-encoded ASN.1 data.
1640
///
1641
/// The main source of this object is the [`read_sequence`] method from
1642
/// [`BERReader`].
1643
///
1644
/// [`read_sequence`]: BERReader::read_sequence
1645
///
1646
/// # Examples
1647
///
1648
/// ```
1649
/// use yasna;
1650
/// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
1651
/// let asn = yasna::parse_der(data, |reader| {
1652
///     reader.read_sequence(|reader| {
1653
///         let i = reader.next().read_i64()?;
1654
///         let b = reader.next().read_bool()?;
1655
///         return Ok((i, b));
1656
///     })
1657
/// }).unwrap();
1658
/// assert_eq!(asn, (10, true));
1659
/// ```
1660
#[derive(Debug)]
1661
pub struct BERReaderSeq<'a, 'b> where 'a: 'b {
1662
    inner: &'b mut BERReaderImpl<'a>,
1663
}
1664
1665
impl<'a, 'b> BERReaderSeq<'a, 'b> {
1666
    /// Tells which format we are parsing, BER or DER.
1667
0
    pub fn mode(&self) -> BERMode {
1668
0
        self.inner.mode
1669
0
    }
1670
1671
    /// Generates a new [`BERReader`].
1672
0
    pub fn next<'c>(&'c mut self) -> BERReader<'a, 'c> {
1673
0
        BERReader::new(self.inner)
1674
0
    }
1675
1676
    /// Tries to read an ASN.1 value. If it fails at the first tag,
1677
    /// it doesn't consume buffer and returns `None`.
1678
    ///
1679
    /// Used to parse OPTIONAL elements.
1680
    ///
1681
    /// # Examples
1682
    ///
1683
    /// ```
1684
    /// use yasna;
1685
    /// let data = &[48, 3, 1, 1, 255];
1686
    /// let asn = yasna::parse_der(data, |reader| {
1687
    ///     reader.read_sequence(|reader| {
1688
    ///         let i = reader.read_optional(|reader| {
1689
    ///             reader.read_i64()
1690
    ///         })?;
1691
    ///         let b = reader.next().read_bool()?;
1692
    ///         return Ok((i, b));
1693
    ///     })
1694
    /// }).unwrap();
1695
    /// assert_eq!(asn, (None, true));
1696
    /// ```
1697
0
    pub fn read_optional<T, F>(&mut self, callback: F)
1698
0
            -> ASN1Result<Option<T>>
1699
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1700
0
        self.inner.read_optional(|inner| {
1701
0
            callback(BERReader::new(inner))
1702
0
        })
1703
0
    }
1704
1705
    /// Similar to [`read_optional`](Self::read_optional),
1706
    /// but uses `default` if it fails.
1707
    ///
1708
    /// `T: Eq` is required because it fails in DER mode if the read value
1709
    /// is equal to `default`.
1710
    ///
1711
    /// Used to parse DEFAULT elements.
1712
    ///
1713
    /// # Examples
1714
    ///
1715
    /// ```
1716
    /// use yasna;
1717
    /// let data = &[48, 3, 1, 1, 255];
1718
    /// let asn = yasna::parse_der(data, |reader| {
1719
    ///     reader.read_sequence(|reader| {
1720
    ///         let i = reader.read_default(10, |reader| {
1721
    ///             reader.read_i64()
1722
    ///         })?;
1723
    ///         let b = reader.next().read_bool()?;
1724
    ///         return Ok((i, b));
1725
    ///     })
1726
    /// }).unwrap();
1727
    /// assert_eq!(asn, (10, true));
1728
    /// ```
1729
0
    pub fn read_default<T, F>(&mut self, default: T, callback: F)
1730
0
            -> ASN1Result<T>
1731
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T>,
1732
0
            T: Eq {
1733
0
        match self.read_optional(callback)? {
1734
0
            Some(result) => {
1735
0
                if self.inner.mode == BERMode::Der && result == default {
1736
0
                    return Err(
1737
0
                        ASN1Error::new(ASN1ErrorKind::Invalid));
1738
0
                }
1739
0
                return Ok(result);
1740
            },
1741
0
            None => Ok(default),
1742
        }
1743
0
    }
1744
1745
0
    pub fn read_with_buffer<T, F>(&mut self, callback: F)
1746
0
            -> ASN1Result<(T, &'a [u8])>
1747
0
            where F: for<'c> FnOnce(
1748
0
                &mut BERReaderSeq<'a, 'c>) -> ASN1Result<T> {
1749
0
        self.inner.read_with_buffer(|inner| {
1750
0
            callback(&mut BERReaderSeq { inner, })
1751
0
        })
1752
0
    }
1753
}
1754
1755
/// A reader object for a set of BER/DER-encoded ASN.1 data.
1756
///
1757
/// The main source of this object is the [`read_set`](BERReader::read_set)
1758
/// method from [`BERReader`].
1759
///
1760
/// # Examples
1761
///
1762
/// ```
1763
/// use yasna;
1764
/// use yasna::tags::{TAG_INTEGER,TAG_BOOLEAN};
1765
/// let data = &[49, 6, 1, 1, 255, 2, 1, 10];
1766
/// let asn = yasna::parse_der(data, |reader| {
1767
///     reader.read_set(|reader| {
1768
///         let i = reader.next(&[TAG_INTEGER])?.read_i64()?;
1769
///         let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1770
///         return Ok((i, b));
1771
///     })
1772
/// }).unwrap();
1773
/// assert_eq!(asn, (10, true));
1774
/// ```
1775
#[derive(Debug)]
1776
pub struct BERReaderSet<'a, 'b> where 'a: 'b {
1777
    impl_ref: &'b mut BERReaderImpl<'a>,
1778
    elements: &'b mut Vec<(Tag, &'a [u8], usize)>,
1779
}
1780
1781
impl<'a, 'b> BERReaderSet<'a, 'b> {
1782
    /// Tells which format we are parsing, BER or DER.
1783
0
    pub fn mode(&self) -> BERMode {
1784
0
        self.impl_ref.mode
1785
0
    }
1786
1787
    /// Generates a new [`BERReader`].
1788
    ///
1789
    /// This method needs `tag_hint` to determine the position of the data.
1790
0
    pub fn next<'c>(&'c mut self, tag_hint: &[Tag])
1791
0
            -> ASN1Result<BERReader<'a, 'c>> {
1792
0
        if let Some(elem_pos) = self.elements.iter().position(|&(tag,_,_)| {
1793
0
            tag_hint.contains(&tag)
1794
0
        }) {
1795
0
            let (_, buf, pos) = self.elements.remove(elem_pos);
1796
0
            *self.impl_ref = BERReaderImpl::with_pos(
1797
0
                buf, pos, self.impl_ref.mode);
1798
0
            return Ok(BERReader::new(self.impl_ref))
1799
        } else {
1800
0
            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1801
        }
1802
0
    }
1803
1804
    /// If there is a set element with a tag in `tag_hint`, reads an ASN.1
1805
    /// value from that element and returns `Some(_)`.
1806
    /// Otherwise, returns `None`.
1807
    ///
1808
    /// Used to parse OPTIONAL elements.
1809
    ///
1810
    /// # Examples
1811
    ///
1812
    /// ```
1813
    /// use yasna;
1814
    /// use yasna::tags::*;
1815
    /// let data = &[49, 3, 1, 1, 255];
1816
    /// let asn = yasna::parse_der(data, |reader| {
1817
    ///     reader.read_set(|reader| {
1818
    ///         let i = reader.read_optional(&[TAG_INTEGER], |reader| {
1819
    ///             reader.read_i64()
1820
    ///         })?;
1821
    ///         let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1822
    ///         return Ok((i, b));
1823
    ///     })
1824
    /// }).unwrap();
1825
    /// assert_eq!(asn, (None, true));
1826
    /// ```
1827
0
    pub fn read_optional<T, F>(&mut self, tag_hint: &[Tag], callback: F)
1828
0
            -> ASN1Result<Option<T>>
1829
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1830
0
        if let Some(elem_pos) = self.elements.iter().position(|&(tag,_,_)| {
1831
0
            tag_hint.contains(&tag)
1832
0
        }) {
1833
0
            let (_, buf, pos) = self.elements.remove(elem_pos);
1834
0
            let mut reader_impl = BERReaderImpl::with_pos(
1835
0
                buf, pos, self.impl_ref.mode);
1836
0
            let result = callback(BERReader::new(&mut reader_impl))?;
1837
0
            reader_impl.end_of_buf()?;
1838
0
            return Ok(Some(result));
1839
        } else {
1840
0
            return Ok(None);
1841
        }
1842
0
    }
1843
1844
    /// Similar to [`read_optional`](Self::read_optional),
1845
    /// but uses `default` if it fails.
1846
    ///
1847
    /// `T: Eq` is required because it fails in DER mode if the read value
1848
    /// is equal to `default`.
1849
    ///
1850
    /// Used to parse DEFAULT elements.
1851
    ///
1852
    /// # Examples
1853
    ///
1854
    /// ```
1855
    /// use yasna;
1856
    /// use yasna::tags::*;
1857
    /// let data = &[49, 3, 1, 1, 255];
1858
    /// let asn = yasna::parse_der(data, |reader| {
1859
    ///     reader.read_set(|reader| {
1860
    ///         let i = reader.read_default(&[TAG_INTEGER], 10, |reader| {
1861
    ///             reader.read_i64()
1862
    ///         })?;
1863
    ///         let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1864
    ///         return Ok((i, b));
1865
    ///     })
1866
    /// }).unwrap();
1867
    /// assert_eq!(asn, (10, true));
1868
    /// ```
1869
0
    pub fn read_default<T, F>
1870
0
            (&mut self, tag_hint: &[Tag], default: T, callback: F)
1871
0
            -> ASN1Result<T>
1872
0
            where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T>,
1873
0
            T: Eq {
1874
0
        let mode = self.impl_ref.mode;
1875
0
        match self.read_optional(tag_hint, callback)? {
1876
0
            Some(result) => {
1877
0
                if mode == BERMode::Der && result == default {
1878
0
                    return Err(
1879
0
                        ASN1Error::new(ASN1ErrorKind::Invalid));
1880
0
                }
1881
0
                return Ok(result);
1882
            },
1883
0
            None => Ok(default),
1884
        }
1885
0
    }
1886
}
1887
1888
1889
#[cfg(test)]
1890
mod tests;