sciparse 0.6.1

Zero-copy SCION packet parsing, serialization and control plane components
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
// Copyright 2026 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SCION packet models

use std::{fmt::Debug, ops::Deref};

use crate::{
    address::{addr::ScionAddr, host_addr::UnknownAddressTypeError, socket_addr::ScionSocketAddr},
    core::{
        convert::{TryFromModel, TryFromView},
        encode::{InvalidStructureError, WireEncode},
        macros::impl_from,
        model::Model,
        view::{View, ViewConversionError},
    },
    dataplane_path::model::DpPath,
    header::{
        model::{AddressHeader, CommonHeader, ScionPacketHeader},
        view::ScionHeaderView,
    },
    packet::{
        classify::{ClassifiedPacket, ClassifyError},
        view::{ScionPacketView, ScionRawPacketView, ScionScmpPacketView, ScionUdpPacketView},
    },
    payload::{
        ProtocolNumber, encode::PayloadEncode, scmp::model::ScmpMessage, udp::model::UdpDatagram,
    },
};

/// A Complete SCION Packet
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ScionPacket<T: PayloadEncode> {
    /// SCION Packet Header
    pub header: ScionPacketHeader,
    /// Payload
    pub payload: T,
}
// Methods for all packet types
impl<T: PayloadEncode> ScionPacket<T> {
    /// Converts this packet into a raw packet with an owned `Vec<u8>` payload by encoding the
    /// payload
    #[inline]
    pub fn into_raw(self) -> ScionRawPacket {
        let header_size = self.header.required_size();
        let payload_size = self.payload.required_size(header_size);
        let mut buf = vec![0u8; payload_size];
        let size = self
            .payload
            .try_encode(&mut buf[..], &self.header.address, header_size)
            .expect("Buffer size must be sufficient based on required_size");

        debug_assert_eq!(
            size, payload_size,
            "Encoded payload size must match required_size calculation"
        );

        ScionPacket {
            header: self.header,
            payload: buf,
        }
    }

    /// Returns the source SCION address of the packet.
    ///
    /// If a unknown address type is encountered in the source host address, an error is returned.
    #[inline]
    pub fn src_scion_addr(&self) -> Result<ScionAddr, UnknownAddressTypeError> {
        let host = self.header.address.src_host_addr.scion_host_addr()?;
        Ok(ScionAddr::new(self.header.address.src_ia, host))
    }

    /// Sets the source SCION address of the packet by updating the appropriate fields in the
    /// header.
    #[inline]
    pub fn set_src_scion_addr(&mut self, addr: ScionAddr) {
        self.header.address.src_ia = addr.isd_asn();
        self.header.address.src_host_addr = addr.host().into();
    }

    /// Returns the destination SCION address of the packet.
    ///
    /// If a unknown address type is encountered in the destination host address, an error is
    /// returned.
    #[inline]
    pub fn dst_scion_addr(&self) -> Result<ScionAddr, UnknownAddressTypeError> {
        let host = self.header.address.dst_host_addr.scion_host_addr()?;
        Ok(ScionAddr::new(self.header.address.dst_ia, host))
    }

    /// Sets the destination SCION address of the packet by updating the appropriate fields in the
    /// header.
    #[inline]
    pub fn set_dst_scion_addr(&mut self, addr: ScionAddr) {
        self.header.address.dst_ia = addr.isd_asn();
        self.header.address.dst_host_addr = addr.host().into();
    }
}
impl<T: PayloadEncode> WireEncode for ScionPacket<T> {
    #[inline]
    fn required_size(&self) -> usize {
        self.header.required_size() + self.payload.required_size(self.header.required_size())
    }

    #[inline]
    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        self.header.wire_valid()?;
        self.payload.wire_valid()?;
        Ok(())
    }

    #[inline]
    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        let header_size = self.header.required_size();
        let payload_size = self.payload.required_size(header_size);

        unsafe {
            // Encode header
            {
                let header_buf = buf.get_unchecked_mut(0..header_size);
                self.header
                    .encode_unchecked(header_buf, payload_size as u16);
            }
            // Encode payload
            let payload_buf = buf.get_unchecked_mut(header_size..(header_size + payload_size));
            self.payload
                .encode_unchecked(payload_buf, &self.header.address, header_size);
        }

        self.required_size()
    }
}

