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
// 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 header models

use crate::{
    address::addr::ScionAddr,
    core::{
        convert::{FromView, TryFromView},
        encode::{EncodeError, InvalidStructureError, WireEncode},
        layout::Layout,
        view::ViewConversionError,
        write::unchecked_bit_range_be_write,
    },
    dataplane_path::{model::DpPath, types::PathType},
    header::{
        layout::{AddressHeaderLayout, CommonHeaderLayout, ScionHeaderLayout},
        view::ScionHeaderView,
    },
    payload::ProtocolNumber,
    scion::{
        address::host_addr::{WireHostAddr, WireHostAddrType},
        identifier::isd_asn::IsdAsn,
    },
};

/// Represents a SCION packet header
///
/// This structure contains all the fields of a SCION packet header,
/// including the common header, address header, and path information.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ScionPacketHeader {
    /// The common header of the SCION packet
    pub common: CommonHeader,
    /// The address header of the SCION packet
    pub address: AddressHeader,
    /// The path information of the SCION packet
    pub path: DpPath,
}
impl ScionPacketHeader {
    /// Returns the size of the SCION packet header in 4-byte units used in the header length field.
    #[inline]
    fn size_units(&self) -> u8 {
        (self.required_size() / 4) as u8
    }
}
// Wire Encode (needs size, so can't use trait)
impl ScionPacketHeader {
    /// Returns the size required for the wire encoding.
    ///
    /// ## Safety
    /// This size must be correct, it is used to validate buffer sizes in `encode`.
    /// If this size is smaller than the actual encoded size, undefined behavior will occur.
    #[inline]
    pub fn required_size(&self) -> usize {
        CommonHeaderLayout::SIZE_BYTES + self.address.required_size() + self.path.required_size()
    }

    /// Validates that all fields in the structure are valid for encoding.
    ///
    /// Note: This only checks the minimal set of fields required for encoding, do not expect
    /// comprehensive validation.
    ///
    /// Returns Ok(()) if valid, otherwise a static error reference.
    #[inline]
    pub fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        let required_size = self.required_size();
        if !required_size.is_multiple_of(4) {
            return Err(InvalidStructureError::from(
                "header size must be a multiple of 4 bytes",
            ));
        }

        if required_size > ScionHeaderLayout::MAX_SIZE_BYTES {
            return Err(InvalidStructureError::from(
                "header size exceeds maximum encodeable value of 1020 bytes",
            ));
        }

        self.common.valid()?;
        self.address.wire_valid()?;
        self.path.wire_valid()?;
        Ok(())
    }

    /// Writes the wire encoding into the provided buffer.
    ///
    /// Returns the number of bytes written.
    ///
    /// ## SAFETY
    /// 1. The buffer must be at least `self.required_size()` bytes long
    /// 2. The structure must be valid for encoding, i.e., `self.valid()` must return `Ok(())`
    #[inline]
    pub unsafe fn encode_unchecked(&self, buf: &mut [u8], payload_size: u16) -> usize {
        unsafe {
            use CommonHeaderLayout as CHL;
            // Encode common header
            self.common.encode_unchecked(
                buf,
                self.size_units(),
                self.path.path_type(),
                self.address.dst_addr_type(),
                self.address.src_addr_type(),
                payload_size,
            );

            // Encode address header
            let offset = CHL::SIZE_BYTES;
            let address_buf = buf.split_at_mut_unchecked(offset).1;
            self.address.encode_unchecked(address_buf);

            // Encode path
            let offset = offset + self.address.required_size();
            let path_buf = buf.split_at_mut_unchecked(offset).1;
            self.path.encode_unchecked(path_buf);
        }

        self.required_size()
    }

    /// Writes the wire encoding into the provided buffer.
    ///
    /// Returns the number of bytes written on success, or `Err(usize)` of the required size if the
    /// buffer is too small or the packet.
    ///
    /// The buffer must be at least `self.required_size()` bytes long.
    #[inline]
    pub fn try_encode(&self, buf: &mut [u8], payload_size: u16) -> Result<usize, EncodeError> {
        self.wire_valid()?;

        let required_size = self.required_size();
        if buf.len() < required_size {
            return Err(EncodeError::BufferTooSmall(required_size));
        }

        // SAFETY: buffer length is checked above
        Ok(unsafe { self.encode_unchecked(buf, payload_size) })
    }
}
impl TryFromView for ScionPacketHeader {
    type ViewType = ScionHeaderView;
    #[inline]
    fn try_from_view(view: &Self::ViewType) -> Result<Self, ViewConversionError> {
        Ok(ScionPacketHeader {
            common: CommonHeader::from_view(view),
            address: AddressHeader::try_from_view(view)?,
            path: DpPath::from_view(&view.path()),
        })
    }
}

