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
use crate::{err::*, *};

/// Slice containing an Ethernet 2 headers & payload.
#[derive(Clone, Eq, PartialEq)]
pub struct Ethernet2Slice<'a> {
    fcs_len: usize,
    slice: &'a [u8],
}

impl<'a> Ethernet2Slice<'a> {
    /// Try creating a [`Ethernet2Slice`] from a slice containing the
    /// Ethernet 2 header & payload WITHOUT an FCS (frame check sequence)
    /// at the end.
    pub fn from_slice_without_fcs(slice: &'a [u8]) -> Result<Ethernet2Slice<'a>, LenError> {
        // check length
        if slice.len() < Ethernet2Header::LEN {
            return Err(LenError {
                required_len: Ethernet2Header::LEN,
                len: slice.len(),
                len_source: LenSource::Slice,
                layer: Layer::Ethernet2Header,
                layer_start_offset: 0,
            });
        }

        Ok(Ethernet2Slice { fcs_len: 0, slice })
    }

    /// Try creating a [`Ethernet2Slice`] from a slice containing the
    /// Ethernet 2 header & payload with a CRC 32 bit FCS (frame
    /// check sequence) at the end.
    ///
    /// In case you are not sure if your ethernet2 frame has a FCS or not
    /// use [`Ethernet2Slice::from_slice_without_fcs`] instead and rely on the
    /// lower layers (e.g. IP) to determine the correct payload length.
    pub fn from_slice_with_crc32_fcs(slice: &'a [u8]) -> Result<Ethernet2Slice<'a>, LenError> {
        // check length
        let fcs_len = 4;
        if slice.len() < Ethernet2Header::LEN + fcs_len {
            return Err(LenError {
                required_len: Ethernet2Header::LEN + 4,
                len: slice.len(),
                len_source: LenSource::Slice,
                layer: Layer::Ethernet2Header,
                layer_start_offset: 0,
            });
        }

        Ok(Ethernet2Slice { fcs_len, slice })
    }

    /// Returns the slice containing the ethernet 2 header
    /// payload and FCS if present.
    #[inline]
    pub fn slice(&self) -> &'a [u8] {
        self.slice
    }

    /// Read the destination MAC address
    #[inline]
    pub fn destination(&self) -> [u8; 6] {
        // SAFETY:
        // Safe as the contructor checks that the slice has
        // at least the length of Ethernet2Header::LEN (14).
        unsafe { get_unchecked_6_byte_array(self.slice.as_ptr()) }
    }

    /// Read the source MAC address
    #[inline]
    pub fn source(&self) -> [u8; 6] {
        // SAFETY:
        // Safe as the contructor checks that the slice has
        // at least the length of Ethernet2Header::LEN (14).
        unsafe { get_unchecked_6_byte_array(self.slice.as_ptr().add(6)) }
    }

    /// Read the ether_type field of the header indicating the protocol
    /// after the header.
    #[inline]
    pub fn ether_type(&self) -> EtherType {
        // SAFETY:
        // Safe as the contructor checks that the slice has
        // at least the length of Ethernet2Header::LEN (14).
        EtherType(unsafe { get_unchecked_be_u16(self.slice.as_ptr().add(12)) })
    }

    /// Returns the frame check sequence if present.
    #[inline]
    pub fn fcs(&self) -> Option<[u8; 4]> {
        if self.fcs_len == 4 {
            // SAFETY: Safe as the slice length was verified
            // to be at least Ethernet2Header::LEN + fcs_len by
            // "from_slice_without_fcs" & "from_slice_with_crc32_fcs".
            Some(unsafe {
                [
                    *self.slice.as_ptr().add(self.slice.len() - 4),
                    *self.slice.as_ptr().add(self.slice.len() - 3),
                    *self.slice.as_ptr().add(self.slice.len() - 2),
                    *self.slice.as_ptr().add(self.slice.len() - 1),
                ]
            })
        } else {
            None
        }
    }

    /// Decode all the fields and copy the results to a [`Ethernet2Header`] struct
    pub fn to_header(&self) -> Ethernet2Header {
        Ethernet2Header {
            source: self.source(),
            destination: self.destination(),
            ether_type: self.ether_type(),
        }
    }

    /// Slice containing the Ethernet 2 header.
    pub fn header_slice(&self) -> &[u8] {
        unsafe {
            // SAFETY:
            // Safe as the contructor checks that the slice has
            // at least the length of Ethernet2Header::LEN (14).
            core::slice::from_raw_parts(self.slice.as_ptr(), Ethernet2Header::LEN)
        }
    }

    /// Returns the slice containing the Ethernet II payload & ether type
    /// identifying it's content type.
    #[inline]
    pub fn payload(&self) -> EtherPayloadSlice<'a> {
        EtherPayloadSlice {
            ether_type: self.ether_type(),
            payload: self.payload_slice(),
        }
    }

