bgpkit-parser 0.25.0-beta.1

MRT/BGP/BMP data processing library
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
use crate::models::{CommonHeader, EntryType};
use crate::ParserError;
use bytes::Bytes;
use std::io::Read;
use zerocopy::big_endian::{U16, U32};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

/// On-wire MRT common header layout (12 bytes, network byte order).
#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
#[repr(C)]
struct RawMrtCommonHeader {
    timestamp: U32,
    entry_type: U16,
    entry_subtype: U16,
    length: U32,
}

const _: () = assert!(size_of::<RawMrtCommonHeader>() == 12);

/// On-wire MRT header with microseconds included (16 bytes, network byte order)
#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
#[repr(C)]
struct RawMrtEtCommonHeader {
    timestamp: U32,
    entry_type: U16,
    entry_subtype: U16,
    length: U32,
    microseconds: U32,
}

const _: () = assert!(size_of::<RawMrtEtCommonHeader>() == 16);

enum RawMrtHeader {
    Standard(RawMrtCommonHeader),
    Et(RawMrtEtCommonHeader),
}

impl From<&CommonHeader> for RawMrtHeader {
    fn from(header: &CommonHeader) -> Self {
        match header.microsecond_timestamp {
            None => RawMrtHeader::Standard(RawMrtCommonHeader {
                timestamp: U32::new(header.timestamp),
                entry_type: U16::new(header.entry_type as u16),
                entry_subtype: U16::new(header.entry_subtype),
                length: U32::new(header.length),
            }),
            Some(microseconds) => RawMrtHeader::Et(RawMrtEtCommonHeader {
                timestamp: U32::new(header.timestamp),
                entry_type: U16::new(header.entry_type as u16),
                entry_subtype: U16::new(header.entry_subtype),
                // Internally, we use the length of the MRT payload.
                // However in the header, the length includes the space used by the extra timestamp
                // data.
                length: U32::new(header.length + 4),
                microseconds: U32::new(microseconds),
            }),
        }
    }
}

impl RawMrtHeader {
    fn as_bytes(&self) -> &[u8] {
        match self {
            RawMrtHeader::Standard(raw) => raw.as_bytes(),
            RawMrtHeader::Et(raw) => raw.as_bytes(),
        }
    }
}

/// Result of parsing a common header, including the raw bytes.
pub struct ParsedHeader {
    pub header: CommonHeader,
    pub raw_bytes: Bytes,
}

/// MRT common header [RFC6396][header].
///
/// [header]: https://tools.ietf.org/html/rfc6396#section-4.1
///
/// A MRT record is constructed as the following:
/// ```text
///  0                   1                   2                   3
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                           Timestamp                           |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |             Type              |            Subtype            |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                             Length                            |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                      Message... (variable)
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// ```
///
/// Or with extended timestamp:
/// ```text
///  0                   1                   2                   3
///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                           Timestamp                           |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |             Type              |            Subtype            |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                             Length                            |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                      Microsecond Timestamp                    |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                      Message... (variable)
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// ```
pub fn parse_common_header<T: Read>(input: &mut T) -> Result<CommonHeader, ParserError> {
    Ok(parse_common_header_with_bytes(input)?.header)
}

/// Parse the MRT common header and return both the parsed header and raw bytes.
///
/// This is useful when you need to preserve the original bytes for debugging
/// or exporting problematic records without re-encoding.
pub fn parse_common_header_with_bytes<T: Read>(input: &mut T) -> Result<ParsedHeader, ParserError> {
    let framed = frame_common_header(input)?;
    Ok(ParsedHeader {
        header: framed.header?,
        raw_bytes: framed.raw_bytes,
    })
}

/// A common header as read from the wire, with its contents validated separately
/// from its framing.
pub(crate) struct FramedHeader {
    /// The parsed header, or why its contents were rejected.
    pub(crate) header: Result<CommonHeader, ParserError>,
    /// The header bytes as read from the wire.
    pub(crate) raw_bytes: Bytes,
}

/// A common header read from the wire, with its raw bytes kept in a fixed buffer.
///
/// The default parse path only needs the raw header bytes when something goes wrong, so capturing
/// them on the stack avoids one small heap allocation per record.
#[derive(Clone, Copy)]
pub(crate) struct HeaderBuf {
    bytes: [u8; 16],
    len: usize,
}

