sciparse 0.5.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
// 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 standard path models

use tinyvec::{ArrayVec, TinyVec};

use crate::{
    core::{
        encode::{InvalidStructureError, WireEncode},
        layout::Layout,
        write::unchecked_bit_range_be_write,
    },
    path::{
        layout::ScionHeaderPathLayout,
        standard::{
            layout::{HopFieldLayout, InfoFieldLayout, StdPathDataLayout, StdPathMetaLayout},
            mac::{ForwardingKey, HopMacCalculate, HopMacInput, HopMacInputSource},
            types::{HopFieldFlags, HopFieldMac, InfoFieldFlags},
            view::{HopFieldView, InfoFieldView, StandardPathView},
        },
    },
};

/// Represents a standard SCION path
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StandardPath {
    /// The current info field index
    pub current_info_field: u8,
    /// The current hop field index
    pub current_hop_field: u8,
    /// The segments of the path
    pub segments: ArrayVec<[Segment; 3]>,
}
impl StandardPath {
    /// Constructs a `StandardPath` from a `StandardPathView`
    pub fn from_view(view: &StandardPathView) -> Self {
        let info_fields = view.info_fields();
        let hop_fields = view.hop_fields();
        let segment_sizes = [view.seg0_len(), view.seg1_len(), view.seg2_len()];

        let mut segments = ArrayVec::new();
        let mut hop_fields_iter = hop_fields.iter();

        for (info_field, segment_size) in info_fields.iter().zip(segment_sizes.iter()) {
            let segment = Segment {
                info_field: InfoField::from_view(info_field),
                hop_fields: hop_fields_iter
                    .by_ref()
                    .take(*segment_size as usize)
                    .map(HopField::from_view)
                    .collect(),
            };

            segments.push(segment);
        }

        StandardPath {
            current_info_field: view.curr_info_field(),
            current_hop_field: view.curr_hop_field(),
            segments,
        }
    }
}
// Utility
impl StandardPath {
    /// Returns the total number of hop fields in the path
    pub fn hop_field_count(&self) -> usize {
        self.segments
            .iter()
            .map(|segment| segment.hop_fields.len())
            .sum()
    }

    /// Returns the total number of info fields in the path
    pub fn info_field_count(&self) -> usize {
        self.segments.len()
    }

    /// Returns the lengths of each segment in the path as a tuple
    pub fn segment_lengths(&self) -> (u8, u8, u8) {
        let seg0 = self.segments.first().map_or(0, |s| s.hop_fields.len()) as u8;
        let seg1 = self.segments.get(1).map_or(0, |s| s.hop_fields.len()) as u8;
        let seg2 = self.segments.get(2).map_or(0, |s| s.hop_fields.len()) as u8;
        (seg0, seg1, seg2)
    }

    /// Returns an iterator over all hop fields in the path
    pub fn iter_hop_fields(&self) -> impl Iterator<Item = &HopField> {
        self.segments
            .iter()
            .flat_map(|segment| segment.hop_fields.iter())
    }

    /// Returns an iterator over all info fields in the path
    pub fn iter_info_fields(&self) -> impl Iterator<Item = &InfoField> {
        self.segments.iter().map(|segment| &segment.info_field)
    }

    /// Returns the sizes of each segment in the path
    pub fn segment_sizes(&self) -> [u8; 3] {
        let seg0 = self.segments.first().map_or(0, |s| s.hop_fields.len()) as u8;
        let seg1 = self.segments.get(1).map_or(0, |s| s.hop_fields.len()) as u8;
        let seg2 = self.segments.get(2).map_or(0, |s| s.hop_fields.len()) as u8;
        [seg0, seg1, seg2]
    }
}
impl WireEncode for StandardPath {
    fn required_size(&self) -> usize {
        let [seg0, seg1, seg2] = self.segment_sizes();
        StdPathMetaLayout::SIZE_BYTES + StdPathDataLayout::new(seg0, seg1, seg2).size_bytes()
    }

    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        if self.required_size() > ScionHeaderPathLayout::MAX_SIZE_BYTES {
            return Err("Encoded path size exceeds maximum allowed".into());
        }

        // Should never be hit since we are using an ArrayVec with a max length of 3.
        // Compiler should optimize this check away.
        if self.segments.len() > StdPathMetaLayout::MAX_SEGMENTS {
            return Err("Number of segments exceeds maximum allowed".into());
        }