/// Represents the common header of a SCION packet
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CommonHeader {
    /// Traffic class of the SCION packet
    pub traffic_class: u8,
    /// Flow ID of the SCION packet
    pub flow_id: u32,
    /// Next header type
    ///
    /// Indicates the type of header that follows the SCION header. E.g., UDP, TCP, etc.
    pub next_header: ProtocolNumber,
}
// Wire Encode (needs size, so can't use trait)
impl CommonHeader {
    /// Validates that all fields in the `CommonHeader` are valid for encoding
    #[inline]
    pub fn valid(&self) -> Result<(), InvalidStructureError> {
        use CommonHeaderLayout as CHL;

        if self.flow_id > CHL::FLOW_ID_RNG.max_uint() as u32 {
            return Err("flow_id exceeds maximum encodeable value".into());
        }

        // Payload size is u16, so all values are valid
        // Next header is a u8, so all values are valid

        Ok(())
    }

    const VERSION: u8 = 0;
    /// Encodes the `CommonHeader` into the provided buffer
    /// # Safety
    /// - The implementation may use unchecked indexing operations and relies on the caller to
    ///   provide a sufficiently large buffer (at least `CommonHeaderLayout::SIZE_BYTES` bytes).
    #[inline]
    pub unsafe fn encode_unchecked(
        &self,
        buf: &mut [u8],
        header_len_units: u8,
        path_type: PathType,
        dst_addr_type: WireHostAddrType,
        src_addr_type: WireHostAddrType,
        payload_size: u16,
    ) -> usize {
        unsafe {
            use CommonHeaderLayout as CHL;
            // Encode common header
            unchecked_bit_range_be_write(buf, CHL::VERSION_RNG, Self::VERSION);
            unchecked_bit_range_be_write(buf, CHL::TRAFFIC_CLASS_RNG, self.traffic_class);
            unchecked_bit_range_be_write(buf, CHL::FLOW_ID_RNG, self.flow_id);
            unchecked_bit_range_be_write::<u8>(buf, CHL::NEXT_HEADER_RNG, self.next_header.into());
            unchecked_bit_range_be_write(buf, CHL::HEADER_LEN_RNG, header_len_units);
            unchecked_bit_range_be_write(buf, CHL::PAYLOAD_LEN_RNG, payload_size);
            unchecked_bit_range_be_write::<u8>(buf, CHL::PATH_TYPE_RNG, path_type.into());
            let dst_addr_info: u8 = dst_addr_type.into();
            unchecked_bit_range_be_write::<u8>(buf, CHL::DST_ADDR_INFO_RNG, dst_addr_info);
            let src_addr_info: u8 = src_addr_type.into();
            unchecked_bit_range_be_write::<u8>(buf, CHL::SRC_ADDR_INFO_RNG, src_addr_info);
            unchecked_bit_range_be_write(buf, CHL::RSV_RNG, 0u16); // Reserved
        }

        CommonHeaderLayout::SIZE_BYTES
    }
}
impl FromView for CommonHeader {
    type ViewType = ScionHeaderView;
    #[inline]
    fn from_view(view: &Self::ViewType) -> Self {
        debug_assert!(view.version() == Self::VERSION, "Unsupported SCION version");
        CommonHeader {
            traffic_class: view.traffic_class(),
            flow_id: view.flow_id(),
            next_header: view.next_header(),
        }
    }
}

/// Represents the address header of a SCION packet
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AddressHeader {
    /// Destination ISD
    pub dst_ia: IsdAsn,
    /// Source ISD
    pub src_ia: IsdAsn,
    /// Destination host address
    pub dst_host_addr: WireHostAddr,
    /// Source host address
    pub src_host_addr: WireHostAddr,
}
impl AddressHeader {
    /// Constructs an `AddressHeader` from the given source and destination `ScionAddr`
    #[inline]
    pub fn new(src: ScionAddr, dst: ScionAddr) -> Self {
        AddressHeader {
            dst_ia: dst.isd_asn(),
            src_ia: src.isd_asn(),
            dst_host_addr: dst.host().into(),
            src_host_addr: src.host().into(),
        }
    }

    /// Returns the destination address type
    #[inline]
    pub fn dst_addr_type(&self) -> WireHostAddrType {
        self.dst_host_addr.addr_type()
    }

