rpki 0.19.3

A library for validating and creating RPKI data.
Documentation
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

use std::{error, fmt, io, str};
use std::borrow::Cow;
use bytes::Bytes;
use quick_xml::encoding::EncodingError;
use quick_xml::events::{BytesStart, Event};
use quick_xml::events::attributes::AttrError;
use quick_xml::name::{Namespace, NamespaceError};
use crate::util::base64;


//------------ Reader --------------------------------------------------------

/// An XML reader.
///
/// This struct holds all state necessary for parsing an XML document.
pub struct Reader<R: io::BufRead> {
    reader: quick_xml::NsReader<BufReadCounter<R>>,
    buf: Vec<u8>,
}

impl<R: io::BufRead> Reader<R> {
    /// Creates a new reader from an underlying reader.
    pub fn new(reader: R) -> Self {
        let reader = BufReadCounter::new(reader);
        let mut reader = quick_xml::NsReader::from_reader(reader);
        reader.config_mut().trim_text(true);
        Reader {
            reader,
            buf: Vec::new(),
        }
    }

    pub fn reset_and_limit(&mut self, limit: u64) {
        self.reader.get_mut().reset();
        self.reader.get_mut().limit(limit);
    }

    /// Parse the start of the document.
    ///
    /// This is like `Content::take_element` except that it also happily
    /// skips over XML and doctype declarations.
    pub fn start<F, E>(&mut self, op: F) -> Result<Content, E>
    where F: FnOnce(Element) -> Result<(), E>, E: From<Error> {
        loop {
            self.buf.clear();
            let (ns, event) = self.reader.read_resolved_event_into(
                &mut self.buf,
            ).map_err(Into::into)?;
            let ns = ns.try_into().map_err(Into::into)?;
            match event {
                Event::Start(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(
                        Content { empty: false }
                    )
                }
                Event::Empty(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(
                        Content { empty: true }
                    )
                }
                Event::Comment(_) | Event::Decl(_) | Event::DocType(_) => { }
                _ => return Err(Error::Malformed.into())
            }
        }
    }

    pub fn start_with_limit<F, E>(
        &mut self, op: F, limit: u64) -> Result<Content, E>
    where F: FnOnce(Element) -> Result<(), E>, E: From<Error> {
        self.reset_and_limit(limit);
        self.start(op)
    }

    /// Parse the end of the document.
    ///
    /// This checks that the next non-comment event to be the end of file.
    pub fn end(&mut self) -> Result<(), Error> {
        loop {
            self.buf.clear();
            match self.reader.read_event_into(&mut self.buf)? {
                Event::Eof => return Ok(()),
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed)
            }
        }
    }
}


//------------ Element -------------------------------------------------------

/// The start of an element.
pub struct Element<'b, 'n> {
    start: BytesStart<'b>,
    ns: Option<Namespace<'n>>,
}

impl<'b, 'n> Element<'b, 'n> {
    /// Creates a new value from the underlying components.
    fn new(start: BytesStart<'b>, ns: Option<Namespace<'n>>) -> Self {
        Element { start, ns, }
    }

    /// Returns the name of the element.
    pub fn name(&self) -> Name<'_, '_> {
        Name::new(
            self.ns.map(|ns| ns.0),
            self.start.local_name().into_inner()
        )
    }

    /// Processes the attributes of the element.
    ///
    /// We don’t support qualified attributes. Any namespace prefixes in
    /// attribute names will lead to an error.
    pub fn attributes<F, E>(&self, mut op: F) -> Result<(), E>
    where
        F: FnMut(&[u8], AttrValue) -> Result<(), E>,
        E: From<Error>
    {
        for attr in self.start.attributes() {
            let attr = attr.map_err(Into::into)?;
            if attr.key.as_namespace_binding().is_some() {
                continue
            }
            if let Some(prefix) = attr.key.prefix() {
                return Err(E::from(
                    Error::Xml(quick_xml::Error::Namespace(
                        quick_xml::name::NamespaceError::UnknownPrefix(
                            prefix.as_ref().into()
                        )
                    ))
                ))
            }
            op(attr.key.local_name().as_ref(), AttrValue(attr))?;
        }
        Ok(())
    }
}