        if self.segments.is_empty() {
            return Err("Standard path must contain at least one segment".into());
        }

        if self.current_hop_field as usize >= self.hop_field_count() {
            return Err("curr_hop_field exceeds total number of hop fields".into());
        }

        if self.current_info_field as usize >= self.info_field_count() {
            return Err("current_info_field exceeds total number of info fields".into());
        }

        for segment in &self.segments {
            if segment.hop_fields.len() > StdPathMetaLayout::MAX_SEGMENT_HOPS {
                return Err("Number of hop fields in segment exceeds maximum allowed".into());
            }

            if segment.hop_fields.is_empty() {
                return Err("Segment must contain at least one hop field".into());
            }

            segment.info_field.wire_valid()?;

            for hop_field in &segment.hop_fields {
                hop_field.wire_valid()?;
            }
        }

        Ok(())
    }

    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        use StdPathMetaLayout as SL;

        let [seg0, seg1, seg2] = self.segment_sizes();

        // Encode standard path meta information
        unsafe {
            unchecked_bit_range_be_write(buf, SL::CURR_INFO_FIELD_RNG, self.current_info_field);
            unchecked_bit_range_be_write(buf, SL::CURR_HOP_FIELD_RNG, self.current_hop_field);
            unchecked_bit_range_be_write(buf, SL::SEG0_LEN_RNG, seg0);
            unchecked_bit_range_be_write(buf, SL::SEG1_LEN_RNG, seg1);
            unchecked_bit_range_be_write(buf, SL::SEG2_LEN_RNG, seg2);
        }

        // Advance offset to path data
        let data_buf = unsafe { buf.get_unchecked_mut(SL::SIZE_BYTES..) };
        let data_layout = StdPathDataLayout::new(seg0, seg1, seg2);

        // Encode standard path data
        // Encode info fields
        for (i, info_field) in self.iter_info_fields().enumerate() {
            let range = data_layout.info_field_range(i).aligned_byte_range();
            unsafe {
                let info_field_buf = data_buf.get_unchecked_mut(range);
                info_field.encode_unchecked(info_field_buf);
            }
        }

        // Encode hop fields
        for (i, hop_field) in self.iter_hop_fields().enumerate() {
            let range = data_layout.hop_field_range(i).aligned_byte_range();
            unsafe {
                let hop_field_buf = data_buf.get_unchecked_mut(range);
                hop_field.encode_unchecked(hop_field_buf);
            }
        }

        SL::SIZE_BYTES + data_layout.size_bytes()
    }
}

/// Represents a segment in a standard SCION path
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Segment {
    /// Info field containing metadata about the segment
    pub info_field: InfoField,
    /// Hop fields representing the hops in the segment
    // Note: As long as the total number of hops does not exceed the defined maximum, tinyvec will
    // store the hop fields inline without heap allocation.
    pub hop_fields: TinyVec<[HopField; 12]>,
}
impl Default for Segment {
    fn default() -> Self {
        Self {
            info_field: InfoField {
                flags: InfoFieldFlags::empty(),
                segment_id: 0,
                timestamp: 0,
            },
            hop_fields: TinyVec::new(),
        }
    }
}

/// Represents an info field in a standard SCION path
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InfoField {
    /// Info field flags
    pub flags: InfoFieldFlags,
    /// Segment ID
    ///
    /// Segment IDs are part of the MAC computation for hop fields.
    ///
    /// Each position in the path, has a segment ID which is computed and modified while the
    /// path is being traversed.
    pub segment_id: u16,
    /// Timestamp when the segment was created
    ///
    /// Used to determine if this segment currently valid.
    pub timestamp: u32,
}
impl InfoField {
    /// Constructs a `InfoField` from a `InfoFieldView`
    pub fn from_view(view: &InfoFieldView) -> Self {
        InfoField {
            flags: view.flags(),
            segment_id: view.segment_id(),
            timestamp: view.timestamp(),
        }
    }
}
impl WireEncode for InfoField {
    fn required_size(&self) -> usize {
        InfoFieldLayout::SIZE_BYTES
    }

    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        // All values are full range, so always valid
        Ok(())
    }

    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        unsafe {
            use InfoFieldLayout as IFL;
            unchecked_bit_range_be_write(buf, IFL::FLAGS_RNG, self.flags.bits());
            unchecked_bit_range_be_write(buf, IFL::RSV_RNG, 0u8);
            unchecked_bit_range_be_write(buf, IFL::SEGMENT_ID_RNG, self.segment_id);
            unchecked_bit_range_be_write(buf, IFL::TIMESTAMP_RNG, self.timestamp);
        }
        self.required_size()
    }
}