/// Raw SCION packet
pub type ScionRawPacket = ScionPacket<Vec<u8>>;
impl ScionRawPacket {
    /// Constructs a [ScionRawPacket] from the given source and destination addresses, path, and
    /// payload.
    ///
    /// Traffic class and flow ID are set to 0, and `next_header` is set according to the provided
    /// protocol.
    #[inline]
    pub fn new(
        src: ScionAddr,
        dst: ScionAddr,
        path: DpPath,
        next_header: ProtocolNumber,
        payload: Vec<u8>,
    ) -> Self {
        Self {
            header: ScionPacketHeader {
                common: CommonHeader {
                    traffic_class: 0,
                    flow_id: 0,
                    next_header,
                },
                address: AddressHeader::new(src, dst),
                path,
            },
            payload,
        }
    }

    /// Classifies the raw packet by inspecting its `next_header` field and attempting to parse the
    /// payload accordingly.
    ///
    /// Returns [`ClassifiedPacket::Other`] for unknown `next_header` values, otherwise returns
    /// a more specific variant with the parsed payload.
    ///
    /// If the payload cannot be parsed according to the expected protocol for the given
    /// `next_header`, an error is returned.
    ///
    /// This method will truncate any data in the payload that is not part of the parsed message.
    /// Meaning if the payload contains a valid UDP datagram followed by extra bytes, the extra
    /// bytes will be ignored.
    #[inline]
    pub fn try_classify(self) -> Result<ClassifiedPacket, ClassifyError> {
        match self.header.common.next_header {
            ProtocolNumber::Scmp => {
                ScionScmpPacket::try_from_raw(self)
                    .map_err(ClassifyError::MalformedScmp)
                    .map(ClassifiedPacket::Scmp)
            }
            ProtocolNumber::Udp => {
                ScionUdpPacket::try_from_raw(self)
                    .map_err(ClassifyError::MalformedUdp)
                    .map(ClassifiedPacket::Udp)
            }
            _ => Ok(ClassifiedPacket::Other(self.to_owned())),
        }
    }

    /// Attempts to convert this raw packet into a SCMP packet by parsing the payload as a SCMP
    /// message.
    #[inline]
    pub fn try_into_scmp(self) -> Result<ScionScmpPacket, ViewConversionError> {
        ScionScmpPacket::try_from_raw(self)
    }

    /// Attempts to convert this raw packet into a UDP packet by parsing the payload as a UDP
    /// datagram.
    #[inline]
    pub fn try_into_udp(self) -> Result<ScionUdpPacket, ViewConversionError> {
        ScionUdpPacket::try_from_raw(self)
    }
}
impl Debug for ScionRawPacket {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScionPacket")
            .field("header", &self.header)
            .field("payload", &format_args!("{} bytes", self.payload.len()))
            .finish()
    }
}
impl Model for ScionRawPacket {
    type ViewType = ScionRawPacketView;
}
impl TryFromModel for ScionRawPacketView {
    type ModelType = ScionRawPacket;
}
impl TryFromView for ScionRawPacket {
    type ViewType = ScionPacketView;

    #[inline]
    fn try_from_view(view: &Self::ViewType) -> Result<Self, ViewConversionError> {
        ScionRawPacketRef::try_from_view(view).map(|packet_ref| packet_ref.to_owned())
    }
}
impl_from!(ScionPacket<ScmpMessage>, ScionRawPacket, |scmp_packet| {
    scmp_packet.into_raw()
});
impl_from!(ScionPacket<UdpDatagram>, ScionRawPacket, |udp_packet| {
    udp_packet.into_raw()
});

