Skip to main content

capsules_extra/net/ipv6/
ipv6.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! This file contains structs, traits, and methods associated with the IP layer
6//! of the networking stack.
7//!
8//! This includes the declaration and methods for the IP6Header, IP6Packet, and
9//! IP6Payload structs. These methods implement the bulk of the functionality
10//! required for manipulating the fields of the IPv6 header. Additionally, the
11//! IP6Packet struct allows for multiple types of transport-level structures to
12//! be encapsulated within.
13//!
14//! An implementation for the structure of an IPv6 packet is provided by this
15//! file, and a rough outline is given below:
16//!
17//! ```txt
18//! ----------------------------------------------
19//! |                 IP6Packet                  |
20//! |--------------------------------------------|
21//! |                 |         IPPayload        |
22//! |    IP6Header    |--------------------------|
23//! |                 |TransportHeader | Payload |
24//! ----------------------------------------------
25//! ```
26//!
27//! The [IP6Packet] struct contains an
28//! [IP6Header] struct and an
29//! [IPPayload] struct, with the `IPPayload` struct also
30//! containing a [TransportHeader] enum and a
31//! `Payload` buffer. Note that transport-level headers are contained inside the
32//! `TransportHeader`.
33//!
34//! For a client interested in using this interface, they first statically
35//! allocate an `IP6Packet` struct, then set the appropriate headers and payload
36//! using the functions defined for the different structs. These methods are
37//! described in greater detail below.
38
39// Discussion of Design Decisions
40// ------------------------------
41// Although still a work-in-progress, the IPv6 layer is quite complicated, and
42// this initial interface represents some of the compromises made in trying
43// to design a memory efficient, modular IP layer. The primary decision made
44// for the IPv6 layer was the design of the `IP6Packet` struct. We noticed
45// that the mutable payload buffer should always be associated with some type
46// of headers; that is, we noticed that the payload for an IP packet should
47// be permanently owned by an instance of an IPv6 packet. This avoids runtime
48// checks, as Rust can guarantee that the payload for an IPv6 packet is always
49// there, as it cannot be moved. In order to facilitate this design while still
50// allowing for (somewhat) arbitrary transport-level headers, we needed to
51// separate out the `TransportHeader` enum from the payload itself. Since
52// we did not want the IP layer to always have to have knowledge of/deal with
53// the transport-level header, we decided to add an intermediate `IPPayload`
54// struct, which encapsulated the `TransportHeader` and associated payload.
55//
56// Known Problems and Remaining Work
57// ---------------------------------
58// This layer is still in the early stages of implementation, and both the
59// interfaces and underlying code will change substantially. There are two main
60// areas of focus for additional work: 1) ensuring that the IP6Packet/IP6Header/
61// IPPayload design makes sense and is properly layered, and 2) figuring out
62// and implementing a receive path that uses this encapsulation.
63//
64// One of the primary problems with the current encapsulation design is that it
65// is impossible to encode recursive headers - any subsequent headers (IPv6 or
66// transport) must be serialized and carried in the raw payload. This may be
67// avoided with references and allocation, but since we do not have a memory
68// allocator we could not allocate all possible headers at compile time.
69// Additionally, we couldn't just allocate headers "as-needed" on the stack, as
70// the network send interface is asynchronous, so anything allocated on the
71// stack would eventually be popped/disappear. Although this is not a major
72// problem in general, it makes handling encapsulated IPv6 packets (as required
73// by 6LoWPAN) difficult.
74
75use crate::net::icmpv6::ICMP6Header;
76use crate::net::ipv6::ip_utils::{IPAddr, compute_icmp_checksum, compute_udp_checksum, ip6_nh};
77use crate::net::stream::SResult;
78use crate::net::stream::{decode_bytes, decode_u8, decode_u16};
79use crate::net::stream::{encode_bytes, encode_u8, encode_u16};
80use crate::net::tcp::TCPHeader;
81use crate::net::udp::UDPHeader;
82
83use kernel::ErrorCode;
84use kernel::utilities::leasable_buffer::SubSliceMut;
85
86pub const UDP_HDR_LEN: usize = 8;
87pub const ICMP_HDR_LEN: usize = 8;
88
89/// This is the struct definition for an IPv6 header. It contains (in order)
90/// the same fields as a normal IPv6 header.
91#[repr(C, packed)]
92#[derive(Copy, Clone)]
93pub struct IP6Header {
94    pub version_class_flow: [u8; 4],
95    pub payload_len: u16,
96    pub next_header: u8,
97    pub hop_limit: u8,
98    pub src_addr: IPAddr,
99    pub dst_addr: IPAddr,
100}
101
102impl Default for IP6Header {
103    fn default() -> IP6Header {
104        let version = 0x60;
105        let hop_limit = 255;
106        IP6Header {
107            version_class_flow: [version, 0, 0, 0],
108            payload_len: 0,
109            next_header: ip6_nh::NO_NEXT,
110            hop_limit,
111            src_addr: IPAddr::new(),
112            dst_addr: IPAddr::new(),
113        }
114    }
115}
116
117impl IP6Header {
118    /// This function returns an IP6Header struct initialized to the default
119    /// values.
120    pub fn new() -> IP6Header {
121        IP6Header::default()
122    }
123
124    /// This function is used to transform a raw buffer into an IP6Header
125    /// struct. This is useful for deserializing a header upon reception.
126    ///
127    /// # Arguments
128    ///
129    /// - `buf` - The serialized version of an IPv6 header
130    ///
131    /// # Return Value
132    ///
133    /// - `SResult<IP6Header>` - The resulting decoded IP6Header struct wrapped
134    ///   in an SResult
135    pub fn decode(buf: &[u8]) -> SResult<IP6Header> {
136        // TODO: Let size of header be a constant
137        stream_len_cond!(buf, 40);
138
139        let mut ip6_header = Self::new();
140        // Note that `dec_consume!` uses the length of the output buffer to
141        // determine how many bytes are to be read.
142        let off = dec_consume!(buf, 0; decode_bytes, &mut ip6_header.version_class_flow);
143        let (off, payload_len_be) = dec_try!(buf, off; decode_u16);
144        ip6_header.payload_len = u16::from_be(payload_len_be);
145        let (off, next_header) = dec_try!(buf, off; decode_u8);
146        ip6_header.next_header = next_header;
147        let (off, hop_limit) = dec_try!(buf, off; decode_u8);
148        ip6_header.hop_limit = hop_limit;
149        let off = dec_consume!(buf, off; decode_bytes, &mut ip6_header.src_addr.0);
150        let off = dec_consume!(buf, off; decode_bytes, &mut ip6_header.dst_addr.0);
151        stream_done!(off, ip6_header);
152    }
153
154    /// This function transforms the `self` instance of an IP6Header into a byte
155    /// array
156    ///
157    /// # Arguments
158    ///
159    /// - `buf` - A mutable array where the serialized version of the IP6Header
160    ///   struct is written to
161    ///
162    /// # Return Value
163    ///
164    /// - `SResult<usize>` - The offset wrapped in an SResult
165    pub fn encode(&self, buf: &mut [u8]) -> SResult<usize> {
166        stream_len_cond!(buf, 40);
167
168        let mut off = enc_consume!(buf, 0; encode_bytes, &self.version_class_flow);
169        off = enc_consume!(buf, off; encode_u16, self.payload_len.to_be());
170        off = enc_consume!(buf, off; encode_u8, self.next_header);
171        off = enc_consume!(buf, off; encode_u8, self.hop_limit);
172        off = enc_consume!(buf, off; encode_bytes, &self.src_addr.0);
173        off = enc_consume!(buf, off; encode_bytes, &self.dst_addr.0);
174        stream_done!(off, off);
175    }
176
177    pub fn get_src_addr(&self) -> IPAddr {
178        self.src_addr
179    }
180
181    pub fn get_dst_addr(&self) -> IPAddr {
182        self.dst_addr
183    }
184
185    // Version should always be 6
186    pub fn get_version(&self) -> u8 {
187        (self.version_class_flow[0] & 0xf0) >> 4
188    }
189
190    pub fn get_traffic_class(&self) -> u8 {
191        (self.version_class_flow[0] & 0x0f) << 4 | (self.version_class_flow[1] & 0xf0) >> 4
192    }
193
194    pub fn set_traffic_class(&mut self, new_tc: u8) {
195        self.version_class_flow[0] &= 0xf0;
196        self.version_class_flow[0] |= (new_tc & 0xf0) >> 4;
197        self.version_class_flow[1] &= 0x0f;
198        self.version_class_flow[1] |= (new_tc & 0x0f) << 4;
199    }
200
201    fn get_dscp_unshifted(&self) -> u8 {
202        self.get_traffic_class() & 0b11111100
203    }
204
205    pub fn get_dscp(&self) -> u8 {
206        self.get_dscp_unshifted() >> 2
207    }
208
209    pub fn set_dscp(&mut self, new_dscp: u8) {
210        let ecn = self.get_ecn();
211        self.set_traffic_class(ecn | ((new_dscp << 2) & 0b11111100));
212    }
213
214    pub fn get_ecn(&self) -> u8 {
215        self.get_traffic_class() & 0b11
216    }
217
218    pub fn set_ecn(&mut self, new_ecn: u8) {
219        let dscp_unshifted = self.get_dscp_unshifted();
220        self.set_traffic_class(dscp_unshifted | (new_ecn & 0b11));
221    }
222
223    // This returns the flow label as the lower 20 bits of a u32
224    pub fn get_flow_label(&self) -> u32 {
225        let mut flow_label: u32 = 0;
226        flow_label |= ((self.version_class_flow[1] & 0x0f) as u32) << 16;
227        flow_label |= (self.version_class_flow[2] as u32) << 8;
228        flow_label |= self.version_class_flow[3] as u32;
229        flow_label
230    }
231
232    pub fn set_flow_label(&mut self, new_fl_val: u32) {
233        self.version_class_flow[1] &= 0xf0;
234        self.version_class_flow[1] |= ((new_fl_val >> 16) & 0x0f) as u8;
235        self.version_class_flow[2] = (new_fl_val >> 8) as u8;
236        self.version_class_flow[3] = new_fl_val as u8;
237    }
238
239    pub fn get_payload_len(&self) -> u16 {
240        u16::from_be(self.payload_len)
241    }
242
243    // TODO: 40 = size of IP6header - find idiomatic way to compute
244    pub fn get_total_len(&self) -> u16 {
245        40 + self.get_payload_len()
246    }
247
248    pub fn set_payload_len(&mut self, new_len: u16) {
249        self.payload_len = new_len.to_be();
250    }
251
252    pub fn get_next_header(&self) -> u8 {
253        self.next_header
254    }
255
256    pub fn set_next_header(&mut self, new_nh: u8) {
257        self.next_header = new_nh;
258    }
259
260    pub fn get_hop_limit(&self) -> u8 {
261        self.hop_limit
262    }
263
264    pub fn set_hop_limit(&mut self, new_hl: u8) {
265        self.hop_limit = new_hl;
266    }
267
268    /// Utility function for verifying whether a transport layer checksum of a
269    /// received packet is correct. Is called on the associated IPv6 Header, and
270    /// passed the buffer containing the remainder of the packet.
271    pub fn check_transport_checksum(&self, buf: &[u8]) -> Result<(), ErrorCode> {
272        match self.next_header {
273            ip6_nh::UDP => {
274                let mut udp_header: [u8; UDP_HDR_LEN] = [0; UDP_HDR_LEN];
275                udp_header.copy_from_slice(&buf[..UDP_HDR_LEN]);
276                let checksum = match UDPHeader::decode(&udp_header).done() {
277                    Some((_offset, hdr)) => u16::from_be(compute_udp_checksum(
278                        self,
279                        &hdr,
280                        buf.len() as u16,
281                        &buf[UDP_HDR_LEN..],
282                    )),
283                    None => 0xffff, //Will be dropped, as ones comp -0 checksum is invalid
284                };
285                if checksum != 0 {
286                    return Err(ErrorCode::FAIL); //Incorrect cksum
287                }
288                Ok(())
289            }
290            ip6_nh::ICMP => {
291                // Untested (10/5/18)
292                let mut icmp_header: [u8; ICMP_HDR_LEN] = [0; ICMP_HDR_LEN];
293                icmp_header.copy_from_slice(&buf[..ICMP_HDR_LEN]);
294                let checksum = match ICMP6Header::decode(&icmp_header).done() {
295                    Some((_offset, mut hdr)) => {
296                        hdr.set_len(buf.len() as u16);
297                        u16::from_be(compute_icmp_checksum(self, &hdr, &buf[ICMP_HDR_LEN..]))
298                    }
299                    None => 0xffff, //Will be dropped, as ones comp -0 checksum is invalid
300                };
301                if checksum != 0 {
302                    return Err(ErrorCode::FAIL); //Incorrect cksum
303                }
304                Ok(())
305            }
306            _ => Err(ErrorCode::NOSUPPORT),
307        }
308    }
309}
310
311/// This defines the currently supported `TransportHeader` types.
312///
313/// The contents of each header is encapsulated by the enum type. Note that this
314/// definition of `TransportHeader`s means that recursive headers are not
315/// supported.  As of now, there is no support for sending raw IP packets
316/// without a transport header.  Currently we accept the overhead of copying
317/// these structs in/out of an OptionalCell in `udp_send.rs`.
318#[derive(Copy, Clone)]
319pub enum TransportHeader {
320    UDP(UDPHeader),
321    TCP(TCPHeader),
322    ICMP(ICMP6Header),
323}
324
325/// The `IPPayload` struct contains a `TransportHeader` and a mutable buffer
326/// (the payload).
327pub struct IPPayload<'a> {
328    pub header: TransportHeader,
329    pub payload: &'a mut [u8],
330}
331
332impl<'a> IPPayload<'a> {
333    /// This function constructs a new `IPPayload` struct
334    ///
335    /// # Arguments
336    ///
337    /// - `header` - A `TransportHeader` for the `IPPayload`
338    /// - `payload` - A reference to a mutable buffer for the raw payload
339    pub fn new(header: TransportHeader, payload: &'a mut [u8]) -> IPPayload<'a> {
340        IPPayload { header, payload }
341    }
342
343    /// This function sets the payload for the `IPPayload`, and sets both the
344    /// TransportHeader and copies the provided payload buffer.
345    ///
346    /// # Arguments
347    ///
348    /// - `transport_header` - The new `TransportHeader` header for the payload
349    /// - `payload` - The payload to be copied into the `IPPayload`
350    ///
351    /// # Return Value
352    ///
353    /// - `(u8, u16)` - Returns a tuple of the `ip6_nh` type of the
354    /// - `transport_header` and the total length of the `IPPayload` (when
355    ///   serialized)
356    pub fn set_payload(
357        &mut self,
358        transport_header: TransportHeader,
359        payload: &SubSliceMut<'static, u8>,
360    ) -> (u8, u16) {
361        for i in 0..payload.len() {
362            self.payload[i] = payload[i];
363        }
364        match transport_header {
365            TransportHeader::UDP(mut udp_header) => {
366                let length = (payload.len() + udp_header.get_hdr_size()) as u16;
367                udp_header.set_len(length);
368                self.header = transport_header;
369                (ip6_nh::UDP, length)
370            }
371            TransportHeader::ICMP(mut icmp_header) => {
372                let length = (payload.len() + icmp_header.get_hdr_size()) as u16;
373                icmp_header.set_len(length);
374                self.header = transport_header;
375                (ip6_nh::ICMP, length)
376            }
377            _ => (ip6_nh::NO_NEXT, payload.len() as u16),
378        }
379    }
380
381    /// This function encodes the `IPPayload` as a byte array
382    ///
383    /// # Arguments
384    ///
385    /// - `buf` - SubSliceMut to write the serialized `IPPayload` to
386    /// - `offset` - Current offset into the buffer
387    ///
388    /// # Return Value
389    ///
390    /// - `SResult<usize>` - The final offset into the buffer `buf` is returned
391    ///   wrapped in an SResult
392    pub fn encode(&self, buf: &mut [u8], offset: usize) -> SResult<usize> {
393        let (offset, _) = match self.header {
394            TransportHeader::UDP(udp_header) => udp_header.encode(buf, offset).done().unwrap(),
395            TransportHeader::ICMP(icmp_header) => icmp_header.encode(buf, offset).done().unwrap(),
396            _ => {
397                unimplemented!();
398            }
399        };
400        let payload_length = self.get_payload_length();
401        let offset = enc_consume!(buf, offset; encode_bytes, &self.payload[..payload_length]);
402        stream_done!(offset, offset)
403    }
404
405    fn get_payload_length(&self) -> usize {
406        match self.header {
407            TransportHeader::UDP(udp_header) => {
408                udp_header.get_len() as usize - udp_header.get_hdr_size()
409            }
410            TransportHeader::ICMP(icmp_header) => {
411                icmp_header.get_len() as usize - icmp_header.get_hdr_size()
412            }
413            _ => {
414                unimplemented!();
415            }
416        }
417    }
418}
419
420/// This struct defines the `IP6Packet` format, and contains an `IP6Header`
421/// and an `IPPayload`.
422pub struct IP6Packet<'a> {
423    pub header: IP6Header,
424    pub payload: IPPayload<'a>,
425}
426
427// Note: We want to have the IP6Header struct implement these methods,
428// as there are cases where we want to allocate/modify the IP6Header without
429// allocating/modifying the entire IP6Packet
430impl<'a> IP6Packet<'a> {
431    // Sets fields to appropriate defaults
432
433    /// This function returns a new `IP6Packet` struct. Note that the
434    /// `IP6Packet.header` field is set to `IP6Header::default()`
435    ///
436    /// # Arguments
437    ///
438    /// - `payload` - The `IPPayload` struct for the `IP6Packet`
439    pub fn new(payload: IPPayload<'a>) -> IP6Packet<'a> {
440        IP6Packet {
441            header: IP6Header::default(),
442            payload,
443        }
444    }
445
446    pub fn reset(&mut self) {
447        self.header = IP6Header::default();
448    }
449
450    pub fn get_total_len(&self) -> u16 {
451        40 + self.header.get_payload_len()
452    }
453
454    pub fn get_payload(&self) -> &[u8] {
455        self.payload.payload
456    }
457
458    pub fn get_total_hdr_size(&self) -> usize {
459        let transport_hdr_size = match self.payload.header {
460            TransportHeader::UDP(udp_hdr) => udp_hdr.get_hdr_size(),
461            TransportHeader::ICMP(icmp_header) => icmp_header.get_hdr_size(),
462            _ => unimplemented!(),
463        };
464        40 + transport_hdr_size
465    }
466
467    pub fn set_transport_checksum(&mut self) {
468        // Looks at internal buffer assuming
469        // it contains a valid IP packet, checks the payload type. If the payload
470        // type requires a cksum calculation, this function calculates the
471        // psuedoheader cksum and calls the appropriate transport packet function
472        // using this pseudoheader cksum to set the transport packet cksum
473
474        match self.payload.header {
475            TransportHeader::UDP(ref mut udp_header) => {
476                let cksum = compute_udp_checksum(
477                    &self.header,
478                    udp_header,
479                    udp_header.get_len(),
480                    self.payload.payload,
481                );
482                udp_header.set_cksum(cksum);
483            }
484            TransportHeader::ICMP(ref mut icmp_header) => {
485                let cksum = compute_icmp_checksum(&self.header, icmp_header, self.payload.payload);
486                icmp_header.set_cksum(cksum);
487            }
488            _ => {
489                unimplemented!();
490            }
491        }
492    }
493
494    /// This function should be the function used to set the payload for a given
495    /// `IP6Packet` object. It first calls the `IPPayload::set_payload` method
496    /// to set the transport header and transport payload, which then returns
497    /// the `ip6_nh` value for the `TransportHeader` and the length of the
498    /// serialized `IPPayload` region. This function then sets the `IP6Header`
499    /// next header field correctly. **Without using this function, the
500    /// `IP6Header.next_header` field may not agree with the actual next header
501    /// (`IP6Header.payload.header`)**
502    ///
503    /// # Arguments
504    ///
505    /// - `transport_header` - The `TransportHeader` to be set as the next
506    ///   header
507    /// - `payload` - The transport payload to be copied into the `IPPayload`
508    ///   transport payload
509    pub fn set_payload(
510        &mut self,
511        transport_header: TransportHeader,
512        payload: &SubSliceMut<'static, u8>,
513    ) {
514        let (next_header, payload_len) = self.payload.set_payload(transport_header, payload);
515        self.header.set_next_header(next_header);
516        self.header.set_payload_len(payload_len);
517    }
518
519    // TODO: Do we need a decode equivalent? I don't think so, but we might
520
521    pub fn encode(&self, buf: &mut [u8]) -> SResult<usize> {
522        let ip6_header = self.header;
523
524        // TODO: Handle unwrap safely
525        let (off, _) = ip6_header.encode(buf).done().unwrap();
526        self.payload.encode(buf, off)
527    }
528}