/// Represents a hop field in a standard SCION path
///
/// Hop fields contain information about individual hops in a SCION path.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HopField {
    /// Hop field flags
    pub flags: HopFieldFlags,
    /// Hop field expiration units
    ///
    /// The expiration time of a hop field is determined by multiplying the value in this field
    /// by [`EXP_TIME_UNIT`](crate::path::standard::types::EXP_TIME_UNIT)
    ///
    /// After this duration has passed since the segment creation time (found in the info
    /// field), the hop field is considered expired and may not be used for forwarding.
    pub expiration_units: u8,
    /// Hop field construction ingress interface
    ///
    /// A value of 0 indicates that the hop is at the start of the path segment.
    /// The interface number corresponds to the ingress interface used when constructing the
    /// path.
    ///
    /// The construction always starts at a Core router and proceeds towards the Child.
    ///
    /// When traversing the path in the reverse direction from construction (e.g. in a UP
    /// segment to a Core router), this field indicates the egress interface instead.
    pub cons_ingress: u16,
    /// Hop field construction egress interface
    ///
    /// A value of 0 indicates that the hop is at the end of the path segment.
    /// The interface number corresponds to the egress interface used when constructing the
    /// path.
    ///
    /// The construction always starts at a Core router and proceeds towards the Child.
    ///
    /// When traversing the path in the reverse direction from construction (e.g. in a UP
    /// segment to a Core router), this field indicates the ingress interface instead.
    pub cons_egress: u16,
    /// Hop field message authentication code (MAC)
    ///
    /// The MAC is used to ensure the integrity and authenticity of the hop field.
    /// It is computed when a segment is created and verified at each hop.
    pub mac: HopFieldMac,
}
impl Default for HopField {
    fn default() -> Self {
        Self {
            flags: HopFieldFlags::empty(),
            expiration_units: 0,
            cons_ingress: 0,
            cons_egress: 0,
            mac: HopFieldMac([0; 6]),
        }
    }
}
impl HopField {
    /// Constructs a `HopField` from a `HopFieldView`
    pub fn from_view(view: &HopFieldView) -> Self {
        HopField {
            flags: view.flags(),
            expiration_units: view.exp_time(),
            cons_ingress: view.cons_ingress(),
            cons_egress: view.cons_egress(),
            mac: view.mac(),
        }
    }
}
impl HopField {
    /// Creates an empty `HopField` with zeroed fields.
    pub fn empty() -> Self {
        Self {
            flags: HopFieldFlags::empty(),
            expiration_units: 0,
            cons_ingress: 0,
            cons_egress: 0,
            mac: HopFieldMac([0; 6]),
        }
    }
}
// MAC methods
impl HopField {
    /// Recalculates the MAC for this hop field and updates the `mac` field with the new value.
    ///
    /// See [`HopMacCalculate::calculate_mac`](crate::path::standard::mac::HopMacCalculate::calculate_mac) for details on how the MAC is calculated.
    pub fn with_calculated_mac(
        mut self,
        mac_chain_beta: u16,
        timestamp_epoch: u32,
        forwarding_key: &ForwardingKey,
    ) -> Self {
        self.mac = self.calculate_mac(mac_chain_beta, timestamp_epoch, forwarding_key);
        self
    }
}
/// Provides the necessary input for calculating the MAC of a hop field.
/// Automatically implements [`HopMacCalculate`](crate::path::standard::mac::HopMacCalculate)
impl HopMacInputSource for HopField {
    #[inline]
    fn get_mac_input(&self) -> HopMacInput {
        HopMacInput {
            exp_time: self.expiration_units,
            cons_ingress: self.cons_ingress,
            cons_egress: self.cons_egress,
        }
    }
}
impl WireEncode for HopField {
    fn required_size(&self) -> usize {
        HopFieldLayout::SIZE_BYTES
    }

    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        // All values are full range, so always valid
        Ok(())
    }

    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        unsafe {
            use HopFieldLayout as HFL;
            unchecked_bit_range_be_write(buf, HFL::FLAGS_RNG, self.flags.bits());
            unchecked_bit_range_be_write(buf, HFL::EXP_TIME_RNG, self.expiration_units);
            unchecked_bit_range_be_write(buf, HFL::CONS_INGRESS_RNG, self.cons_ingress);
            unchecked_bit_range_be_write(buf, HFL::CONS_EGRESS_RNG, self.cons_egress);
            buf.get_unchecked_mut(HFL::MAC_RNG.aligned_byte_range())
                .copy_from_slice(&self.mac.0);
        }
        self.required_size()
    }
}