/// Raw SCION packet with referenced payload
pub type ScionRawPacketRef<'a> = ScionPacket<&'a [u8]>;
impl<'a> ScionPacket<&'a [u8]> {
    /// Constructs a [ScionPacket] from a [ScionHeaderView] and payload slice
    #[inline]
    pub fn try_from_view(view: &'a ScionPacketView) -> Result<Self, ViewConversionError> {
        Ok(Self {
            header: ScionPacketHeader::try_from_view(view.header())?,
            payload: view.payload(),
        })
    }

    /// Parses a [ScionPacket] from a byte slice, returning the packet and any remaining bytes.
    #[inline]
    pub fn try_from_slice(buf: &'a [u8]) -> Result<(Self, &'a [u8]), ViewConversionError> {
        let payload_size = ScionHeaderView::try_from_slice(buf)?.0.payload_len();
        let (header, rest) = ScionPacketHeader::try_from_slice(buf)?;
        let (payload, rest) = rest.split_at_checked(payload_size as usize).ok_or(
            ViewConversionError::BufferTooSmall {
                at: "Payload",
                required: payload_size as usize,
                actual: rest.len(),
            },
        )?;

        Ok((ScionPacket { header, payload }, rest))
    }
}
impl Debug for ScionPacket<&[u8]> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScionRawPacketRef")
            .field("header", &self.header)
            .field("payload", &format_args!("{} bytes", self.payload.len()))
            .finish()
    }
}

// Methods for all RAW packet types
impl<'a, RawT: PayloadEncode + Deref<Target = [u8]>> ScionPacket<RawT> {
    /// Clones the packet, converting the payload to an owned `Vec<u8>`.
    #[inline]
    pub fn to_owned(self) -> ScionRawPacket {
        ScionPacket {
            header: self.header,
            payload: self.payload.to_vec(),
        }
    }

    /// Clones the packet header, keeping the payload as a reference.
    #[inline]
    pub fn to_ref(&'a self) -> ScionRawPacketRef<'a> {
        ScionPacket {
            header: self.header.clone(),
            payload: self.payload.deref(),
        }
    }
}

/// SCMP SCION packet
pub type ScionScmpPacket = ScionPacket<ScmpMessage>;
impl ScionScmpPacket {
    /// Constructs a [ScionScmpPacket] from the given source and destination addresses, path, and
    /// payload.
    ///
    /// Traffic class and flow ID are set to 0, and `next_header` is set to the appropriate value
    /// for SCMP.
    #[inline]
    pub fn new(src: ScionAddr, dst: ScionAddr, path: DpPath, payload: ScmpMessage) -> Self {
        Self {
            header: ScionPacketHeader {
                common: CommonHeader {
                    traffic_class: 0,
                    flow_id: 0,
                    next_header: ProtocolNumber::Scmp,
                },
                address: AddressHeader::new(src, dst),
                path,
            },
            payload,
        }
    }

    /// Attempts to construct a `ScionScmpPacket` from a `ScionRawPacket` by parsing the payload as
    /// a SCMP message.
    ///
    /// Returns an error if the payload cannot be parsed as a valid SCMP message or if the
    /// `next_header` field is not set to the appropriate value for SCMP.
    #[inline]
    pub fn try_from_raw(packet: ScionRawPacket) -> Result<Self, ViewConversionError> {
        if packet.header.common.next_header != ProtocolNumber::Scmp {
            return Err(ViewConversionError::Other("next header not SCMP"));
        }

        let payload = packet.payload;
        let (scmp_message, _rest) = ScmpMessage::try_from_slice(&payload)?;
        Ok(Self {
            header: packet.header,
            payload: scmp_message,
        })
    }
}
impl Debug for ScionScmpPacket {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScionScmpPacket")
            .field("header", &self.header)
            .field("payload", &self.payload)
            .finish()
    }
}
impl Model for ScionScmpPacket {
    type ViewType = ScionScmpPacketView;
}
impl TryFromModel for ScionScmpPacketView {
    type ModelType = ScionScmpPacket;
}
impl TryFromView for ScionScmpPacket {
    type ViewType = ScionScmpPacketView;