    /// Returns the source address type
    #[inline]
    pub fn src_addr_type(&self) -> WireHostAddrType {
        self.src_host_addr.addr_type()
    }
}
impl WireEncode for AddressHeader {
    #[inline]
    fn required_size(&self) -> usize {
        AddressHeaderLayout::new(
            self.dst_host_addr.required_size() as u8,
            self.src_host_addr.required_size() as u8,
        )
        .size_bytes()
    }

    #[inline]
    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        // ISD and ASN are newtypes, so assumed valid

        self.dst_host_addr.wire_valid()?;
        self.src_host_addr.wire_valid()?;

        Ok(())
    }

    #[inline]
    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        unsafe {
            use AddressHeaderLayout as AHL;
            unchecked_bit_range_be_write(buf, AHL::DST_ISD_RNG, self.dst_ia.isd().0);
            unchecked_bit_range_be_write(buf, AHL::DST_AS_RNG, self.dst_ia.asn().0);
            unchecked_bit_range_be_write(buf, AHL::SRC_ISD_RNG, self.src_ia.isd().0);
            unchecked_bit_range_be_write(buf, AHL::SRC_AS_RNG, self.src_ia.asn().0);

            let layout = AddressHeaderLayout::new(
                self.src_host_addr.required_size() as u8,
                self.dst_host_addr.required_size() as u8,
            );

            {
                let dst_host_buf =
                    buf.get_unchecked_mut(layout.dst_host_addr_range().aligned_byte_range());
                self.dst_host_addr.encode_unchecked(dst_host_buf);
            }

            {
                let src_host_buf =
                    buf.get_unchecked_mut(layout.src_host_addr_range().aligned_byte_range());
                self.src_host_addr.encode_unchecked(src_host_buf);
            }
        }

        self.required_size()
    }
}
impl TryFromView for AddressHeader {
    type ViewType = ScionHeaderView;
    #[inline]
    fn try_from_view(view: &Self::ViewType) -> Result<Self, ViewConversionError> {
        Ok(AddressHeader {
            dst_ia: view.dst_ia(),
            src_ia: view.src_ia(),
            dst_host_addr: view
                .dst_host_addr()
                .map_err(|_| ViewConversionError::Other("invalid dst_host_addr"))?,
            src_host_addr: view
                .src_host_addr()
                .map_err(|_| ViewConversionError::Other("invalid src_host_addr"))?,
        })
    }
}

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

    use super::*;
    use crate::dataplane_path::model::DpPath;

    /// Configuration for generating arbitrary [`ScionPacketHeader`] values.
    ///
    /// Composes sub-parameters for the address header (host address variant weights)
    /// and the path.
    #[derive(Debug, Clone, Default)]
    pub struct ArbitraryScionPacketHeaderParams {
        /// Parameters for generating destination host addresses.
        pub dst_host_addr: <WireHostAddr as Arbitrary>::Parameters,
        /// Parameters for generating source host addresses.
        pub src_host_addr: <WireHostAddr as Arbitrary>::Parameters,
        /// Parameters for generating paths.
        pub path: <DpPath as Arbitrary>::Parameters,
    }

    impl Arbitrary for ScionPacketHeader {
        type Parameters = ArbitraryScionPacketHeaderParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            let traffic_class = any::<u8>();
            let flow_id = 0u32..=0xF_FFFFu32;
            let next_header = any::<u8>();

            let dst_ia = any::<IsdAsn>();
            let src_ia = any::<IsdAsn>();

            let dst_host_addr = WireHostAddr::arbitrary_with(params.dst_host_addr);
            let src_host_addr = WireHostAddr::arbitrary_with(params.src_host_addr);

            let path = DpPath::arbitrary_with(params.path);

            (
                traffic_class,
                flow_id,
                next_header,
                dst_ia,
                src_ia,
                dst_host_addr,
                src_host_addr,
                path,
            )
                .prop_map(
                    |(
                        traffic_class,
                        flow_id,
                        next_header,
                        dst_ia,
                        src_ia,
                        dst_host_addr,
                        src_host_addr,
                        path,
                    )| {
                        Self {
                            common: CommonHeader {
                                traffic_class,
                                flow_id,
                                next_header: next_header.into(),
                            },
                            address: AddressHeader {
                                dst_ia,
                                src_ia,
                                dst_host_addr,
                                src_host_addr,
                            },
                            path,
                        }
                    },
                )
                .boxed()
        }
    }
}