/// Support for [`proptest::arbitrary`].
#[cfg(feature = "proptest")]
pub mod ptest {
    use ::proptest::prelude::*;

    use super::*;

    /// Configuration for generating arbitrary [`StandardPath`] values.
    #[derive(Debug, Clone, Default)]
    pub struct ArbitraryPathContext {
        // Not implemented yet, but would allow providing ForwardingKeys for generating valid MACs,
        // or even generating paths valid on a topology
    }

    impl Arbitrary for StandardPath {
        type Parameters = ArbitraryPathContext;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(ctx: Self::Parameters) -> Self::Strategy {
            (
                any::<u8>(),
                prop::collection::vec(Segment::arbitrary_with(ctx), 1..=3),
            )
                .prop_map(|(curr_hop, segments): (u8, Vec<Segment>)| {
                    // A full path can only address up to 63 hops due to the 6-bit limit of the
                    // curr_hop_field.
                    let max_total_hops = StdPathMetaLayout::MAX_TOTAL_HOPS;

                    // ensure the total number of hops does not exceed the maximum allowed for the
                    // number of segments
                    let total_hops: usize = segments.iter().map(|s| s.hop_fields.len()).sum();
                    let mut segments = segments;
                    if total_hops > max_total_hops {
                        let n = segments.len();
                        let base = max_total_hops / n;
                        let extra = max_total_hops % n;
                        for (i, seg) in segments.iter_mut().enumerate() {
                            let limit = base + if i < extra { 1 } else { 0 };
                            seg.hop_fields.truncate(limit.max(1));
                        }
                    }

                    // current_hop must be in range of total hops
                    let total_hops: usize = segments.iter().map(|s| s.hop_fields.len()).sum();
                    let curr_hop = match total_hops {
                        0 => 0,
                        _ => curr_hop % (total_hops as u8),
                    };

                    // current_info_field is defined by which segment the current_hop_field is in
                    let mut hop_count = 0;
                    let mut curr_info = 0;
                    for (i, seg) in segments.iter().enumerate() {
                        hop_count += seg.hop_fields.len();
                        if (curr_hop as usize) < hop_count {
                            curr_info = i as u8;
                            break;
                        }
                    }

                    let segments = segments.into_iter().collect();

                    StandardPath {
                        current_info_field: curr_info,
                        current_hop_field: curr_hop,
                        segments,
                    }
                })
                .boxed()
        }
    }

    impl Arbitrary for Segment {
        type Parameters = ArbitraryPathContext;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(_ctx: Self::Parameters) -> Self::Strategy {
            (
                any::<InfoField>(),
                prop::collection::vec(any::<HopField>(), 1..=63),
            )
                .prop_map(|(info_field, hop_fields)| {
                    Segment {
                        info_field,
                        hop_fields: TinyVec::Heap(hop_fields),
                    }
                })
                .boxed()
        }
    }

    impl Arbitrary for InfoField {
        type Parameters = ();
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
            (any::<InfoFieldFlags>(), any::<u16>(), any::<u32>())
                .prop_map(|(flags, segment_id, timestamp)| {
                    InfoField {
                        flags,
                        segment_id,
                        timestamp,
                    }
                })
                .boxed()
        }
    }

    impl Arbitrary for HopField {
        type Parameters = ();
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
            (
                any::<HopFieldFlags>(),
                any::<u8>(),
                any::<u16>(),
                any::<u16>(),
                any::<[u8; 6]>(),
            )
                .prop_map(
                    |(flags, expiration_units, cons_ingress, cons_egress, mac_bytes)| {
                        HopField {
                            flags,
                            expiration_units,
                            cons_ingress,
                            cons_egress,
                            mac: HopFieldMac(mac_bytes),
                        }
                    },
                )
                .boxed()
        }
    }
}