sciparse 0.5.2

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
// 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.

use std::mem::transmute;

use super::classify::{ClassifiedPacketView, ClassifyError};
use crate::{
    core::view::{View, ViewConversionError},
    header::{layout::ScionHeaderLayout, view::ScionHeaderView},
    payload::{ProtocolNumber, scmp::view::ScmpPayloadView, udp::view::UdpDatagramView},
};

// Marker types for different view variants.
/// Marker type for a raw (untyped) SCION packet view.
pub struct Raw;
/// Marker type for a SCION/UDP packet view.
pub struct Udp;
/// Marker type for a SCION/SCMP packet view.
pub struct Scmp;

/// A view over a complete SCION packet
#[repr(transparent)]
pub struct ScionPacketView<T = Raw>(std::marker::PhantomData<T>, [u8]);
impl<T> ScionPacketView<T> {
    /// Returns a view over the SCION headers
    #[inline]
    pub fn header(&self) -> &ScionHeaderView {
        // Safety: Buffer size is checked on construction of ScionPacketView
        unsafe {
            let header_len = ScionHeaderView::from_slice_unchecked(&self.1).header_len() as usize;
            ScionHeaderView::from_slice_unchecked(self.1.get_unchecked(..header_len))
        }
    }

    /// Returns a mutable view over the SCION headers
    #[inline]
    pub fn header_mut(&mut self) -> &mut ScionHeaderView {
        // Safety: Buffer size is checked on construction of ScionPacketView
        unsafe {
            let header_len = ScionHeaderView::from_slice_unchecked(&self.1).header_len() as usize;
            ScionHeaderView::from_mut_slice_unchecked(self.1.get_unchecked_mut(..header_len))
        }
    }

    /// Returns a slice of the payload
    #[inline]
    pub fn payload(&self) -> &[u8] {
        // Safety: Buffer size is checked on construction of ScionPacketView
        unsafe {
            let header = self.header();
            let header_len = header.header_len() as usize;
            let payload_len = header.payload_len() as usize;

            let tail_len = self.1.len().saturating_sub(header_len);
            let truncated_payload_len = std::cmp::min(payload_len, tail_len);

            self.1
                .get_unchecked(header_len..header_len + truncated_payload_len)
        }
    }
}

/// A view over a raw SCION packet (payload protocol unspecified).
pub type ScionRawPacketView = ScionPacketView<Raw>;
impl View for ScionRawPacketView {
    #[inline]
    fn has_required_size(buf: &[u8]) -> Result<usize, ViewConversionError> {
        // Safety: This validates that the buffer is large enough for the header,
        // The payload may be truncated, which is handled in the accessor
        let layout = ScionHeaderLayout::from_slice(buf)?;

        let packet_len = std::cmp::min(layout.header_len + layout.payload_len, buf.len());
        Ok(packet_len)
    }

    #[inline]
    unsafe fn from_slice_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_mut_slice_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_boxed_unchecked(buf: Box<[u8]>) -> Box<Self> {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.1
    }

    #[inline]
    fn as_bytes_boxed(self: Box<Self>) -> Box<[u8]> {
        // SAFETY: This is safe because the view no longer exists after this call.
        // This just returns the underlying buffer.
        unsafe { std::mem::transmute(self) }
    }

    #[inline]
    fn as_bytes(&self) -> &[u8] {
        &self.1
    }
}
impl ScionRawPacketView {
    /// Returns a mutable slice of the payload
    #[inline]
    pub fn payload_mut(&mut self) -> &mut [u8] {
        // Safety: Buffer size is checked on construction of ScionPacketView
        unsafe {
            let header = self.header();
            let header_len = header.header_len() as usize;
            let payload_len = header.payload_len() as usize;

            let tail_len = self.1.len().saturating_sub(header_len);
            let truncated_payload_len = std::cmp::min(payload_len, tail_len);

            self.1
                .get_unchecked_mut(header_len..header_len + truncated_payload_len)
        }
    }