//------------ Content -------------------------------------------------------

pub struct Content {
    empty: bool
}

impl Content {
    pub fn take_element<R, F, E>(
        &self,
        reader: &mut Reader<R>,
        op: F
    ) -> Result<Content, E>
    where R: io::BufRead, F: FnOnce(Element) -> Result<(), E>, E: From<Error> {
        if self.empty {
            return Err(Error::Malformed.into())
        }

        loop {
            reader.buf.clear();
            let (ns, event) = reader.reader.read_resolved_event_into(
                &mut reader.buf
            ).map_err(Into::into)?;
            let ns = ns.try_into().map_err(Into::into)?;
            match event {
                Event::Start(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(
                        Content { empty: false }
                    )
                }
                Event::Empty(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(
                        Content { empty: false }
                    )
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed.into())
            }
        }
    }

    pub fn take_element_with_limit<R, F, E>(
        &self,
        reader: &mut Reader<R>,
        op: F,
        limit: u64
    ) -> Result<Content, E>
    where R: io::BufRead, F: FnOnce(Element) -> Result<(), E>, E: From<Error> {
        reader.reset_and_limit(limit);

        self.take_element(reader, op)
    }

    pub fn take_opt_element<R, F, E>(
        &mut self,
        reader: &mut Reader<R>,
        op: F
    ) -> Result<Option<Content>, E>
    where
        R: io::BufRead,
        F: FnOnce(Element) -> Result<(), E>,
        E: From<Error>
    {
        if self.empty {
            return Ok(None)
        }

        loop {
            reader.buf.clear();
            let (ns, event) = reader.reader.read_resolved_event_into(
                &mut reader.buf
            ).map_err(Into::into)?;
            let ns = ns.try_into().map_err(Into::into)?;
            match event {
                Event::Start(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(Some(
                        Content { empty: false }
                    ))
                }
                Event::Empty(start) => {
                    op(Element::new(start, ns))?;
                    return Ok(Some(
                        Content { empty: true }
                    ))
                }
                Event::End(_) => {
                    self.empty = true;
                    return Ok(None)
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed.into())
            }
        }
    }

    pub fn take_opt_element_with_limit<R, F, E>(
        &mut self,
        reader: &mut Reader<R>,
        op: F,
        limit: u64
    ) -> Result<Option<Content>, E>
    where
        R: io::BufRead,
        F: FnOnce(Element) -> Result<(), E>,
        E: From<Error>
    {
        reader.reset_and_limit(limit);
        self.take_opt_element(reader, op)
    }

    pub fn take_text<R, F, T, E>(
        &mut self,
        reader: &mut Reader<R>,
        op: F
    ) -> Result<T, E>
    where
        R: io::BufRead,
        F: FnOnce(Text) -> Result<T, E>,
        E: From<Error>
    {
        if self.empty {
            return Err(Error::Malformed.into())
        }

        loop {
            reader.buf.clear();
            let event = reader.reader.read_event_into(
                &mut reader.buf
            ).map_err(Into::into)?;
            match event {
                Event::Text(text) => {
                    return op(Text(text))
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed.into())
            }
        }
    }

    pub fn take_text_with_limit<R, F, T, E>(
        &mut self,
        reader: &mut Reader<R>,
        op: F,
        limit: u64
    ) -> Result<T, E>
    where
        R: io::BufRead,
        F: FnOnce(Text) -> Result<T, E>,
        E: From<Error>
    {
        reader.reset_and_limit(limit);
        self.take_text(reader, op)
    }

    pub fn take_end<R: io::BufRead>(
        &mut self,
        reader: &mut Reader<R>
    ) -> Result<(), Error> {
        if self.empty {
            return Ok(())
        }

        loop {
            reader.buf.clear();
            match reader.reader.read_event_into(&mut reader.buf)? {
                Event::End(_) => {
                    self.empty = true;
                    return Ok(())
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed)
            }
        }
    }