    /// Returns the slice containing the Ethernet II payload.
    #[inline]
    pub fn payload_slice(&self) -> &'a [u8] {
        unsafe {
            // SAFETY: Safe as the slice length was verified
            // to be at least Ethernet2Header::LEN + fcs_len by
            // "from_slice_without_fcs" & "from_slice_with_crc32_fcs".
            core::slice::from_raw_parts(
                self.slice.as_ptr().add(Ethernet2Header::LEN),
                self.slice.len() - Ethernet2Header::LEN - self.fcs_len,
            )
        }
    }

    /// Length of the Ethernet 2 header in bytes (equal to
    /// [`crate::Ethernet2Header::LEN`]).
    #[inline]
    pub const fn header_len(&self) -> usize {
        Ethernet2Header::LEN
    }
}

impl<'a> core::fmt::Debug for Ethernet2Slice<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Ethernet2Slice")
            .field("header", &self.to_header())
            .field("payload", &self.payload())
            .field("fcs", &self.fcs())
            .finish()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_gens::*;
    use alloc::{format, vec::Vec};
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn debug_clone_eq(
            eth in ethernet_2_any(),
            has_fcs in any::<bool>()
        ) {
            let payload: [u8;8] = [1,2,3,4,5,6,7,8];
            let mut data = Vec::with_capacity(
                eth.header_len() +
                payload.len()
            );
            data.extend_from_slice(&eth.to_bytes());
            data.extend_from_slice(&payload);

            // decode packet
            let slice = if has_fcs {
                Ethernet2Slice::from_slice_with_crc32_fcs(&data).unwrap()
            } else {
                Ethernet2Slice::from_slice_without_fcs(&data).unwrap()
            };

            // check debug output
            prop_assert_eq!(
                format!("{:?}", slice),
                format!(
                    "Ethernet2Slice {{ header: {:?}, payload: {:?}, fcs: {:?} }}",
                    slice.to_header(),
                    slice.payload(),
                    slice.fcs()
                )
            );
            prop_assert_eq!(slice.clone(), slice);
        }
    }

    proptest! {
        #[test]
        fn getters(eth in ethernet_2_any()) {
            let payload: [u8;8] = [1,2,3,4,5,6,7,8];
            let mut data = Vec::with_capacity(
                eth.header_len() +
                payload.len()
            );
            data.extend_from_slice(&eth.to_bytes());
            data.extend_from_slice(&payload);

            // without fcs
            {
                let slice = Ethernet2Slice::from_slice_without_fcs(&data).unwrap();
                assert_eq!(eth.destination, slice.destination());
                assert_eq!(eth.source, slice.source());
                assert_eq!(eth.ether_type, slice.ether_type());
                assert_eq!(&payload, slice.payload_slice());
                assert_eq!(
                    EtherPayloadSlice{
                        payload: &payload,
                        ether_type: eth.ether_type,
                    },
                    slice.payload()
                );
                assert_eq!(None, slice.fcs());
                assert_eq!(eth, slice.to_header());
                assert_eq!(&data, slice.slice());
                assert_eq!(&data[..Ethernet2Header::LEN], slice.header_slice());
            }
            // with fcs
            {
                let slice = Ethernet2Slice::from_slice_with_crc32_fcs(&data).unwrap();
                assert_eq!(eth.destination, slice.destination());
                assert_eq!(eth.source, slice.source());
                assert_eq!(eth.ether_type, slice.ether_type());
                assert_eq!(&payload[..payload.len() - 4], slice.payload_slice());
                assert_eq!(
                    EtherPayloadSlice{
                        payload: &payload[..payload.len() - 4],
                        ether_type: eth.ether_type,
                    },
                    slice.payload()
                );
                assert_eq!(Some([5, 6, 7, 8]), slice.fcs());
                assert_eq!(eth, slice.to_header());
                assert_eq!(&data, slice.slice());
                assert_eq!(&data[..Ethernet2Header::LEN], slice.header_slice());
            }
        }
    }

    proptest! {
        #[test]
        fn from_slice_without_fcs(eth in ethernet_2_any()) {

            let payload: [u8;10] = [1,2,3,4,5,6,7,8,9,10];
            let data = {
                let mut data = Vec::with_capacity(
                    eth.header_len() +
                    payload.len()
                );
                data.extend_from_slice(&eth.to_bytes());
                data.extend_from_slice(&payload);
                data
            };

            // normal decode
            {
                let slice = Ethernet2Slice::from_slice_without_fcs(&data).unwrap();
                assert_eq!(slice.to_header(), eth);
                assert_eq!(slice.payload_slice(), &payload);
                assert_eq!(slice.fcs(), None);
            }

            // decode without payload
            {
                let slice = Ethernet2Slice::from_slice_without_fcs(&data[..Ethernet2Header::LEN]).unwrap();
                assert_eq!(slice.to_header(), eth);
                assert_eq!(slice.payload_slice(), &[]);
                assert_eq!(slice.fcs(), None);
            }

            // length error
            for len in 0..Ethernet2Header::LEN {
                assert_eq!(
                    Ethernet2Slice::from_slice_without_fcs(&data[..len]).unwrap_err(),
                    LenError{
                        required_len: Ethernet2Header::LEN,
                        len,
                        len_source: LenSource::Slice,
                        layer: Layer::Ethernet2Header,
                        layer_start_offset: 0
                    }
                );
            }
        }
    }

    proptest! {
        #[test]
        fn from_slice_with_crc32_fcs(
            eth in ethernet_2_any()
        ) {
            let payload: [u8;10] = [1,2,3,4,5,6,7,8,9,10];
            let fcs: [u8;4] = [11,12,13,14];
            let data = {
                let mut data = Vec::with_capacity(
                    eth.header_len() +
                    payload.len()
                );
                data.extend_from_slice(&eth.to_bytes());
                data.extend_from_slice(&payload);
                data.extend_from_slice(&fcs);
                data
            };

            // normal decode
            {
                let slice = Ethernet2Slice::from_slice_with_crc32_fcs(&data).unwrap();
                assert_eq!(slice.to_header(), eth);
                assert_eq!(slice.payload_slice(), &payload);
                assert_eq!(slice.fcs(), Some(fcs));
            }

            // decode without payload
            {
                let slice = Ethernet2Slice::from_slice_with_crc32_fcs(&data[..Ethernet2Header::LEN + 4]).unwrap();
                assert_eq!(slice.to_header(), eth);
                assert_eq!(slice.payload_slice(), &[]);
                assert_eq!(slice.fcs(), Some([1,2,3,4]));
            }

            // length error
            for len in 0..Ethernet2Header::LEN + 4 {
                assert_eq!(
                    Ethernet2Slice::from_slice_with_crc32_fcs(&data[..len]).unwrap_err(),
                    LenError{
                        required_len: Ethernet2Header::LEN + 4,
                        len,
                        len_source: LenSource::Slice,
                        layer: Layer::Ethernet2Header,
                        layer_start_offset: 0
                    }
                );
            }
        }
    }
}