    /// Classifies this packet by inspecting its `next_header` field.
    ///
    /// For UDP packets the destination port is read from the UDP header.
    /// For SCMP packets the destination port is deduced from the message type:
    /// - informational messages (echo request/reply, traceroute request/reply): identifier field
    /// - error messages: source port of the quoted inner UDP datagram (if parseable)
    ///
    /// Returns [`ClassifiedPacketView::Other`] only for unknown `next_header` values. SCMP packets
    /// are always classified as [`ClassifiedPacketView::Scmp`], with `dst_port` set to `None` when
    /// no port can be deduced. Never allocates.
    pub fn classify(&self) -> Result<ClassifiedPacketView<'_>, ClassifyError> {
        match self.header().next_header().into() {
            ProtocolNumber::Udp => {
                let udp =
                    ScionUdpPacketView::try_from_raw(self).map_err(ClassifyError::MalformedUdp)?;
                Ok(ClassifiedPacketView::Udp(udp))
            }
            ProtocolNumber::Scmp => {
                let scmp = ScionScmpPacketView::try_from_raw(self)
                    .map_err(ClassifyError::MalformedScmp)?;
                Ok(ClassifiedPacketView::Scmp(scmp))
            }
            _ => Ok(ClassifiedPacketView::Other(self)),
        }
    }

    /// Tries to interpret this packet as a SCION/UDP packet.
    ///
    /// Checks that the payload is large enough for a UDP header but does not verify the
    /// `next_header` field.
    pub fn try_into_udp(&self) -> Result<&ScionUdpPacketView, ViewConversionError> {
        ScionUdpPacketView::try_from_raw(self)
    }

    /// Converts this packet view into a mutable UDP packet view. This only checks that the payload
    /// is large enough for a UDP header but does not check the packets NextHeader field.
    pub fn try_into_udp_mut(&mut self) -> Result<&mut ScionUdpPacketView, ViewConversionError> {
        ScionUdpPacketView::try_from_raw_mut(self)
    }

    /// Converts this packet view into a UDP packet view. This only checks that the payload is
    /// large enough for a UDP header but does not check the packets NextHeader field.
    pub fn try_into_udp_owned(
        self: Box<Self>,
    ) -> Result<Box<ScionUdpPacketView>, ViewConversionError> {
        ScionUdpPacketView::try_from_raw_owned(self)
    }

    /// Tries to interpret this packet as a SCION/SCMP packet.
    ///
    /// Checks that the payload is large enough for a SCMP header but does not verify the
    /// `next_header` field.
    pub fn try_into_scmp(&self) -> Result<&ScionScmpPacketView, ViewConversionError> {
        ScionScmpPacketView::try_from_raw(self)
    }

    /// Converts this packet view into a mutable SCMP packet view. This only checks that the payload
    /// is large enough for a SCMP header but does not check the packets NextHeader field.
    pub fn try_into_scmp_mut(&mut self) -> Result<&mut ScionScmpPacketView, ViewConversionError> {
        ScionScmpPacketView::try_from_raw_mut(self)
    }

    /// Converts this packet view into a SCMP packet view. This only checks that the payload is
    /// large enough for a SCMP header but does not check the packets NextHeader field.
    pub fn try_into_scmp_owned(
        self: Box<Self>,
    ) -> Result<Box<ScionScmpPacketView>, ViewConversionError> {
        ScionScmpPacketView::try_from_raw_owned(self)
    }
}

/// A view over a SCION packet whose payload is a UDP datagram.
pub type ScionUdpPacketView = ScionPacketView<Udp>;
impl View for ScionUdpPacketView {
    #[inline]
    fn has_required_size(buf: &[u8]) -> Result<usize, ViewConversionError> {
        let packet_len = ScionRawPacketView::has_required_size(buf)?;
        let view = unsafe { ScionRawPacketView::from_slice_unchecked(buf) };
        // Note: we only check that the buffer is large enough for a UDP header, not
        // that the packet is actually a udp packet (the next_header field could be something else).
        _ = UdpDatagramView::has_required_size(view.payload())?;
        Ok(packet_len)
    }

    #[inline]
    unsafe fn from_slice_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_mut_slice_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_boxed_unchecked(buf: Box<[u8]>) -> Box<Self> {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.1
    }

    #[inline]
    fn as_bytes_boxed(self: Box<Self>) -> Box<[u8]> {
        // SAFETY: repr(transparent) over [u8], identical fat pointer layout
        unsafe { transmute(self) }
    }

    #[inline]
    fn as_bytes(&self) -> &[u8] {
        &self.1
    }
}
impl ScionUdpPacketView {
    /// Converts a raw SCION packet into a UDP packet view. This only checks that the payload is
    /// large enough for a UDP header but does not check the packets NextHeader field.
    pub fn try_from_raw(raw: &ScionRawPacketView) -> Result<&Self, ViewConversionError> {
        // There won't be any trailing bytes, so we can just use from_slice.
        let (view, _) = ScionUdpPacketView::from_slice(raw.as_bytes())?;
        Ok(view)
    }