    #[inline]
    fn try_from_view(view: &Self::ViewType) -> Result<Self, ViewConversionError> {
        let header = ScionPacketHeader::try_from_view(view.header())?;
        let payload = ScmpMessage::from_view(&view.scmp().message());

        Ok(Self { header, payload })
    }
}
impl TryFrom<ScionRawPacket> for ScionScmpPacket {
    type Error = ViewConversionError;
    #[inline]
    fn try_from(raw_packet: ScionRawPacket) -> Result<Self, Self::Error> {
        Self::try_from_raw(raw_packet)
    }
}

/// UDP SCION packet
pub type ScionUdpPacket = ScionPacket<UdpDatagram>;
impl ScionUdpPacket {
    /// Constructs a [ScionUdpPacket] from the given source and destination socket addresses, path,
    /// and payload.
    ///
    /// Traffic class and flow ID are set to 0, and `next_header` is set to the appropriate value
    /// for UDP.
    #[inline]
    pub fn new(src: ScionSocketAddr, dst: ScionSocketAddr, path: DpPath, payload: Vec<u8>) -> Self {
        Self {
            header: ScionPacketHeader {
                common: CommonHeader {
                    traffic_class: 0,
                    flow_id: 0,
                    next_header: ProtocolNumber::Udp,
                },
                address: AddressHeader::new(src.scion_addr(), dst.scion_addr()),
                path,
            },
            payload: UdpDatagram::new(src.port(), dst.port(), payload),
        }
    }

    /// Constructs a [ScionUdpPacket] from the given parts, inferring header fields as needed.
    #[inline]
    pub fn new_from_parts(address: AddressHeader, path: DpPath, payload: UdpDatagram) -> Self {
        let header = ScionPacketHeader {
            common: CommonHeader {
                traffic_class: 0,
                flow_id: 0,
                next_header: ProtocolNumber::Udp,
            },
            address,
            path,
        };
        Self { header, payload }
    }

    /// Attempts to construct a `ScionUdpPacket` from a `ScionRawPacket` by parsing the payload as
    /// a UDP datagram. Bytes past the end of the UDP datagram are truncated.
    ///
    /// Returns an error if the payload cannot be parsed as a valid UDP datagram or if the
    /// `next_header` field is not set to the appropriate value for UDP.
    #[inline]
    pub fn try_from_raw(packet: ScionRawPacket) -> Result<Self, ViewConversionError> {
        if packet.header.common.next_header != ProtocolNumber::Udp {
            return Err(ViewConversionError::Other("next header not UDP"));
        }

        let payload = packet.payload;
        let (udp_datagram, _rest) = UdpDatagram::try_from_slice(&payload)?;
        Ok(Self {
            header: packet.header,
            payload: udp_datagram,
        })
    }
}
impl Debug for ScionUdpPacket {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScionUdpPacket")
            .field("header", &self.header)
            .field("payload", &self.payload)
            .finish()
    }
}
impl Model for ScionUdpPacket {
    type ViewType = ScionUdpPacketView;
}
impl TryFromModel for ScionUdpPacketView {
    type ModelType = ScionUdpPacket;
}
impl TryFromView for ScionUdpPacket {
    type ViewType = ScionUdpPacketView;

    #[inline]
    fn try_from_view(view: &Self::ViewType) -> Result<Self, ViewConversionError> {
        let header = ScionPacketHeader::try_from_view(view.header())?;
        let payload = UdpDatagram::from_view(view.udp());

        Ok(Self { header, payload })
    }
}
impl TryFrom<ScionRawPacket> for ScionUdpPacket {
    type Error = ViewConversionError;

    #[inline]
    fn try_from(packet: ScionRawPacket) -> Result<Self, Self::Error> {
        Self::try_from_raw(packet)
    }
}

impl ScionUdpPacket {
    /// Returns the source SCION socket address of the packet.
    ///
    /// If a unknown address type is encountered in the source host address, an error is returned.
    #[inline]
    pub fn src_socket_addr(&self) -> Result<ScionSocketAddr, UnknownAddressTypeError> {
        let src_port = self.payload.as_ref().src_port;
        let isd_asn = self.header.address.src_ia;
        let scion_addr = self.header.address.src_host_addr.scion_host_addr()?;

        Ok(ScionSocketAddr::new(isd_asn, scion_addr, src_port))
    }

