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
//! Iterative BER OCTET STRING views with source spans and retained accounting.
use crate::{Error, ErrorCode, Result};
use structured_asn1::memory::{OwnedVec, Work};
use structured_asn1::{Element, Parser, Reader, Span, Tag, universal};
/// One original content range, excluding ASN.1 tag and length octets.
#[derive(Debug, Clone, Copy)]
pub struct Piece<'a> {
bytes: &'a [u8],
span: Span,
}
impl<'a> Piece<'a> {
/// The original content bytes; no join or re-encoding is performed.
#[must_use]
pub fn as_bytes(self) -> &'a [u8] {
self.bytes
}
/// The content's original document range.
#[must_use]
pub fn span(self) -> Span {
self.span
}
}
#[derive(Debug)]
enum Storage<'a> {
One([Piece<'a>; 1]),
Many(OwnedVec<Piece<'a>>),
}
/// Borrowed logical octets with independently accounted segment metadata.
///
/// Primitive content stays inline and allocates no catalogue. Constructed BER
/// content retains its original disjoint ranges, flattened only as metadata.
/// The catalogue can outlive the producing reader; its bytes remain borrowed.
#[derive(Debug)]
pub struct Octets<'a> {
parser: &'a Parser,
outer_depth: u32,
carrier: Span,
contents: Span,
storage: Storage<'a>,
length: usize,
field: &'static str,
}
impl<'a> Octets<'a> {
/// Reads logical `IA5String` contents through the SAME iterative base-string
/// walker. BER constructed strings carry OCTET STRING fragments (X.690
/// ยง8.23.3); DER remains primitive. ASCII validation is admitted before every
/// content scan, and original fragment spans are preserved without joining.
/// <https://www.itu.int/rec/T-REC-X.690-202102-I/en>
pub fn read_ia5(
parent: &Reader<'a>,
element: &Element<'a>,
field: &'static str,
) -> Result<Self> {
parent
.charge(1)
.map_err(|cause| Error::encoding(cause, field))?;
let value = Self::read_tagged(parent, element, universal::IA5_STRING, false, field)?;
let execution = parent.execution();
for piece in value.pieces() {
execution
.charge_work(1 + piece.as_bytes().len() as u64)
.map_err(|cause| Error::resource(cause, field, piece.span().start))?;
if !piece.as_bytes().is_ascii() {
return Err(Error::schema(
ErrorCode::MalformedValue,
field,
piece.span().start,
));
}
}
Ok(value)
}
/// Reads an OCTET STRING using the original parser's encoding and ceilings.
///
/// X.690 ยง8.7 permits constructed BER strings composed of OCTET STRING
/// fragments. The iterative traversal preserves inherited depth and source
/// positions, admitting frame/catalogue growth before allocation. A DER
/// reader still refuses constructed forms under its own encoding contract.
/// <https://www.itu.int/rec/T-REC-X.690-202102-I/en>
pub fn read(parent: &Reader<'a>, element: &Element<'a>, field: &'static str) -> Result<Self> {
Self::read_tagged(parent, element, universal::OCTET_STRING, false, field)
}
/// Reads `[0] IMPLICIT OCTET STRING`, the CMS subject-key identifier.
///
/// Only the outer tag is replaced; constructed children remain universal
/// OCTET STRINGs (X.690 ยงยง8.7, 8.14). Both forms use the same segment walker.
pub(crate) fn read_identifier(
parent: &Reader<'a>,
element: &Element<'a>,
field: &'static str,
) -> Result<Self> {
Self::read_tagged(parent, element, 0, true, field)
}
fn read_tagged(
parent: &Reader<'a>,
element: &Element<'a>,
outer_number: u32,
context: bool,
field: &'static str,
) -> Result<Self> {
let primitive = if context {
Tag::context(false, outer_number)
} else {
Tag::primitive(outer_number)
};
let constructed = if context {
Tag::context(true, outer_number)
} else {
Tag::constructed(outer_number)
};
if element.tag() == primitive {
return Ok(Self {
parser: parent.parser(),
outer_depth: parent.depth(),
carrier: element.span(),
contents: element.contents_span(),
storage: Storage::One([Piece {
bytes: element.contents(),
span: element.contents_span(),
}]),
length: element.contents().len(),
field,
});
}
if element.tag() != constructed {
return Err(Error::schema(
ErrorCode::UnexpectedTag,
field,
element.span().start,
));
}
if parent.encoding().is_der() {
return Err(Error::schema(
ErrorCode::UnexpectedTag,
field,
element.span().start,
));
}
let execution = parent.execution();
let mut pieces = execution.vector();
let mut frames = execution.vector();
frames
.try_push(
parent
.enter(element)
.map_err(|error| Error::encoding(error, field))?,
)
.map_err(|reason| Error::resource(reason, field, element.span().start))?;
let mut length = 0_usize;
while let Some(reader) = frames.last_mut() {
let Some(child) = reader
.next_element()
.map_err(|error| Error::encoding(error, field))?
else {
frames.pop();
continue;
};
// Only the OUTER tag changes: X.690 ยง8.23.3 defines restricted
// strings as [UNIVERSAL x] IMPLICIT OCTET STRING. Its ยง8.23.5.4
// example encodes constructed VisibleString with child tag 04,
// not another VisibleString. IA5String follows the same rule:
// 36 03 04 01 61 is valid; 36 03 16 01 61 is not.
// https://www.itu.int/rec/T-REC-X.690-202102-I/en
if child.tag() == Tag::primitive(universal::OCTET_STRING) {
length = length.checked_add(child.contents().len()).ok_or_else(|| {
Error::schema(ErrorCode::LengthOverflow, field, child.span().start)
})?;
pieces
.try_push(Piece {
bytes: child.contents(),
span: child.contents_span(),
})
.map_err(|reason| Error::resource(reason, field, child.span().start))?;
} else if child.tag() == Tag::constructed(universal::OCTET_STRING) {
let nested = reader
.enter(&child)
.map_err(|error| Error::encoding(error, field))?;
frames
.try_push(nested)
.map_err(|reason| Error::resource(reason, field, child.span().start))?;
} else {
return Err(Error::schema(
ErrorCode::UnexpectedTag,
field,
child.span().start,
));
}
}
Ok(Self {
parser: parent.parser(),
outer_depth: parent.depth(),
carrier: element.span(),
contents: element.contents_span(),
storage: Storage::Many(pieces.into_owned()),
length,
field,
})
}
/// The original primitive content ranges in logical order.
#[must_use]
pub fn pieces(&self) -> &[Piece<'a>] {
match &self.storage {
Storage::One(piece) => piece,
Storage::Many(pieces) => pieces,
}
}
/// The logical octet count, recorded during parsing without a later scan.
#[must_use]
pub fn len(&self) -> usize {
self.length
}
/// Whether the logical content is empty, including constructed empty input.
#[must_use]
pub fn is_empty(&self) -> bool {
self.length == 0
}
/// The original whole carrying element, including its tag and length.
#[must_use]
pub fn span(&self) -> Span {
self.carrier
}
pub(crate) fn content_span(&self) -> Span {
self.contents
}
pub(crate) fn outer_depth(&self) -> u32 {
self.outer_depth
}
pub(crate) fn parser(&self) -> &'a Parser {
self.parser
}
/// The borrowed bytes when the logical value occupies one original range.
#[must_use]
pub fn as_one(&self) -> Option<&'a [u8]> {
match self.pieces() {
[piece] => Some(piece.bytes),
_ => None,
}
}
/// Copies logical content into independently retained accounted storage.
///
/// This is an explicit materialization; inspection can keep using borrowed
/// ranges, and an already owned result should be moved instead of copied.
/// The original producing session is required before any admission or scan.
/// Metadata traversal, exact capacity and each copy use both its local and
/// current aggregate ceilings. The result retains charge after reader drop.
/// `field` and `at` locate the actual enclosing operation, including an
/// empty constructed value. Refusal releases partial output, not the source.
pub fn copy_in(
&self,
parent: &Reader<'_>,
field: &'static str,
at: u64,
) -> Result<OwnedVec<u8>> {
if !core::ptr::eq(self.parser, parent.parser()) {
return Err(Error::pkix(structured_pkix::Error::new(
structured_pkix::ErrorCode::ForeignReader,
field,
at,
)));
}
let execution = parent.execution();
let refusal = |reason| Error::resource(reason, field, at);
execution
.charge_work(self.pieces().len() as u64)
.map_err(refusal)?;
let mut output = execution.vector();
// The logical length was checked during the one structural traversal.
output.try_reserve_exact(self.length).map_err(refusal)?;
for piece in self.pieces() {
output.try_extend_from_slice(piece.bytes).map_err(refusal)?;
}
Ok(output.into_owned())
}
pub(crate) fn same_value(
&self,
other: &Octets<'_>,
parent: &Reader<'_>,
field: &'static str,
at: u64,
) -> Result<bool> {
let execution = parent.execution();
execution
.charge_work(1)
.map_err(|reason| Error::resource(reason, field, at))?;
if self.length != other.length {
return Ok(false);
}
for amount in [self.pieces().len(), other.pieces().len(), self.length] {
execution
.charge_work(amount as u64)
.map_err(|reason| Error::resource(reason, field, at))?;
}
Ok(self
.pieces()
.iter()
.flat_map(|piece| piece.bytes.iter())
.eq(other.pieces().iter().flat_map(|piece| piece.bytes.iter())))
}
}
/// Why feeding attached ranges could not finish.
#[derive(Debug)]
pub enum SourceError {
/// Metadata traversal refused the current operation's resources.
Processing(Error),
/// The stream driver refused a chunk and retains its original cause.
Receiver(crate::stream::Refused),
}
impl crate::stream::Source for &Octets<'_> {
type Error = SourceError;
fn stream<W: Work>(
&mut self,
receiver: &mut impl crate::stream::Receiver,
execution: &W,
) -> core::result::Result<(), Self::Error> {
for piece in self.pieces() {
execution.charge_work(1).map_err(|reason| {
SourceError::Processing(Error::resource(reason, self.field, piece.span.start))
})?;
receiver.write(piece.bytes).map_err(SourceError::Receiver)?;
}
Ok(())
}
}