    /// Converts a raw SCION packet into a UDP packet view. This only checks that the payload is
    /// large enough for a UDP header but does not check the packets NextHeader field.
    pub fn try_from_raw_mut(
        raw: &mut ScionRawPacketView,
    ) -> Result<&mut Self, ViewConversionError> {
        // There won't be any trailing bytes, so we can just use from_mut_slice.
        let (view, _) = {
            // SAFETY: ScionUdpPacketView does not offer safe functions to change the size of the
            // buffer or mutable access to fields that would cause out of bounds access.
            unsafe { ScionUdpPacketView::from_mut_slice(raw.as_bytes_mut())? }
        };
        Ok(view)
    }

    /// Converts a raw SCION packet into a UDP packet view. This only checks that the payload is
    /// large enough for a UDP header but does not check the packets NextHeader field.
    pub fn try_from_raw_owned(
        raw: Box<ScionRawPacketView>,
    ) -> Result<Box<Self>, ViewConversionError> {
        ScionUdpPacketView::from_boxed(raw.as_bytes_boxed())
    }

    /// Converts a UDP packet view into a raw SCION packet view.
    pub fn into_raw(&self) -> &ScionRawPacketView {
        // Safety: The buffer is large enough for a SCION raw packet.
        unsafe { ScionRawPacketView::from_slice_unchecked(self.as_bytes()) }
    }

    /// Converts a UDP packet view into a raw SCION packet view.
    pub fn into_raw_mut(&mut self) -> &mut ScionRawPacketView {
        // Safety: The buffer is large enough for a SCION raw packet.
        unsafe { ScionRawPacketView::from_mut_slice_unchecked(self.as_bytes_mut()) }
    }

    /// Converts a UDP packet view into a raw SCION packet view.
    pub fn into_raw_owned(self: Box<Self>) -> Box<ScionRawPacketView> {
        unsafe { ScionRawPacketView::from_boxed_unchecked(self.as_bytes_boxed()) }
    }

    /// Returns a UDP datagram view over packets payload.
    /// This returned view only includes the part of the payload slice that is actually taken up by
    /// the UDP datagram.
    pub fn udp(&self) -> &UdpDatagramView {
        // The buffer size was already checked when creating the ScionUdpPacketView.
        let (view, _) = UdpDatagramView::from_slice(self.payload())
            .expect("udp payload is not large enough for a UDP header");
        view
    }
}
impl<'a> TryFrom<&'a ScionRawPacketView> for &'a ScionUdpPacketView {
    type Error = ViewConversionError;

    fn try_from(value: &'a ScionRawPacketView) -> Result<Self, Self::Error> {
        ScionUdpPacketView::try_from_raw(value)
    }
}
impl<'a> TryFrom<&'a mut ScionRawPacketView> for &'a mut ScionUdpPacketView {
    type Error = ViewConversionError;

    fn try_from(value: &'a mut ScionRawPacketView) -> Result<Self, Self::Error> {
        ScionUdpPacketView::try_from_raw_mut(value)
    }
}
impl TryFrom<Box<ScionRawPacketView>> for Box<ScionUdpPacketView> {
    type Error = ViewConversionError;

    fn try_from(value: Box<ScionRawPacketView>) -> Result<Self, Self::Error> {
        ScionUdpPacketView::try_from_raw_owned(value)
    }
}
impl<'a> From<&'a ScionUdpPacketView> for &'a ScionRawPacketView {
    fn from(value: &'a ScionUdpPacketView) -> Self {
        value.into_raw()
    }
}
impl<'a> From<&'a mut ScionUdpPacketView> for &'a mut ScionRawPacketView {
    fn from(value: &'a mut ScionUdpPacketView) -> Self {
        value.into_raw_mut()
    }
}
impl From<Box<ScionUdpPacketView>> for Box<ScionRawPacketView> {
    fn from(value: Box<ScionUdpPacketView>) -> Self {
        value.into_raw_owned()
    }
}

/// A view over a SCION packet whose payload is an SCMP message.
pub type ScionScmpPacketView = ScionPacketView<Scmp>;
impl View for ScionScmpPacketView {
    #[inline]
    fn has_required_size(buf: &[u8]) -> Result<usize, ViewConversionError> {
        let packet_len = ScionRawPacketView::has_required_size(buf)?;
        let view = unsafe { ScionRawPacketView::from_slice_unchecked(buf) };
        // Note: we only check that the buffer is large enough for the SCMP message.
        // The next_header field could be something else.
        _ = ScmpPayloadView::has_required_size(view.payload())?;
        Ok(packet_len)
    }

    #[inline]
    unsafe fn from_slice_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_mut_slice_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn from_boxed_unchecked(buf: Box<[u8]>) -> Box<Self> {
        // SAFETY: see View trait documentation
        unsafe { transmute(buf) }
    }

