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
// 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 views
//!
//! See [`View`](crate::core::view) for more information about views in general.

// TODO: Max header lenght is 1020 bytes (255 * 4), so we should be able to use [u8; 1020] as a safe
// construction buffer without checks. Need to check that no view would ever try to go beyond
// that size first.

use std::fmt::Debug;

use crate::{
    core::{
        layout::{BitRange, Layout},
        read::unchecked_bit_range_be_read,
        view::{
            View, ViewConversionError,
            macros::{gen_field_read, gen_field_write, gen_unsafe_field_write, gen_view_impl},
        },
        write::unchecked_bit_range_be_write,
    },
    dataplane_path::{
        standard::view::StandardPathView,
        types::PathType,
        view::{ScionDpPathViewRef, ScionDpPathViewRefMut},
    },
    header::layout::{AddressHeaderLayout, CommonHeaderLayout, ScionHeaderLayout},
    payload::ProtocolNumber,
    scion::{
        address::host_addr::{HostAddressSizeError, WireHostAddr, WireHostAddrType},
        identifier::{asn::Asn, isd::Isd, isd_asn::IsdAsn},
    },
};

/// A view over the SCION headers
///
/// Combines CommonHeader, AddressHeader and PathHeader
#[repr(transparent)]
pub struct ScionHeaderView([u8]);
gen_view_impl!(ScionHeaderView, ScionHeaderLayout);

// Common header
impl ScionHeaderView {
    // Field readers
    gen_field_read!(version, CommonHeaderLayout::VERSION_RNG, u8);
    gen_field_read!(traffic_class, CommonHeaderLayout::TRAFFIC_CLASS_RNG, u8);
    gen_field_read!(flow_id, CommonHeaderLayout::FLOW_ID_RNG, u32);

    /// Returns the next header protocol number.
    #[inline]
    pub fn next_header(&self) -> ProtocolNumber {
        // SAFETY: buffer size is checked on construction
        unsafe { unchecked_bit_range_be_read::<u8>(&self.0, CommonHeaderLayout::NEXT_HEADER_RNG) }
            .into()
    }

    gen_field_read!(payload_len, CommonHeaderLayout::PAYLOAD_LEN_RNG, u16);

    /// Returns the header length in bytes
    #[inline]
    pub fn header_len(&self) -> u16 {
        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_read::<u8>(&self.0, CommonHeaderLayout::HEADER_LEN_RNG) as u16
                * 4
        }
    }
    /// Returns the path type
    #[inline]
    pub fn path_type(&self) -> PathType {
        // SAFETY: buffer size is checked on construction
        unsafe { unchecked_bit_range_be_read::<u8>(&self.0, CommonHeaderLayout::PATH_TYPE_RNG) }
            .into()
    }

    /// Returns the destination address type
    #[inline]
    pub fn dst_addr_type(&self) -> WireHostAddrType {
        // SAFETY: buffer size is checked on construction
        unsafe { unchecked_bit_range_be_read::<u8>(&self.0, CommonHeaderLayout::DST_ADDR_INFO_RNG) }
            .into()
    }

    /// Returns the source address type
    #[inline]
    pub fn src_addr_type(&self) -> WireHostAddrType {
        // SAFETY: buffer size is checked on construction
        unsafe { unchecked_bit_range_be_read::<u8>(&self.0, CommonHeaderLayout::SRC_ADDR_INFO_RNG) }
            .into()
    }

    /// Returns the path type bit range
    // TODO(uniquefine): create constructors for SCMP messages that make this function
    // unnecessary.
    #[inline]
    pub const fn path_type_range(&self) -> BitRange {
        CommonHeaderLayout::PATH_TYPE_RNG
    }
}
// Mut Common header
impl ScionHeaderView {
    // Field writers
    gen_field_write!(set_version, CommonHeaderLayout::VERSION_RNG, u8);
    gen_field_write!(set_traffic_class, CommonHeaderLayout::TRAFFIC_CLASS_RNG, u8);
    gen_field_write!(set_flow_id, CommonHeaderLayout::FLOW_ID_RNG, u32);
    /// Sets the next header protocol number.
    #[inline]
    pub fn set_next_header(&mut self, value: ProtocolNumber) {
        use crate::core::write::unchecked_bit_range_be_write;
        unsafe {
            unchecked_bit_range_be_write::<u8>(
                &mut self.0,
                CommonHeaderLayout::NEXT_HEADER_RNG,
                value.into(),
            )
        }
    }
    gen_unsafe_field_write!(set_payload_len, CommonHeaderLayout::PAYLOAD_LEN_RNG, u16);