impl Default for HeaderBuf {
    fn default() -> Self {
        HeaderBuf::new()
    }
}

impl HeaderBuf {
    pub(crate) fn new() -> Self {
        HeaderBuf {
            bytes: [0u8; 16],
            len: 0,
        }
    }

    pub(crate) fn as_slice(&self) -> &[u8] {
        &self.bytes[..self.len]
    }
}

/// A common header as read from the wire, borrowing its raw bytes from the caller's buffer.
pub(crate) struct FramedHeaderRef<'a> {
    /// The parsed header, or why its contents were rejected.
    pub(crate) header: Result<CommonHeader, ParserError>,
    /// The header bytes as read from the wire.
    pub(crate) raw_bytes: &'a [u8],
    /// Length of the record body following `raw_bytes`.
    pub(crate) body_length: u32,
}

/// Read a common header into `header`, keeping its body length even when the contents are
/// rejected. Only I/O failures are returned as `Err`.
pub(crate) fn frame_common_header_captured<'a, T: Read>(
    input: &mut T,
    header: &'a mut HeaderBuf,
) -> std::io::Result<FramedHeaderRef<'a>> {
    header.len = 0;
    read_header_upto(input, header, 12)?;
    if header.len < 12 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "failed to fill whole buffer",
        ));
    }

    // Single bounds check via zerocopy instead of four sequential cursor reads.
    let raw = RawMrtCommonHeader::ref_from_bytes(&header.bytes[..12])
        .expect("base_bytes is exactly 12 bytes with no alignment requirement");

    let timestamp = raw.timestamp.get();
    let entry_subtype = raw.entry_subtype.get();
    // the length field does not include the length of the common header
    let length = raw.length.get();

    // The on-wire length counts every byte after the 12-byte base header, so it
    // frames the record even when the header contents are invalid.
    let entry_type = match EntryType::try_from(raw.entry_type.get()) {
        Ok(entry_type) => entry_type,
        Err(error) => {
            return Ok(FramedHeaderRef {
                header: Err(error.into()),
                raw_bytes: header.as_slice(),
                body_length: length,
            })
        }
    };

    let (microsecond_timestamp, body_length) = match &entry_type {
        EntryType::BGP4MP_ET => {
            // For ET records, the on-wire length includes the extra 4-byte microsecond timestamp
            // that lives in the header. Internally we store `length` as the message length only,
            // so subtract 4 after validating to avoid underflow.
            if length < 4 {
                return Ok(FramedHeaderRef {
                    header: Err(ParserError::ParseError(
                        "invalid MRT header length for ET record: length < 4".into(),
                    )),
                    raw_bytes: header.as_slice(),
                    body_length: length,
                });
            }
            read_header_upto(input, header, 16)?;
            if header.len < 16 {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "failed to fill whole buffer",
                ));
            }
            (
                Some(u32::from_be_bytes(
                    header.bytes[12..16].try_into().expect("four bytes"),
                )),
                length - 4,
            )
        }
        _ => (None, length),
    };

    Ok(FramedHeaderRef {
        header: Ok(CommonHeader {
            timestamp,
            microsecond_timestamp,
            entry_type,
            entry_subtype,
            length: body_length,
        }),
        raw_bytes: header.as_slice(),
        body_length,
    })
}