    #[inline]
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.1
    }

    #[inline]
    fn as_bytes_boxed(self: Box<Self>) -> Box<[u8]> {
        // SAFETY: repr(transparent) over [u8], identical fat pointer layout
        unsafe { transmute(self) }
    }

    #[inline]
    fn as_bytes(&self) -> &[u8] {
        &self.1
    }
}
impl<'a> ScionScmpPacketView {
    /// Converts a raw SCION packet into a SCMP packet view. This only checks that the payload is
    /// large enough for a SCMP header but does not check the packets NextHeader field.
    pub fn try_from_raw(raw: &'a ScionRawPacketView) -> Result<&'a Self, ViewConversionError> {
        // There won't be any trailing bytes, so we can just use from_slice.
        let (view, _) = ScionScmpPacketView::from_slice(raw.as_bytes())?;
        Ok(view)
    }

    /// Converts a raw SCION packet into a SCMP packet view. This only checks that the payload is
    /// large enough for a SCMP header but does not check the packets NextHeader field.
    pub fn try_from_raw_mut(
        raw: &'a mut ScionRawPacketView,
    ) -> Result<&'a mut Self, ViewConversionError> {
        // We disregard any trailing bytes.
        let (view, _) = {
            // SAFETY: ScionScmpPacketView does not offer safe functions to change the size of the
            // buffer or mutable access to fields that would cause out of bounds access.
            unsafe { ScionScmpPacketView::from_mut_slice(raw.as_bytes_mut())? }
        };
        Ok(view)
    }

    /// Converts a raw SCION packet into a SCMP packet view. This only checks that the payload
    /// is large enough for a SCMP header but does not check the packets NextHeader field.
    pub fn try_from_raw_owned(
        raw: Box<ScionRawPacketView>,
    ) -> Result<Box<Self>, ViewConversionError> {
        // We disregard any trailing bytes.
        ScionScmpPacketView::from_boxed(raw.as_bytes_boxed())
    }

    /// Converts a SCMP packet view into a raw SCION packet view.
    pub fn into_raw(&self) -> &ScionRawPacketView {
        // Safety: The buffer is large enough for a SCION raw packet.
        unsafe { ScionRawPacketView::from_slice_unchecked(self.as_bytes()) }
    }

    /// Converts a SCMP packet view into a raw SCION packet view.
    ///
    /// # Safety
    /// The caller must ensure that the buffer is not mutated in a way that would invalidate the
    /// view. e.g. by changing the fields that have an effect on `has_required_size`.
    pub unsafe fn into_raw_mut(&mut self) -> &mut ScionRawPacketView {
        unsafe { ScionRawPacketView::from_mut_slice_unchecked(self.as_bytes_mut()) }
    }

    /// Converts a SCMP packet view into a raw SCION packet view.
    pub fn into_raw_owned(self: Box<Self>) -> Box<ScionRawPacketView> {
        unsafe { ScionRawPacketView::from_boxed_unchecked(self.as_bytes_boxed()) }
    }

    /// Returns a SCMP payload view over packets payload.
    /// This returned view only includes the part of the payload slice that is actually taken up by
    /// the SCMP message.
    pub fn scmp(&self) -> &ScmpPayloadView {
        // The buffer size was already checked when creating the ScionScmpPacketView.
        let (view, _) = ScmpPayloadView::from_slice(self.payload())
            .expect("scmp payload is not large enough for a SCMP header");
        view
    }
}
impl<'a> TryFrom<&'a ScionRawPacketView> for &'a ScionScmpPacketView {
    type Error = ViewConversionError;

    fn try_from(value: &'a ScionRawPacketView) -> Result<Self, Self::Error> {
        ScionScmpPacketView::try_from_raw(value)
    }
}
impl<'a> TryFrom<&'a mut ScionRawPacketView> for &'a mut ScionScmpPacketView {
    type Error = ViewConversionError;

    fn try_from(value: &'a mut ScionRawPacketView) -> Result<Self, Self::Error> {
        ScionScmpPacketView::try_from_raw_mut(value)
    }
}
impl TryFrom<Box<ScionRawPacketView>> for Box<ScionScmpPacketView> {
    type Error = ViewConversionError;

    fn try_from(value: Box<ScionRawPacketView>) -> Result<Self, Self::Error> {
        ScionScmpPacketView::try_from_raw_owned(value)
    }
}
impl<'a> From<&'a ScionScmpPacketView> for &'a ScionRawPacketView {
    fn from(value: &'a ScionScmpPacketView) -> Self {
        value.into_raw()
    }
}
impl From<Box<ScionScmpPacketView>> for Box<ScionRawPacketView> {
    fn from(value: Box<ScionScmpPacketView>) -> Self {
        value.into_raw_owned()
    }
}