    /// Sets the header length in bytes.
    ///
    /// The length must be a multiple of 4, and at most 255 * 4 = 1020 bytes.
    ///
    /// # Safety
    /// Modifying the header length can lead to undefined behavior on subsequent accesses to the
    /// View. If the new length surpasses the actual buffer size, out-of-bounds accesses can occur.
    #[inline]
    pub unsafe fn set_header_len(&mut self, len: u16) {
        debug_assert!(
            len.is_multiple_of(4),
            "Header length must be a multiple of 4"
        );
        debug_assert!(
            len <= ScionHeaderLayout::MAX_SIZE_BYTES as u16,
            "Header length must be at most 1020 bytes"
        );

        let raw_len = (len / 4) as u8;

        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write::<u8>(
                &mut self.0,
                CommonHeaderLayout::HEADER_LEN_RNG,
                raw_len,
            )
        }
    }

    /// Sets the path type
    ///
    /// # Safety
    /// Modifying the path type can lead to undefined behavior on subsequent accesses to the
    /// View. If the required size for the new path type surpasses the actual buffer size,
    /// out-of-bounds accesses can occur.
    #[inline]
    pub unsafe fn set_path_type(&mut self, path_type: PathType) {
        let raw_path_type: u8 = path_type.into();

        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write::<u8>(
                &mut self.0,
                CommonHeaderLayout::PATH_TYPE_RNG,
                raw_path_type,
            )
        }
    }

    /// Sets the destination address type
    ///
    /// This function does not modify the actual address data.
    /// If a different address type should be used, prefer using a loaded packet instead of a view.
    ///
    /// # Safety
    /// This field is changes the size requirements of the header. The caller has to ensure
    /// that the buffer is large enough to accommodate the new address size. If the new size
    /// surpasses the actual buffer size, out-of-bounds accesses can occur on subsequent accesses to
    /// the View.
    #[inline]
    pub unsafe fn set_dst_addr_type(&mut self, addr_type: WireHostAddrType) {
        let addr_info: u8 = addr_type.into();

        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write::<u8>(
                &mut self.0,
                CommonHeaderLayout::DST_ADDR_INFO_RNG,
                addr_info,
            )
        }
    }

    /// Sets the source address type
    ///
    /// This function does not modify the actual address data.
    /// If a different address type should be used, prefer using a loaded packet instead of a view.
    ///
    /// # Safety
    /// This field is changes the size requirements of the header. The caller has to ensure
    /// that the buffer is large enough to accommodate the new address size. If the new size
    /// surpasses the actual buffer size, out-of-bounds accesses can occur on subsequent accesses to
    /// the View.
    #[inline]
    pub unsafe fn set_src_addr_type(&mut self, addr_type: WireHostAddrType) {
        let addr_info: u8 = addr_type.into();

        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write::<u8>(
                &mut self.0,
                CommonHeaderLayout::SRC_ADDR_INFO_RNG,
                addr_info,
            )
        }
    }
}
// Address header
impl ScionHeaderView {
    /// Returns the destination ISD-AS identifier.
    #[inline]
    pub fn dst_ia(&self) -> IsdAsn {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u64>(
                &self.0,
                AddressHeaderLayout::DST_IA_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        IsdAsn::from_u64(val)
    }

    /// Returns the destination ISD
    #[inline]
    pub fn dst_isd(&self) -> Isd {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u16>(
                &self.0,
                AddressHeaderLayout::DST_ISD_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        Isd(val)
    }

    /// Returns the destination ASN
    #[inline]
    pub fn dst_as(&self) -> Asn {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u64>(
                &self.0,
                AddressHeaderLayout::DST_AS_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        Asn(val)
    }

    /// Returns the source ISD-AS identifier.
    #[inline]
    pub fn src_ia(&self) -> IsdAsn {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u64>(
                &self.0,
                AddressHeaderLayout::SRC_IA_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        IsdAsn::from_u64(val)
    }

    /// Returns the source ISD
    #[inline]
    pub fn src_isd(&self) -> Isd {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u16>(
                &self.0,
                AddressHeaderLayout::SRC_ISD_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        Isd(val)
    }

    /// Returns the source ASN
    #[inline]
    pub fn src_as(&self) -> Asn {
        // SAFETY: buffer size is checked on construction
        let val = unsafe {
            unchecked_bit_range_be_read::<u64>(
                &self.0,
                AddressHeaderLayout::SRC_AS_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
            )
        };

        Asn(val)
    }

    /// Attempts to return the destination host address
    ///
    /// If the address type and length do not match, an error is returned.
    #[inline]
    pub fn dst_host_addr(&self) -> Result<WireHostAddr, HostAddressSizeError> {
        let src_len = self.src_addr_type().size();
        let dst_len = self.dst_addr_type().size();
        let range = AddressHeaderLayout::new(src_len, dst_len)
            .dst_host_addr_range()
            .shift(CommonHeaderLayout::SIZE_BYTES);

        // SAFETY: buffer size is checked on construction
        let raw = unsafe { self.0.get_unchecked(range.aligned_byte_range()) };

        WireHostAddr::try_from_parts(self.dst_addr_type(), raw)
    }

    /// Returns the source host address range in the buffer.
    /// If you need to read the host address, use [src_host_addr](Self::src_host_addr) instead,
    /// which also checks that the address type and length match.
    /// TODO(uniquefine): create constructors for SCMP messages that make this function
    /// unnecessary.
    #[inline]
    pub fn src_host_addr_range(&self) -> BitRange {
        let src_len = self.src_addr_type().size();
        let dst_len = self.dst_addr_type().size();
        AddressHeaderLayout::new(src_len, dst_len)
            .src_host_addr_range()
            .shift(CommonHeaderLayout::SIZE_BYTES)
    }

    /// Attempts to return the destination host address
    ///
    /// If the address type and length do not match, an error is returned.
    #[inline]
    pub fn src_host_addr(&self) -> Result<WireHostAddr, HostAddressSizeError> {
        let range = self.src_host_addr_range();

        // SAFETY: buffer size is checked on construction
        let raw = unsafe { self.0.get_unchecked(range.aligned_byte_range()) };

        WireHostAddr::try_from_parts(self.src_addr_type(), raw)
    }
}
// Address header mut
impl ScionHeaderView {
    /// Sets the source ISD
    #[inline]
    pub fn set_src_isd(&mut self, isd: Isd) {
        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write(
                &mut self.0,
                AddressHeaderLayout::SRC_ISD_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
                isd.0,
            )
        }
    }

    /// Sets the source ASN
    #[inline]
    pub fn set_src_as(&mut self, asn: Asn) {
        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write(
                &mut self.0,
                AddressHeaderLayout::SRC_AS_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
                asn.0,
            )
        }
    }

    /// Sets the destination ISD
    #[inline]
    pub fn set_dst_isd(&mut self, isd: Isd) {
        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write(
                &mut self.0,
                AddressHeaderLayout::DST_ISD_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
                isd.0,
            )
        }
    }

    /// Sets the destination ASN
    #[inline]
    pub fn set_dst_as(&mut self, asn: Asn) {
        // SAFETY: buffer size is checked on construction
        unsafe {
            unchecked_bit_range_be_write(
                &mut self.0,
                AddressHeaderLayout::DST_AS_RNG.shift(CommonHeaderLayout::SIZE_BYTES),
                asn.0,
            )
        }
    }

    // Impl Note: no functions to set dst_host_addr and src_host_addr, as both are variable-length
    // and would require shifting the rest of the buffer.
}
// Path header
impl ScionHeaderView {
    /// Returns a view over the path
    #[inline]
    pub fn path(&self) -> ScionDpPathViewRef<'_> {
        let path_offset = CommonHeaderLayout::SIZE_BYTES
            + AddressHeaderLayout::new(self.dst_addr_type().size(), self.src_addr_type().size())
                .size_bytes();

        let len = self.header_len() as usize;

        match self.path_type() {
            PathType::Empty => ScionDpPathViewRef::Empty,
            PathType::Scion => {
                // SAFETY: min buffer size is checked on construction
                let path_buf = unsafe { self.0.get_unchecked(path_offset..len) };
                let path = unsafe { StandardPathView::from_slice_unchecked(path_buf) };

                ScionDpPathViewRef::Standard(path)
            }
            PathType::OneHop => {
                // SAFETY: min buffer size is checked on construction
                let path_size =
                    crate::proto::dataplane_path::onehop::layout::OneHopPathLayout::SIZE_BYTES;
                let path_range = path_offset..path_offset + path_size;
                let path_buf = unsafe { self.0.get_unchecked(path_range) };
                let path = unsafe {
                    crate::proto::dataplane_path::onehop::view::OneHopPathView::from_slice_unchecked(
                        path_buf,
                    )
                };

                ScionDpPathViewRef::OneHop(path)
            }
            pt => {
                // SAFETY: min buffer size is checked on construction
                let path_buf = unsafe { self.0.get_unchecked(path_offset..len) };
                ScionDpPathViewRef::Unsupported {
                    path_type: pt,
                    data: path_buf,
                }
            }
        }
    }

    /// Returns a mutable view over the path
    #[inline]
    pub fn path_mut(&mut self) -> ScionDpPathViewRefMut<'_> {
        let path_offset = CommonHeaderLayout::SIZE_BYTES
            + AddressHeaderLayout::new(self.dst_addr_type().size(), self.src_addr_type().size())
                .size_bytes();

        let len = self.header_len() as usize;

        match self.path_type() {
            PathType::Empty => ScionDpPathViewRefMut::Empty,
            PathType::Scion => {
                // SAFETY: min size is checked on construction of ScionHeaderView
                let path_buf = unsafe { self.0.get_unchecked_mut(path_offset..len) };
                let path = unsafe { StandardPathView::from_mut_slice_unchecked(path_buf) };

                ScionDpPathViewRefMut::Standard(path)
            }
            PathType::OneHop => {
                // SAFETY: min size is checked on construction of ScionHeaderView
                let header_size =
                    crate::proto::dataplane_path::onehop::layout::OneHopPathLayout::SIZE_BYTES;
                let path_range = path_offset..path_offset + header_size;
                let path_buf = unsafe { self.0.get_unchecked_mut(path_range) };
                let path = unsafe {
                    crate::proto::dataplane_path::onehop::view::OneHopPathView::from_mut_slice_unchecked(
                        path_buf,
                    )
                };

                ScionDpPathViewRefMut::OneHop(path)
            }
            pt => {
                // SAFETY: min size is checked on construction of ScionHeaderView
                let path_buf = unsafe { self.0.get_unchecked_mut(path_offset..len) };
                ScionDpPathViewRefMut::Unsupported {
                    path_type: pt,
                    buf: path_buf,
                }
            }
        }
    }
}
impl Debug for ScionHeaderView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let path = self.path();
        f.debug_struct("ScionHeaderView")
            .field("version", &self.version())
            .field("traffic_class", &self.traffic_class())
            .field("flow_id", &self.flow_id())
            .field("next_header", &self.next_header())
            .field("payload_len", &self.payload_len())
            .field("header_len", &self.header_len())
            .field("path_type", &self.path_type())
            .field("dst_addr_type", &self.dst_addr_type())
            .field("src_addr_type", &self.src_addr_type())
            .field("dst_isd", &self.dst_isd())
            .field("dst_as", &self.dst_as())
            .field("src_isd", &self.src_isd())
            .field("src_as", &self.src_as())
            .field("dst_host_addr", &self.dst_host_addr())
            .field("src_host_addr", &self.src_host_addr())
            .field("path", &path)
            .finish()
    }
}