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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::ber::*;
use crate::der_constraint_fail_if;
use crate::error::*;
#[cfg(feature = "std")]
use crate::ToDer;
use crate::{Class, DynTagged, FromBer, FromDer, Length, Tag, ToStatic};
use alloc::borrow::Cow;
use core::convert::TryFrom;
use nom::bytes::streaming::take;
#[derive(Clone, Debug)]
pub struct Header<'a> {
pub(crate) class: Class,
pub(crate) constructed: bool,
pub(crate) tag: Tag,
pub(crate) length: Length,
pub(crate) raw_tag: Option<Cow<'a, [u8]>>,
}
impl<'a> Header<'a> {
pub const fn new(class: Class, constructed: bool, tag: Tag, length: Length) -> Self {
Header {
tag,
constructed,
class,
length,
raw_tag: None,
}
}
#[inline]
pub const fn new_simple(tag: Tag) -> Self {
let constructed = matches!(tag, Tag::Sequence | Tag::Set);
Self::new(Class::Universal, constructed, tag, Length::Definite(0))
}
#[inline]
pub fn with_class(self, class: Class) -> Self {
Self { class, ..self }
}
#[inline]
pub fn with_constructed(self, constructed: bool) -> Self {
Self {
constructed,
..self
}
}
#[inline]
pub fn with_tag(self, tag: Tag) -> Self {
Self { tag, ..self }
}
#[inline]
pub fn with_length(self, length: Length) -> Self {
Self { length, ..self }
}
#[inline]
pub fn with_raw_tag(self, raw_tag: Option<Cow<'a, [u8]>>) -> Self {
Header { raw_tag, ..self }
}
#[inline]
pub const fn class(&self) -> Class {
self.class
}
#[inline]
pub const fn constructed(&self) -> bool {
self.constructed
}
#[inline]
pub const fn tag(&self) -> Tag {
self.tag
}
#[inline]
pub const fn length(&self) -> Length {
self.length
}
#[inline]
pub fn raw_tag(&self) -> Option<&[u8]> {
self.raw_tag.as_ref().map(|cow| cow.as_ref())
}
#[inline]
pub const fn is_primitive(&self) -> bool {
!self.constructed
}
#[inline]
pub const fn is_constructed(&self) -> bool {
self.constructed
}
#[inline]
pub const fn assert_class(&self, class: Class) -> Result<()> {
self.class.assert_eq(class)
}
#[inline]
pub const fn assert_tag(&self, tag: Tag) -> Result<()> {
self.tag.assert_eq(tag)
}
#[inline]
pub const fn assert_primitive(&self) -> Result<()> {
if self.is_primitive() {
Ok(())
} else {
Err(Error::ConstructUnexpected)
}
}
#[inline]
pub const fn assert_constructed(&self) -> Result<()> {
if !self.is_primitive() {
Ok(())
} else {
Err(Error::ConstructExpected)
}
}
#[inline]
pub const fn is_universal(&self) -> bool {
self.class as u8 == Class::Universal as u8
}
#[inline]
pub const fn is_application(&self) -> bool {
self.class as u8 == Class::Application as u8
}
#[inline]
pub const fn is_contextspecific(&self) -> bool {
self.class as u8 == Class::ContextSpecific as u8
}
#[inline]
pub const fn is_private(&self) -> bool {
self.class as u8 == Class::Private as u8
}
#[inline]
pub const fn assert_definite(&self) -> Result<()> {
if self.length.is_definite() {
Ok(())
} else {
Err(Error::DerConstraintFailed(DerConstraint::IndefiniteLength))
}
}
#[inline]
pub fn parse_ber_content<'i>(&'_ self, i: &'i [u8]) -> ParseResult<'i, &'i [u8]> {
ber_get_object_content(i, self, 8)
}
#[inline]
pub fn parse_der_content<'i>(&'_ self, i: &'i [u8]) -> ParseResult<'i, &'i [u8]> {
self.assert_definite()?;
ber_get_object_content(i, self, 8)
}
}
impl From<Tag> for Header<'_> {
#[inline]
fn from(tag: Tag) -> Self {
let constructed = matches!(tag, Tag::Sequence | Tag::Set);
Self::new(Class::Universal, constructed, tag, Length::Definite(0))
}
}
impl<'a> ToStatic for Header<'a> {
type Owned = Header<'static>;
fn to_static(&self) -> Self::Owned {
let raw_tag: Option<Cow<'static, [u8]>> =
self.raw_tag.as_ref().map(|b| Cow::Owned(b.to_vec()));
Header {
tag: self.tag,
constructed: self.constructed,
class: self.class,
length: self.length,
raw_tag,
}
}
}
impl<'a> FromBer<'a> for Header<'a> {
fn from_ber(bytes: &'a [u8]) -> ParseResult<Self> {
let (i1, el) = parse_identifier(bytes)?;
let class = match Class::try_from(el.0) {
Ok(c) => c,
Err(_) => unreachable!(),
};
let (i2, len) = parse_ber_length_byte(i1)?;
let (i3, len) = match (len.0, len.1) {
(0, l1) => {
(i2, Length::Definite(usize::from(l1)))
}
(_, 0) => {
if el.1 == 0 {
return Err(nom::Err::Error(Error::ConstructExpected));
}
(i2, Length::Indefinite)
}
(_, l1) => {
if l1 == 0b0111_1111 {
return Err(::nom::Err::Error(Error::InvalidLength));
}
let (i3, llen) = take(l1)(i2)?;
match bytes_to_u64(llen) {
Ok(l) => {
let l =
usize::try_from(l).or(Err(::nom::Err::Error(Error::InvalidLength)))?;
(i3, Length::Definite(l))
}
Err(_) => {
return Err(::nom::Err::Error(Error::InvalidLength));
}
}
}
};
let constructed = el.1 != 0;
let hdr = Header::new(class, constructed, Tag(el.2), len).with_raw_tag(Some(el.3.into()));
Ok((i3, hdr))
}
}
impl<'a> FromDer<'a> for Header<'a> {
fn from_der(bytes: &'a [u8]) -> ParseResult<Self> {
let (i1, el) = parse_identifier(bytes)?;
let class = match Class::try_from(el.0) {
Ok(c) => c,
Err(_) => unreachable!(),
};
let (i2, len) = parse_ber_length_byte(i1)?;
let (i3, len) = match (len.0, len.1) {
(0, l1) => {
(i2, Length::Definite(usize::from(l1)))
}
(_, 0) => {
return Err(::nom::Err::Error(Error::DerConstraintFailed(
DerConstraint::IndefiniteLength,
)));
}
(_, l1) => {
if l1 == 0b0111_1111 {
return Err(::nom::Err::Error(Error::InvalidLength));
}
der_constraint_fail_if!(
&i[1..],
len.1 == 0 && el.1 != 1,
DerConstraint::NotConstructed
);
let (i3, llen) = take(l1)(i2)?;
match bytes_to_u64(llen) {
Ok(l) => {
let l =
usize::try_from(l).or(Err(::nom::Err::Error(Error::InvalidLength)))?;
(i3, Length::Definite(l))
}
Err(_) => {
return Err(::nom::Err::Error(Error::InvalidLength));
}
}
}
};
let constructed = el.1 != 0;
let hdr = Header::new(class, constructed, Tag(el.2), len).with_raw_tag(Some(el.3.into()));
Ok((i3, hdr))
}
}
impl DynTagged for (Class, bool, Tag) {
fn tag(&self) -> Tag {
self.2
}
}
#[cfg(feature = "std")]
impl ToDer for (Class, bool, Tag) {
fn to_der_len(&self) -> Result<usize> {
let (_, _, tag) = self;
match tag.0 {
0..=30 => Ok(1),
t => {
let mut sz = 1;
let mut val = t;
loop {
if val <= 127 {
return Ok(sz + 1);
} else {
val >>= 7;
sz += 1;
}
}
}
}
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let (class, constructed, tag) = self;
let b0 = (*class as u8) << 6;
let b0 = b0 | if *constructed { 0b10_0000 } else { 0 };
if tag.0 > 30 {
let b0 = b0 | 0b1_1111;
let mut sz = writer.write(&[b0])?;
let mut val = tag.0;
loop {
if val <= 127 {
sz += writer.write(&[val as u8])?;
return Ok(sz);
} else {
let b = (val & 0b0111_1111) as u8 | 0b1000_0000;
sz += writer.write(&[b])?;
val >>= 7;
}
}
} else {
let b0 = b0 | (tag.0 as u8);
let sz = writer.write(&[b0])?;
Ok(sz)
}
}
fn write_der_content(&self, _writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
Ok(0)
}
}
impl DynTagged for Header<'_> {
fn tag(&self) -> Tag {
self.tag
}
}
#[cfg(feature = "std")]
impl ToDer for Header<'_> {
fn to_der_len(&self) -> Result<usize> {
let tag_len = (self.class, self.constructed, self.tag).to_der_len()?;
let len_len = self.length.to_der_len()?;
Ok(tag_len + len_len)
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let sz = (self.class, self.constructed, self.tag).write_der_header(writer)?;
let sz = sz + self.length.write_der_header(writer)?;
Ok(sz)
}
fn write_der_content(&self, _writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
Ok(0)
}
fn write_der_raw(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let sz = match &self.raw_tag {
Some(t) => writer.write(t)?,
None => (self.class, self.constructed, self.tag).write_der_header(writer)?,
};
let sz = sz + self.length.write_der_header(writer)?;
Ok(sz)
}
}
impl<'a> PartialEq<Header<'a>> for Header<'a> {
fn eq(&self, other: &Header) -> bool {
self.class == other.class
&& self.tag == other.tag
&& self.constructed == other.constructed
&& {
if self.length.is_null() && other.length.is_null() {
self.length == other.length
} else {
true
}
}
&& {
if self.raw_tag.as_ref().xor(other.raw_tag.as_ref()).is_none() {
self.raw_tag == other.raw_tag
} else {
true
}
}
}
}
impl Eq for Header<'_> {}
#[cfg(test)]
mod tests {
use crate::*;
use hex_literal::hex;
#[test]
fn methods_header() {
let input = &hex! {"02 01 00"};
let (rem, header) = Header::from_ber(input).expect("parsing header failed");
assert_eq!(header.class(), Class::Universal);
assert_eq!(header.tag(), Tag::Integer);
assert!(header.assert_primitive().is_ok());
assert!(header.assert_constructed().is_err());
assert!(header.is_universal());
assert!(!header.is_application());
assert!(!header.is_private());
assert_eq!(rem, &input[2..]);
let hdr2 = Header::new_simple(Tag::Integer);
assert_eq!(header, hdr2);
let hdr3 = hdr2
.with_class(Class::ContextSpecific)
.with_constructed(true)
.with_length(Length::Definite(1));
assert!(hdr3.constructed());
assert!(hdr3.is_constructed());
assert!(hdr3.assert_constructed().is_ok());
assert!(hdr3.is_contextspecific());
let xx = hdr3.to_der_vec().expect("serialize failed");
assert_eq!(&xx, &[0xa2, 0x01]);
let hdr4 = hdr3.with_length(Length::Indefinite);
assert!(hdr4.assert_definite().is_err());
let xx = hdr4.to_der_vec().expect("serialize failed");
assert_eq!(&xx, &[0xa2, 0x80]);
let hdr = Header::new_simple(Tag(2)).with_length(Length::Definite(1));
let (_, r) = hdr.parse_ber_content(&input[2..]).unwrap();
assert_eq!(r, &input[2..]);
let (_, r) = hdr.parse_der_content(&input[2..]).unwrap();
assert_eq!(r, &input[2..]);
}
}