    pub fn take_opt_final_text<R, F, T, E>(
        &mut self,
        reader: &mut Reader<R>,
        op: F
    ) -> Result<T, E>
    where
        R: io::BufRead,
        F: FnOnce(Option<Text>) -> Result<T, E>,
        E: From<Error>
    {
        if self.empty {
            return op(None)
        }

        loop {
            reader.buf.clear();
            let event = reader.reader.read_event_into(
                &mut reader.buf
            ).map_err(Into::into)?;
            match event {
                Event::Text(text) => {
                    let res = op(Some(Text(text)))?;
                    self.take_end(reader)?;
                    return Ok(res)
                }
                Event::End(_) => {
                    self.empty = true;
                    return op(None)
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed.into())
            }
        }
    }

    /// Skips an optional text element inside the reader.
    pub fn skip_opt_text<R>(
        &mut self,
        reader: &mut Reader<R>
    ) -> Result<(), Error>
    where
        R: io::BufRead,
    {
        if self.empty {
            return Ok(())
        }

        loop {
            reader.buf.clear();
            let event = reader.reader.read_event_into(
                &mut reader.buf
            )?;
            match event {
                Event::Text(_text) => {
                    self.take_end(reader)?;
                    return Ok(())
                }
                Event::End(_) => {
                    self.empty = true;
                    return Ok(())
                }
                Event::Comment(_) => { }
                _ => return Err(Error::Malformed)
            }
        }
    }
}


//------------ Name ----------------------------------------------------------

/// The name of a tag or attribute.
#[derive(Clone, Copy,Eq, Hash, PartialEq)]
pub struct Name<'n, 'l> {
    namespace: Option<&'n [u8]>,
    local: &'l [u8],
}

impl<'n, 'l> Name<'n, 'l> {
    /// Creates a new name from its components.
    fn new(namespace: Option<&'n [u8]>, local: &'l [u8]) -> Self {
        Name { namespace, local }
    }

    /// Creates a qualified name from a namespace and a local name.
    pub const fn qualified(namespace: &'n [u8], local: &'l [u8]) -> Self {
        Name {
            namespace: Some(namespace),
            local
        }
    }

    /// Creates an unqualified name from only a local name.
    pub const fn unqualified(local: &'l [u8]) -> Self {
        Name {
            namespace: None,
            local
        }
    }

    pub fn namespace(&self) -> Option<&[u8]> {
        self.namespace
    }

    pub fn local(&self) -> &[u8] {
        self.local
    }

    pub const fn into_unqualified(self) -> Name<'static, 'l> {
        Name::unqualified(self.local)
    }
}

impl fmt::Debug for Name<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Name(")?;
        if let Some(ns) = self.namespace {
            write!(f, "{}:", String::from_utf8_lossy(ns))?;
        }
        write!(f, "{}", String::from_utf8_lossy(self.local))
    }
}

impl<'l> From<&'l [u8]> for Name<'_, 'l> {
    fn from(local: &'l [u8]) -> Self {
        Name::unqualified(local)
    }
}

impl<'l> From<&'l str> for Name<'_, 'l> {
    fn from(local: &'l str) -> Self {
        Name::unqualified(local.as_bytes())
    }
}

impl<'n, 'l> From<(&'n [u8], &'l [u8])> for Name<'n, 'l> {
    fn from((namespace, local): (&'n [u8], &'l [u8])) -> Self {
        Name::qualified(namespace, local)
    }
}

impl<'n, 'l> From<(&'n str, &'l str)> for Name<'n, 'l> {
    fn from((namespace, local): (&'n str, &'l str)) -> Self {
        Name::qualified(namespace.as_bytes(), local.as_bytes())
    }
}


//------------ AttrValue -----------------------------------------------------

/// The value of an attribute.
#[derive(Clone)]
pub struct AttrValue<'a>(quick_xml::events::attributes::Attribute<'a>);