/// Read into `header.bytes` until it holds `end` bytes.
///
/// `header.len` advances as bytes arrive, so a reader that fails part-way still leaves the bytes it
/// did deliver in the buffer for error reporting.
fn read_header_upto(
    input: &mut impl Read,
    header: &mut HeaderBuf,
    end: usize,
) -> std::io::Result<()> {
    while header.len < end {
        match input.read(&mut header.bytes[header.len..end]) {
            Ok(0) => break,
            Ok(read) => header.len += read,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

/// Read a common header, keeping its body length even when the contents are
/// rejected. Only I/O failures are returned as `Err`.
pub(crate) fn frame_common_header<T: Read>(input: &mut T) -> std::io::Result<FramedHeader> {
    let mut header = HeaderBuf::new();
    let framed = frame_common_header_captured(input, &mut header)?;
    Ok(FramedHeader {
        header: framed.header,
        raw_bytes: Bytes::copy_from_slice(framed.raw_bytes),
    })
}

impl CommonHeader {
    pub fn encode(&self) -> Bytes {
        let raw = RawMrtHeader::from(self);
        Bytes::copy_from_slice(raw.as_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::EntryType;
    use bytes::Buf;

    #[test]
    fn test_parse_common_header_with_bytes() {
        let input = Bytes::from_static(&[
            0, 0, 0, 1, // timestamp
            0, 16, // entry type
            0, 4, // entry subtype
            0, 0, 0, 5, // length
        ]);

        let mut reader = input.clone().reader();
        let result = parse_common_header_with_bytes(&mut reader).unwrap();

        assert_eq!(result.header.timestamp, 1);
        assert_eq!(result.header.entry_type, EntryType::BGP4MP);
        assert_eq!(result.header.entry_subtype, 4);
        assert_eq!(result.header.length, 5);
        assert_eq!(result.raw_bytes, input);
    }

    #[test]
    fn test_parse_common_header_with_bytes_et() {
        let input = Bytes::from_static(&[
            0, 0, 0, 1, // timestamp
            0, 17, // entry type = BGP4MP_ET
            0, 4, // entry subtype
            0, 0, 0, 9, // length (includes 4 bytes for microsecond)
            0, 3, 130, 112, // microsecond timestamp
        ]);

        let mut reader = input.clone().reader();
        let result = parse_common_header_with_bytes(&mut reader).unwrap();

        assert_eq!(result.header.timestamp, 1);
        assert_eq!(result.header.entry_type, EntryType::BGP4MP_ET);
        assert_eq!(result.header.entry_subtype, 4);
        assert_eq!(result.header.length, 5); // adjusted length
        assert_eq!(result.header.microsecond_timestamp, Some(230_000));
        assert_eq!(result.raw_bytes, input);
    }

    /// Test that the length is not adjusted when the microsecond timestamp is not present.
    #[test]
    fn test_encode_common_header() {
        let header = CommonHeader {
            timestamp: 1,
            microsecond_timestamp: None,
            entry_type: EntryType::BGP4MP,
            entry_subtype: 4,
            length: 5,
        };

        let expected = Bytes::from_static(&[
            0, 0, 0, 1, // timestamp
            0, 16, // entry type
            0, 4, // entry subtype
            0, 0, 0, 5, // length
        ]);

        let encoded = header.encode();
        assert_eq!(encoded, expected);

        let mut reader = expected.reader();
        let parsed = parse_common_header(&mut reader).unwrap();
        assert_eq!(parsed, header);
    }

    /// Test that the length is adjusted when the microsecond timestamp is present.
    #[test]
    fn test_encode_common_header_et() {
        let header = CommonHeader {
            timestamp: 1,
            microsecond_timestamp: Some(230_000),
            entry_type: EntryType::BGP4MP_ET,
            entry_subtype: 4,
            length: 5,
        };

        let expected = Bytes::from_static(&[
            0, 0, 0, 1, // timestamp
            0, 17, // entry type
            0, 4, // entry subtype
            0, 0, 0, 9, // length
            0, 3, 130, 112, // microsecond timestamp
        ]);

        let encoded = header.encode();
        assert_eq!(encoded, expected);

        let mut reader = expected.reader();
        let parsed = parse_common_header(&mut reader).unwrap();
        assert_eq!(parsed, header);
    }

    /// Ensure ET header with invalid on-wire length (< 4) returns error instead of panicking.
    #[test]
    fn test_parse_common_header_et_invalid_length() {
        // Construct a header with length=3 for ET (which is invalid since it must include 4 bytes of microsecond field)
        let bytes = Bytes::from_static(&[
            0, 0, 0, 0, // timestamp
            0, 17, // entry type = BGP4MP_ET
            0, 0, // subtype
            0, 0, 0, 3, // length (invalid for ET)
        ]);
        let mut reader = bytes.reader();
        let res = parse_common_header(&mut reader);
        assert!(res.is_err());
    }
}