    /// Sets the source SCION socket address of the packet by updating the appropriate fields in the
    /// header and payload.
    #[inline]
    pub fn set_src_socket_addr(&mut self, socket_addr: ScionSocketAddr) {
        self.header.address.src_ia = socket_addr.isd_asn();
        self.header.address.src_host_addr = socket_addr.host().into();
        self.payload.as_mut().src_port = socket_addr.port();
    }

    /// Returns the destination SCION socket address of the packet.
    ///
    /// If a unknown address type is encountered in the destination host address, an error is
    /// returned.
    #[inline]
    pub fn dst_socket_addr(&self) -> Result<ScionSocketAddr, UnknownAddressTypeError> {
        let dst_port = self.payload.as_ref().dst_port;
        let isd_asn = self.header.address.dst_ia;
        let scion_addr = self.header.address.dst_host_addr.scion_host_addr()?;

        Ok(ScionSocketAddr::new(isd_asn, scion_addr, dst_port))
    }

    /// Sets the destination SCION socket address of the packet by updating the appropriate fields
    /// in the header and payload.
    #[inline]
    pub fn set_dst_socket_addr(&mut self, socket_addr: ScionSocketAddr) {
        self.header.address.dst_ia = socket_addr.isd_asn();
        self.header.address.dst_host_addr = socket_addr.host().into();
        self.payload.as_mut().dst_port = socket_addr.port();
    }
}
/// Support for [`proptest::arbitrary`].
#[cfg(feature = "proptest")]
pub mod ptest {
    use ::proptest::prelude::*;
    use proptest::collection;

    use super::*;

    /// Configuration for generating arbitrary [`ScionRawPacket`] values.
    #[derive(Debug, Clone, Default)]
    pub struct ArbitraryScionRawPacketParams {
        /// Parameters for generating the SCION packet header.
        pub header: <ScionPacketHeader as Arbitrary>::Parameters,
    }

    impl Arbitrary for ScionRawPacket {
        type Parameters = ArbitraryScionRawPacketParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            (
                ScionPacketHeader::arbitrary_with(params.header),
                collection::vec(any::<u8>(), 0..2048),
            )
                .prop_map(|(header, payload)| ScionPacket { header, payload })
                .boxed()
        }
    }

    /// Configuration for generating arbitrary [`ScionUdpPacket`] values.
    #[derive(Debug, Clone, Default)]
    pub struct ArbitraryScionUdpPacketParams {
        /// Parameters for generating the SCION packet header.
        pub header: <ScionPacketHeader as Arbitrary>::Parameters,
    }

    impl Arbitrary for ScionUdpPacket {
        type Parameters = ArbitraryScionUdpPacketParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            (
                ScionPacketHeader::arbitrary_with(params.header),
                any::<UdpDatagram>(),
            )
                .prop_map(|(mut header, payload)| {
                    header.common.next_header = ProtocolNumber::Udp;
                    ScionPacket { header, payload }
                })
                .boxed()
        }
    }

    /// Configuration for generating arbitrary [`ScionScmpPacket`] values.
    #[derive(Debug, Clone, Default)]
    pub struct ArbitraryScionScmpPacketParams {
        /// Parameters for generating the SCION packet header.
        pub header: <ScionPacketHeader as Arbitrary>::Parameters,
        /// Parameters for generating the SCMP message payload.
        pub scmp_message: <ScmpMessage as Arbitrary>::Parameters,
    }

    impl Arbitrary for ScionScmpPacket {
        type Parameters = ArbitraryScionScmpPacketParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            (
                ScionPacketHeader::arbitrary_with(params.header),
                ScmpMessage::arbitrary_with(params.scmp_message),
            )
                .prop_map(|(mut header, payload)| {
                    header.common.next_header = ProtocolNumber::Scmp;
                    ScionPacket { header, payload }
                })
                .boxed()
        }
    }
}