impl AttrValue<'_> {
    pub fn ascii_into<T: str::FromStr>(self) -> Result<T, Error> {
        let s = self.0.unescape_value()?;
        if !s.is_ascii() {
            return Err(Error::Malformed)
        }
        T::from_str(s.as_ref()).map_err(|_| Error::Malformed)
    }

    pub fn into_ascii_bytes(self) -> Result<Bytes, Error> {
        let s = self.0.unescape_value()?;
        if !s.is_ascii() {
            return Err(Error::Malformed)
        }
        Ok(s.into_owned().into())
    }
}


//------------ Text ----------------------------------------------------------

pub struct Text<'a>(quick_xml::events::BytesText<'a>);

impl Text<'_> {
    pub fn to_utf8(&self) -> Result<Cow<'_, str>, Error> {
        Ok(self.0.decode()?)
    }

    pub fn to_ascii(&self) -> Result<Cow<'_, str>, Error> {
        // XXX Shouldn’t this reject non-ASCII Unicode?
        Ok(self.0.decode()?)
    }

    pub fn base64_decode(&self) -> Result<Vec<u8>, Error> {
        base64::Xml.decode(
            self.to_utf8()?.as_ref()
        ).map_err(|_| Error::Malformed)
    }
}


//------------ BufReadCounter ------------------------------------------------

/// A simple BufRead passthrough proxy that acts as a "trip computer"
/// 
/// It keeps track of the amount of bytes read since it was last reset.
/// If a limit is set, it will return an IO error when attempting to read
/// past that limit.
struct BufReadCounter<R: io::BufRead> {
    reader: R,
    trip: u64,
    limit: u64,
}

impl<R: io::BufRead> BufReadCounter<R> {
    /// Create a new trip computer (resetting counter) for a BufRead.
    ///
    /// Acts transparently to the implementation of a BufRead below.
    pub fn new(reader: R) -> Self {
        BufReadCounter {
            reader,
            trip: 0,
            limit: 0
        }
    }

    /// Reset the amount of bytes read back to 0
    pub fn reset(&mut self) {
        self.trip = 0;
    }

    /// Set a limit or pass 0 to disable the limit to the maximum bytes to 
    /// read. This overrides the previous limit.
    pub fn limit(&mut self, limit: u64) {
        self.limit = limit;
    }
}

impl<R: io::BufRead> io::Read for BufReadCounter<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

impl<R: io::BufRead> io::BufRead for BufReadCounter<R> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        if self.limit > 0 && self.trip > self.limit {
            return Err(
                io::Error::other(
                    format!("Trip is over limit ({:?}/{:?})", 
                        &self.trip, &self.limit))
            );
        }
        self.reader.fill_buf()
    }

    fn consume(&mut self, amt: usize) {
        self.trip = self.trip.saturating_add(
            u64::try_from(amt).unwrap_or_default()
        );
        self.reader.consume(amt)
    }
}


//------------ Error ---------------------------------------------------------

#[derive(Debug)]
pub enum Error {
    Xml(quick_xml::Error),
    XmlAttr(AttrError),
    Malformed,
}

impl From<quick_xml::Error> for Error {
    fn from(err: quick_xml::Error) -> Self {
        Error::Xml(err)
    }
}

impl From<NamespaceError> for Error {
    fn from(err: NamespaceError) -> Self {
        Error::Xml(err.into())
    }
}

impl From<EncodingError> for Error {
    fn from(err: EncodingError) -> Self {
        Error::Xml(err.into())
    }
}

impl From<AttrError> for Error {
    fn from(err: AttrError) -> Self {
        Error::XmlAttr(err)
    }
}

impl From<base64::XmlDecodeError> for Error {
    fn from(_: base64::XmlDecodeError) -> Self {
        Self::Malformed
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Xml(ref err) => err.fmt(f),
            Error::XmlAttr(ref err) => err.fmt(f),
            Error::Malformed => f.write_str("malformed XML"),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::Xml(error) => Some(error),
            Error::XmlAttr(attr_error) => Some(attr_error),
            Error::Malformed => None,
        }
    }
 }