Skip to main content

etherparse/net/
ipv6_header_slice.rs

1use crate::*;
2use core::slice::from_raw_parts;
3
4/// A slice containing an ipv6 header of a network package.
5#[derive(Copy, Clone, Debug, Eq, PartialEq)]
6pub struct Ipv6HeaderSlice<'a> {
7    slice: &'a [u8],
8}
9
10impl<'a> Ipv6HeaderSlice<'a> {
11    /// Creates a slice containing an ipv6 header (without header extensions).
12    pub fn from_slice(slice: &'a [u8]) -> Result<Ipv6HeaderSlice<'a>, err::ipv6::HeaderSliceError> {
13        use err::ipv6::{HeaderError::*, HeaderSliceError::*};
14
15        // check length
16        if slice.len() < Ipv6Header::LEN {
17            return Err(Len(err::LenError {
18                required_len: Ipv6Header::LEN,
19                len: slice.len(),
20                len_source: LenSource::Slice,
21                layer: err::Layer::Ipv6Header,
22                layer_start_offset: 0,
23            }));
24        }
25
26        // read version & ihl
27        //
28        // SAFETY:
29        // This is safe as the slice len is checked to be
30        // at least 40 bytes at the start of the function.
31        let version_number = unsafe { slice.get_unchecked(0) >> 4 };
32
33        // check version
34        if 6 != version_number {
35            return Err(Content(UnexpectedVersion { version_number }));
36        }
37
38        // all good
39        Ok(Ipv6HeaderSlice {
40            // SAFETY:
41            // This is safe as the slice length is checked to be
42            // at least Ipv6Header::LEN (40)
43            // at the start of the function.
44            slice: unsafe { from_raw_parts(slice.as_ptr(), Ipv6Header::LEN) },
45        })
46    }
47
48    /// Converts the given slice into a ipv6 header slice WITHOUT any
49    /// checks to ensure that the data present is an ipv4 header or that the
50    /// slice length is matching the header length.
51    ///
52    /// If you are not sure what this means, use [`Ipv6HeaderSlice::from_slice`]
53    /// instead.
54    ///
55    /// # Safety
56    ///
57    /// It must ensured that the slice length is at least [`Ipv6Header::LEN`].
58    #[inline]
59    pub(crate) unsafe fn from_slice_unchecked(slice: &[u8]) -> Ipv6HeaderSlice<'_> {
60        Ipv6HeaderSlice { slice }
61    }
62
63    /// Returns the slice containing the ipv6 header
64    #[inline]
65    pub fn slice(&self) -> &'a [u8] {
66        self.slice
67    }
68
69    /// Read the "version" field from the slice (should be 6).
70    #[inline]
71    pub fn version(&self) -> u8 {
72        // SAFETY:
73        // Safe as the slice length is set to
74        // Ipv6Header::LEN (40) during construction
75        // of the struct.
76        unsafe { *self.slice.get_unchecked(0) >> 4 }
77    }
78
79    /// Read the "traffic class" field from the slice.
80    #[inline]
81    pub fn traffic_class(&self) -> u8 {
82        // SAFETY:
83        // Safe as the slice length is set to
84        // Ipv6Header::LEN (40) during construction
85        // of the struct.
86        unsafe { (self.slice.get_unchecked(0) << 4) | (self.slice.get_unchecked(1) >> 4) }
87    }
88
89    /// Returns the [`IpEcn`] decoded from the `traffic_class` octet.
90    #[inline]
91    pub fn ecn(&self) -> IpEcn {
92        // SAFETY: Safe as value can only be at most 0b11 as it is bit-and-ed with 0b11.
93        unsafe { IpEcn::new_unchecked(self.traffic_class() & 0b0000_0011) }
94    }
95
96    /// Returns the [`IpDscp`] decoded from the `traffic_class` octet.
97    #[inline]
98    pub fn dscp(&self) -> IpDscp {
99        // SAFETY: Safe as value can not be bigger than IpDscp::MAX_U8 as it
100        //         is bit masked with IpDscp::MAX_U8 (0b0011_1111).
101        unsafe { IpDscp::new_unchecked((self.traffic_class() >> 2) & 0b0011_1111) }
102    }
103
104    /// Read the "flow label" field from the slice.
105    #[inline]
106    pub fn flow_label(&self) -> Ipv6FlowLabel {
107        unsafe {
108            // SAFETY:
109            // Slice access safe as the slice length is set to Ipv6Header::LEN (40)
110            // during construction of the struct.
111            // Conversion to flow label safe as the bitmask & 0 constant guarantee
112            // that the value does not exceed 20 bits.
113            Ipv6FlowLabel::new_unchecked(u32::from_be_bytes([
114                0,
115                *self.slice.get_unchecked(1) & 0xf,
116                *self.slice.get_unchecked(2),
117                *self.slice.get_unchecked(3),
118            ]))
119        }
120    }
121
122    /// Read the "payload length" field from  the slice. The length should contain the length of all extension headers and payload.
123    #[inline]
124    pub fn payload_length(&self) -> u16 {
125        // SAFETY:
126        // Safe as the slice length is set to
127        // Ipv6Header::LEN (40) during construction
128        // of the struct.
129        unsafe { get_unchecked_be_u16(self.slice.as_ptr().add(4)) }
130    }
131
132    /// Read the "next header" field from the slice.
133    ///
134    /// The next header value specifies what the next header or transport
135    /// layer protocol is (see [IpNumber] or [ip_number] for a definitions of ids).
136    #[inline]
137    pub fn next_header(&self) -> IpNumber {
138        // SAFETY:
139        // Safe as the slice length is set to
140        // Ipv6Header::LEN (40) during construction
141        // of the struct.
142        IpNumber(unsafe { *self.slice.get_unchecked(6) })
143    }
144
145    /// Read the "hop limit" field from the slice. The hop limit specifies the number of hops the packet can take before it is discarded.
146    #[inline]
147    pub fn hop_limit(&self) -> u8 {
148        // SAFETY:
149        // Safe as the slice length is set to
150        // Ipv6Header::LEN (40) during construction
151        // of the struct.
152        unsafe { *self.slice.get_unchecked(7) }
153    }
154
155    /// Returns a slice containing the IPv6 source address.
156    #[inline]
157    pub fn source(&self) -> [u8; 16] {
158        // SAFETY:
159        // Safe as the slice length is set to
160        // Ipv6Header::LEN (40) during construction
161        // of the struct.
162        unsafe { get_unchecked_16_byte_array(self.slice.as_ptr().add(8)) }
163    }
164
165    /// Return the ipv6 source address as an core::net::Ipv6Addr
166    #[inline]
167    pub fn source_addr(&self) -> core::net::Ipv6Addr {
168        core::net::Ipv6Addr::from(self.source())
169    }
170
171    /// Returns a slice containing the IPv6 destination address.
172    #[inline]
173    pub fn destination(&self) -> [u8; 16] {
174        // SAFETY:
175        // Safe as the slice length is set to
176        // Ipv6Header::LEN (40) during construction
177        // of the struct.
178        unsafe { get_unchecked_16_byte_array(self.slice.as_ptr().add(24)) }
179    }
180
181    /// Return the ipv6 destination address as an core::net::Ipv6Addr
182    #[inline]
183    pub fn destination_addr(&self) -> core::net::Ipv6Addr {
184        core::net::Ipv6Addr::from(self.destination())
185    }
186
187    /// Decode all the fields and copy the results to a Ipv6Header struct
188    pub fn to_header(&self) -> Ipv6Header {
189        Ipv6Header {
190            traffic_class: self.traffic_class(),
191            flow_label: self.flow_label(),
192            payload_length: self.payload_length(),
193            next_header: self.next_header(),
194            hop_limit: self.hop_limit(),
195            source: self.source(),
196            destination: self.destination(),
197        }
198    }
199
200    /// Returns the length of the IPv6 header in bytes (same as [`crate::Ipv6Header::LEN`]).
201    pub const fn header_len(&self) -> usize {
202        Ipv6Header::LEN
203    }
204}
205
206#[cfg(test)]
207mod test {
208    use crate::{err::ipv6::HeaderError::*, err::ipv6::HeaderSliceError::*, test_gens::*, *};
209    use alloc::format;
210    use proptest::*;
211
212    #[test]
213    fn debug() {
214        let header: Ipv6Header = Default::default();
215        let bytes = header.to_bytes();
216        let slice = Ipv6HeaderSlice::from_slice(&bytes).unwrap();
217        assert_eq!(
218            format!("{:?}", slice),
219            format!("Ipv6HeaderSlice {{ slice: {:?} }}", &bytes[..])
220        );
221    }
222
223    proptest! {
224        #[test]
225        fn clone_eq(header in ipv6_any()) {
226            let bytes = header.to_bytes();
227            let slice = Ipv6HeaderSlice::from_slice(&bytes).unwrap();
228            assert_eq!(slice.clone(), slice);
229        }
230    }
231
232    proptest! {
233        #[test]
234        fn from_slice(
235            header in ipv6_any(),
236            bad_version in 0..=0b1111u8)
237        {
238            // ok read
239            {
240                let bytes = header.to_bytes();
241                let actual = Ipv6HeaderSlice::from_slice(&bytes).unwrap();
242                assert_eq!(actual.slice(), &bytes[..]);
243            }
244
245            // version error
246            if bad_version != 6 {
247                let mut bytes = header.to_bytes();
248                // inject a bad version number
249                bytes[0] = (0b1111 & bytes[0]) | (bad_version << 4);
250
251                assert_eq!(
252                    Ipv6HeaderSlice::from_slice(&bytes).unwrap_err(),
253                    Content(UnexpectedVersion{ version_number: bad_version })
254                );
255            }
256
257            // length error
258            {
259                let bytes = header.to_bytes();
260                for len in 0..bytes.len() {
261                    assert_eq!(
262                        Ipv6HeaderSlice::from_slice(&bytes[..len])
263                            .unwrap_err(),
264                        Len(err::LenError{
265                            required_len: Ipv6Header::LEN,
266                            len: len,
267                            len_source: LenSource::Slice,
268                            layer: err::Layer::Ipv6Header,
269                            layer_start_offset: 0,
270                        })
271                    );
272                }
273            }
274        }
275    }
276
277    proptest! {
278        #[test]
279        fn from_slice_unchecked(header in ipv6_any()) {
280            let bytes = header.to_bytes();
281            let actual = unsafe {
282                Ipv6HeaderSlice::from_slice_unchecked(&bytes)
283            };
284            assert_eq!(actual.slice(), &bytes[..]);
285        }
286    }
287
288    proptest! {
289        #[test]
290        fn getters(header in ipv6_any()) {
291            let bytes = header.to_bytes();
292            let actual = Ipv6HeaderSlice::from_slice(&bytes).unwrap();
293            assert_eq!(actual.slice(), &bytes[..]);
294            assert_eq!(actual.version(), 6);
295            assert_eq!(actual.traffic_class(), header.traffic_class);
296            assert_eq!(actual.ecn(), header.ecn());
297            assert_eq!(actual.dscp(), header.dscp());
298            assert_eq!(actual.flow_label(), header.flow_label);
299            assert_eq!(actual.payload_length(), header.payload_length);
300            assert_eq!(actual.next_header(), header.next_header);
301            assert_eq!(actual.hop_limit(), header.hop_limit);
302            assert_eq!(actual.source(), header.source);
303            assert_eq!(actual.destination(), header.destination);
304            assert_eq!(actual.source_addr(), core::net::Ipv6Addr::from(header.source));
305            assert_eq!(actual.destination_addr(), core::net::Ipv6Addr::from(header.destination));
306        }
307    }
308
309    proptest! {
310        #[test]
311        fn to_header(header in ipv6_any()) {
312            let bytes = header.to_bytes();
313            let actual = Ipv6HeaderSlice::from_slice(&bytes).unwrap();
314            assert_eq!(actual.to_header(), header);
315        }
316    }
317}