Skip to main content

capsules_extra/net/sixlowpan/
sixlowpan_compression.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
5use crate::net::ieee802154::MacAddress;
6use crate::net::ipv6::ip_utils::{IPAddr, compute_udp_checksum, ip6_nh};
7use crate::net::ipv6::{IP6Header, IP6Packet, TransportHeader};
8use crate::net::udp::UDPHeader;
9use crate::net::util;
10use crate::net::util::{network_slice_to_u16, u16_to_network_slice};
11/// Implements the 6LoWPAN specification for sending IPv6 datagrams over
12/// 802.15.4 packets efficiently, as detailed in RFC 6282.
13use core::mem;
14
15/// Contains bit masks and constants related to the two-byte header of the
16/// LoWPAN_IPHC encoding format.
17mod iphc {
18    pub const DISPATCH: [u8; 2] = [0x60, 0x00];
19
20    // First byte masks
21
22    pub const TF_TRAFFIC_CLASS: u8 = 0x08;
23    pub const TF_FLOW_LABEL: u8 = 0x10;
24
25    pub const NH: u8 = 0x04;
26
27    pub const HLIM_MASK: u8 = 0x03;
28    pub const HLIM_INLINE: u8 = 0x00;
29    pub const HLIM_1: u8 = 0x01;
30    pub const HLIM_64: u8 = 0x02;
31    pub const HLIM_255: u8 = 0x03;
32
33    // Second byte masks
34
35    pub const CID: u8 = 0x80;
36
37    pub const SAC: u8 = 0x40;
38
39    pub const SAM_MASK: u8 = 0x30;
40    pub const SAM_INLINE: u8 = 0x00;
41    pub const SAM_MODE1: u8 = 0x10;
42    pub const SAM_MODE2: u8 = 0x20;
43    pub const SAM_MODE3: u8 = 0x30;
44
45    pub const MULTICAST: u8 = 0x08;
46
47    pub const DAC: u8 = 0x04;
48    pub const DAM_MASK: u8 = 0x03;
49    pub const DAM_INLINE: u8 = 0x00;
50    pub const DAM_MODE1: u8 = 0x01;
51    pub const DAM_MODE2: u8 = 0x02;
52    pub const DAM_MODE3: u8 = 0x03;
53
54    // Address compression
55    pub const MAC_BASE: [u8; 8] = [0, 0, 0, 0xff, 0xfe, 0, 0, 0];
56    pub const MAC_UL: u8 = 0x02;
57}
58
59/// Contains bit masks and constants related to LoWPAN_NHC encoding,
60/// including some specific to UDP header encoding
61mod nhc {
62    pub const DISPATCH_NHC: u8 = 0xe0;
63    pub const DISPATCH_UDP: u8 = 0xf0;
64    pub const DISPATCH_MASK: u8 = 0xf0;
65
66    pub const EID_MASK: u8 = 0x0e;
67    pub const HOP_OPTS: u8 = 0 << 1;
68    pub const ROUTING: u8 = 1 << 1;
69    pub const FRAGMENT: u8 = 2 << 1;
70    pub const DST_OPTS: u8 = 3 << 1;
71    pub const MOBILITY: u8 = 4 << 1;
72    pub const IP6: u8 = 7 << 1;
73
74    pub const NH: u8 = 0x01;
75
76    // UDP header compression
77
78    pub const UDP_4BIT_PORT: u16 = 0xf0b0;
79    pub const UDP_4BIT_PORT_MASK: u16 = 0xfff0;
80    pub const UDP_8BIT_PORT: u16 = 0xf000;
81    pub const UDP_8BIT_PORT_MASK: u16 = 0xff00;
82
83    pub const UDP_CHECKSUM_FLAG: u8 = 0b100;
84    pub const UDP_SRC_PORT_FLAG: u8 = 0b010;
85    pub const UDP_DST_PORT_FLAG: u8 = 0b001;
86    pub const UDP_PORTS_SIZE: u16 = 4;
87}
88
89#[derive(Copy, Clone, Debug)]
90pub struct Context {
91    pub prefix: [u8; 16],
92    pub prefix_len: u8,
93    pub id: u8,
94    pub compress: bool,
95}
96
97/// LoWPan ContextStore
98///
99/// LoWPAN encoding requires being able to look up the existence of contexts,
100/// which are essentially IPv6 address prefixes. Any implementation must ensure
101/// that context 0 is always available and contains the mesh-local prefix.
102pub trait ContextStore {
103    fn get_context_from_addr(&self, ip_addr: IPAddr) -> Option<Context>;
104    fn get_context_from_id(&self, ctx_id: u8) -> Option<Context>;
105    fn get_context_0(&self) -> Context {
106        match self.get_context_from_id(0) {
107            Some(ctx) => ctx,
108            None => panic!("Context 0 not found"),
109        }
110    }
111    fn get_context_from_prefix(&self, prefix: &[u8], prefix_len: u8) -> Option<Context>;
112}
113
114/// Computes the LoWPAN Interface Identifier from either the 16-bit short MAC or
115/// the IEEE EUI-64 that is derived from the 48-bit MAC.
116pub fn compute_iid(mac_addr: &MacAddress) -> [u8; 8] {
117    match *mac_addr {
118        MacAddress::Short(short_addr) => {
119            // IID is 0000:00ff:fe00:XXXX, where XXXX is 16-bit MAC
120            let mut iid: [u8; 8] = iphc::MAC_BASE;
121            iid[6] = (short_addr >> 1) as u8;
122            iid[7] = (short_addr & 0xff) as u8;
123            iid
124        }
125        MacAddress::Long(long_addr) => {
126            // IID is IEEE EUI-64 with universal/local bit inverted
127            let mut iid: [u8; 8] = long_addr;
128            iid[0] ^= iphc::MAC_UL;
129            iid
130        }
131    }
132}
133
134impl ContextStore for Context {
135    fn get_context_from_addr(&self, ip_addr: IPAddr) -> Option<Context> {
136        if util::matches_prefix(&ip_addr.0, &self.prefix, self.prefix_len) {
137            Some(*self)
138        } else {
139            None
140        }
141    }
142
143    fn get_context_from_id(&self, ctx_id: u8) -> Option<Context> {
144        if ctx_id == 0 { Some(*self) } else { None }
145    }
146
147    fn get_context_from_prefix(&self, prefix: &[u8], prefix_len: u8) -> Option<Context> {
148        if prefix_len == self.prefix_len && util::matches_prefix(prefix, &self.prefix, prefix_len) {
149            Some(*self)
150        } else {
151            None
152        }
153    }
154}
155
156pub fn is_lowpan(packet: &[u8]) -> bool {
157    (packet[0] & iphc::DISPATCH[0]) == iphc::DISPATCH[0]
158}
159
160/// Maps a LoWPAN_NHC header the corresponding IPv6 next header type,
161/// or an error if the NHC header is invalid
162fn nhc_to_ip6_nh(nhc: u8) -> Result<u8, ()> {
163    match nhc & nhc::DISPATCH_MASK {
164        nhc::DISPATCH_NHC => match nhc & nhc::EID_MASK {
165            nhc::HOP_OPTS => Ok(ip6_nh::HOP_OPTS),
166            nhc::ROUTING => Ok(ip6_nh::ROUTING),
167            nhc::FRAGMENT => Ok(ip6_nh::FRAGMENT),
168            nhc::DST_OPTS => Ok(ip6_nh::DST_OPTS),
169            nhc::MOBILITY => Ok(ip6_nh::MOBILITY),
170            nhc::IP6 => Ok(ip6_nh::IP6),
171            _ => Err(()),
172        },
173        nhc::DISPATCH_UDP => Ok(ip6_nh::UDP),
174        _ => Err(()),
175    }
176}
177
178/// Compresses an IPv6 header into a 6loWPAN header
179///
180/// Constructs a 6LoWPAN header in `buf` from the given IPv6 datagram and
181/// 16-bit MAC addresses. If the compression was successful, returns
182/// `Ok((consumed, written))`, where `consumed` is the number of header
183/// bytes consumed from the IPv6 datagram `written` is the number of
184/// compressed header bytes written into `buf`. Payload bytes and
185/// non-compressed next headers are not written, so the remaining `buf.len()
186/// - consumed` bytes must still be copied over to `buf`.
187pub fn compress<'a>(
188    ctx_store: &dyn ContextStore,
189    ip6_packet: &'a IP6Packet<'a>,
190    src_mac_addr: MacAddress,
191    dst_mac_addr: MacAddress,
192    buf: &mut [u8],
193) -> Result<(usize, usize), ()> {
194    // Note that consumed should be constant, and equal sizeof(IP6Header)
195    //let (mut consumed, ip6_header) = IP6Header::decode(ip6_datagram).done().ok_or(())?;
196    let mut consumed = 40; // TODO
197    let ip6_header = ip6_packet.header;
198
199    //let mut next_headers: &[u8] = &ip6_datagram[consumed..];
200
201    // The first two bytes are the LOWPAN_IPHC header
202    let mut written: usize = 2;
203
204    // Initialize the LOWPAN_IPHC header
205    buf[0..2].copy_from_slice(&iphc::DISPATCH);
206
207    let mut src_ctx: Option<Context> = ctx_store.get_context_from_addr(ip6_header.src_addr);
208    let mut dst_ctx: Option<Context> = if ip6_header.dst_addr.is_multicast() {
209        let prefix_len: u8 = ip6_header.dst_addr.0[3];
210        let prefix: &[u8] = &ip6_header.dst_addr.0[4..12];
211        // This also implicitly verifies that prefix_len <= 64
212        if util::verify_prefix_len(prefix, prefix_len) {
213            ctx_store.get_context_from_prefix(prefix, prefix_len)
214        } else {
215            None
216        }
217    } else {
218        ctx_store.get_context_from_addr(ip6_header.dst_addr)
219    };
220
221    // Do not contexts that are not marked to be available for compression
222    src_ctx = src_ctx.filter(|&ctx| ctx.compress);
223    dst_ctx = dst_ctx.filter(|&ctx| ctx.compress);
224
225    // Context Identifier Extension
226    compress_cie(src_ctx.as_ref(), dst_ctx.as_ref(), buf, &mut written);
227
228    // Traffic Class & Flow Label
229    compress_tf(&ip6_header, buf, &mut written);
230
231    // Next Header
232
233    //let (mut is_nhc, mut nh_len): (bool, u8) = is_ip6_nh_compressible(ip6_packet)?;
234    let is_nhc = ip6_header.next_header == ip6_nh::UDP;
235    compress_nh(&ip6_header, is_nhc, buf, &mut written);
236
237    // Hop Limit
238    compress_hl(&ip6_header, buf, &mut written);
239
240    // Source Address
241    compress_src(
242        &ip6_header.src_addr,
243        &src_mac_addr,
244        src_ctx.as_ref(),
245        buf,
246        &mut written,
247    );
248
249    // Destination Address
250    if ip6_header.dst_addr.is_multicast() {
251        compress_multicast(&ip6_header.dst_addr, dst_ctx.as_ref(), buf, &mut written);
252    } else {
253        compress_dst(
254            &ip6_header.dst_addr,
255            &dst_mac_addr,
256            dst_ctx.as_ref(),
257            buf,
258            &mut written,
259        );
260    }
261
262    // Next Headers
263    // At each iteration, next_headers begins at the first byte of the
264    // current uncompressed next header.
265    // Since we aren't recursing, we only handle UDP
266    if is_nhc {
267        match ip6_packet.payload.header {
268            TransportHeader::UDP(udp_header) => {
269                let mut nhc_header = nhc::DISPATCH_UDP;
270
271                // Leave a space for the UDP LoWPAN_NHC byte
272                let udp_nh_offset = written;
273                written += 1;
274
275                // Compress ports and checksum
276                nhc_header |= compress_udp_ports(&udp_header, buf, &mut written);
277                nhc_header |= compress_udp_checksum(&udp_header, buf, &mut written);
278
279                // Write the UDP LoWPAN_NHC byte
280                buf[udp_nh_offset] = nhc_header;
281                consumed += 8;
282            }
283            // Return an error, as there is a conflict between IPv6 next
284            // header and actual IPv6 payload
285            _ => return Err(()),
286        }
287    }
288    Ok((consumed, written))
289}
290
291fn compress_cie(
292    src_ctx: Option<&Context>,
293    dst_ctx: Option<&Context>,
294    buf: &mut [u8],
295    written: &mut usize,
296) {
297    let mut cie: u8 = 0;
298
299    src_ctx.as_ref().map(|ctx| {
300        if ctx.id != 0 {
301            cie |= ctx.id << 4;
302        }
303    });
304    dst_ctx.as_ref().map(|ctx| {
305        if ctx.id != 0 {
306            cie |= ctx.id;
307        }
308    });
309
310    if cie != 0 {
311        buf[1] |= iphc::CID;
312        buf[*written] = cie;
313        *written += 1;
314    }
315}
316
317fn compress_tf(ip6_header: &IP6Header, buf: &mut [u8], written: &mut usize) {
318    let ecn = ip6_header.get_ecn();
319    let dscp = ip6_header.get_dscp();
320    let flow = ip6_header.get_flow_label();
321
322    let mut tf_encoding = 0;
323    let old_offset = *written;
324
325    // If ECN != 0 we are forced to at least have one byte,
326    // otherwise we can elide dscp
327    if dscp == 0 && (ecn == 0 || flow != 0) {
328        tf_encoding |= iphc::TF_TRAFFIC_CLASS;
329    } else {
330        buf[*written] = dscp;
331        *written += 1;
332    }
333
334    // We can elide flow if it is 0
335    if flow == 0 {
336        tf_encoding |= iphc::TF_FLOW_LABEL;
337    } else {
338        buf[*written] = ((flow >> 16) & 0x0f) as u8;
339        buf[*written + 1] = (flow >> 8) as u8;
340        buf[*written + 2] = flow as u8;
341        *written += 3;
342    }
343
344    if *written != old_offset {
345        buf[old_offset] |= ecn << 6;
346    }
347    buf[0] |= tf_encoding;
348}
349
350fn compress_nh(ip6_header: &IP6Header, is_nhc: bool, buf: &mut [u8], written: &mut usize) {
351    if is_nhc {
352        buf[0] |= iphc::NH;
353    } else {
354        buf[*written] = ip6_header.next_header;
355        *written += 1;
356    }
357}
358
359fn compress_hl(ip6_header: &IP6Header, buf: &mut [u8], written: &mut usize) {
360    let hop_limit_flag = match ip6_header.hop_limit {
361        1 => iphc::HLIM_1,
362        64 => iphc::HLIM_64,
363        255 => iphc::HLIM_255,
364        _ => {
365            buf[*written] = ip6_header.hop_limit;
366            *written += 1;
367            iphc::HLIM_INLINE
368        }
369    };
370    buf[0] |= hop_limit_flag;
371}
372
373// TODO: We should check to see whether context or link local compression
374// schemes gives the better compression; currently, we will always match
375// on link local even if we could get better compression through context.
376fn compress_src(
377    src_ip_addr: &IPAddr,
378    src_mac_addr: &MacAddress,
379    src_ctx: Option<&Context>,
380    buf: &mut [u8],
381    written: &mut usize,
382) {
383    if src_ip_addr.is_unspecified() {
384        // SAC = 1, SAM = 00
385        buf[1] |= iphc::SAC;
386    } else if src_ip_addr.is_unicast_link_local() {
387        // SAC = 0, SAM = 01, 10, 11
388        compress_iid(src_ip_addr, src_mac_addr, true, buf, written);
389    } else if src_ctx.is_some() {
390        // SAC = 1, SAM = 01, 10, 11
391        buf[1] |= iphc::SAC;
392        compress_iid(src_ip_addr, src_mac_addr, true, buf, written);
393    } else {
394        // SAC = 0, SAM = 00
395        buf[*written..*written + 16].copy_from_slice(&src_ip_addr.0);
396        *written += 16;
397    }
398}
399
400// TODO: For the SAC = 0, SAM = 11 case in IPv6-encapsulated headers,
401// it might be that we have to compute the IID from the encapsulating
402// IPv6 header address instead of the EUI-64 from the 802.15.4 layer
403fn compress_iid(
404    ip_addr: &IPAddr,
405    mac_addr: &MacAddress,
406    is_src: bool,
407    buf: &mut [u8],
408    written: &mut usize,
409) {
410    let iid: [u8; 8] = compute_iid(mac_addr);
411    if ip_addr.0[8..16] == iid {
412        // SAM/DAM = 11, 0 bits
413        buf[1] |= if is_src {
414            iphc::SAM_MODE3
415        } else {
416            iphc::DAM_MODE3
417        };
418    } else if ip_addr.0[8..14] == iphc::MAC_BASE[0..6] {
419        // SAM/DAM = 10, 16 bits
420        buf[1] |= if is_src {
421            iphc::SAM_MODE2
422        } else {
423            iphc::DAM_MODE2
424        };
425        buf[*written..*written + 2].copy_from_slice(&ip_addr.0[14..16]);
426        *written += 2;
427    } else {
428        // SAM/DAM = 01, 64 bits
429        buf[1] |= if is_src {
430            iphc::SAM_MODE1
431        } else {
432            iphc::DAM_MODE1
433        };
434        buf[*written..*written + 8].copy_from_slice(&ip_addr.0[8..16]);
435        *written += 8;
436    }
437}
438
439// Compresses non-multicast destination address
440// TODO: We should check to see whether context or link local compression
441// schemes gives the better compression; currently, we will always match
442// on link local even if we could get better compression through context.
443fn compress_dst(
444    dst_ip_addr: &IPAddr,
445    dst_mac_addr: &MacAddress,
446    dst_ctx: Option<&Context>,
447    buf: &mut [u8],
448    written: &mut usize,
449) {
450    // Assumes dst_ip_addr is not a multicast address (prefix ffXX)
451    if dst_ip_addr.is_unicast_link_local() {
452        // Link local compression
453        // M = 0, DAC = 0, DAM = 01, 10, 11
454        compress_iid(dst_ip_addr, dst_mac_addr, false, buf, written);
455    } else if dst_ctx.is_some() {
456        // Context compression
457        // DAC = 1, DAM = 01, 10, 11
458        buf[1] |= iphc::DAC;
459        compress_iid(dst_ip_addr, dst_mac_addr, false, buf, written);
460    } else {
461        // Full address inline
462        // DAC = 0, DAM = 00
463        buf[*written..*written + 16].copy_from_slice(&dst_ip_addr.0);
464        *written += 16;
465    }
466}
467
468// Compresses multicast destination addresses
469fn compress_multicast(
470    dst_ip_addr: &IPAddr,
471    dst_ctx: Option<&Context>,
472    buf: &mut [u8],
473    written: &mut usize,
474) {
475    // Assumes dst_ip_addr is indeed a multicast address (prefix ffXX)
476    buf[1] |= iphc::MULTICAST;
477    if dst_ctx.is_some() {
478        // M = 1, DAC = 1, DAM = 00
479        buf[1] |= iphc::DAC;
480        buf[*written..*written + 2].copy_from_slice(&dst_ip_addr.0[1..3]);
481        buf[*written + 2..*written + 6].copy_from_slice(&dst_ip_addr.0[12..16]);
482        *written += 6;
483    } else {
484        // M = 1, DAC = 0
485        if dst_ip_addr.0[1] == 0x02 && dst_ip_addr.0[2..15].iter().all(|&b| b == 0) {
486            // DAM = 11
487            buf[1] |= iphc::DAM_MODE3;
488            buf[*written] = dst_ip_addr.0[15];
489            *written += 1;
490        } else {
491            if !dst_ip_addr.0[2..11].iter().all(|&b| b == 0) {
492                // DAM = 00
493                buf[1] |= iphc::DAM_INLINE;
494                buf[*written..*written + 16].copy_from_slice(&dst_ip_addr.0);
495                *written += 16;
496            } else if !dst_ip_addr.0[11..13].iter().all(|&b| b == 0) {
497                // DAM = 01, ffXX::00XX:XXXX:XXXX
498                buf[1] |= iphc::DAM_MODE1;
499                buf[*written] = dst_ip_addr.0[1];
500                buf[*written + 1..*written + 6].copy_from_slice(&dst_ip_addr.0[11..16]);
501                *written += 6;
502            } else {
503                // DAM = 10, ffXX::00XX:XXXX
504                buf[1] |= iphc::DAM_MODE2;
505                buf[*written] = dst_ip_addr.0[1];
506                buf[*written + 1..*written + 4].copy_from_slice(&dst_ip_addr.0[13..16]);
507                *written += 4;
508            }
509        }
510    }
511}
512
513fn compress_udp_ports(udp_header: &UDPHeader, buf: &mut [u8], written: &mut usize) -> u8 {
514    // Need to deal with fields in network byte order when writing directly to buf
515    let src_port = udp_header.get_src_port().to_be();
516    let dst_port = udp_header.get_dst_port().to_be();
517
518    let mut udp_port_nhc = 0;
519    if (src_port & nhc::UDP_4BIT_PORT_MASK) == nhc::UDP_4BIT_PORT
520        && (dst_port & nhc::UDP_4BIT_PORT_MASK) == nhc::UDP_4BIT_PORT
521    {
522        // Both can be compressed to 4 bits
523        udp_port_nhc |= nhc::UDP_SRC_PORT_FLAG | nhc::UDP_DST_PORT_FLAG;
524        // This should compress the ports to a single 8-bit value,
525        // with the source port before the destination port
526        buf[*written] = (((src_port & !nhc::UDP_4BIT_PORT_MASK) << 4)
527            | (dst_port & !nhc::UDP_4BIT_PORT_MASK)) as u8;
528        *written += 1;
529    } else if (src_port & nhc::UDP_8BIT_PORT_MASK) == nhc::UDP_8BIT_PORT {
530        // Source port compressed to 8 bits, destination port uncompressed
531        udp_port_nhc |= nhc::UDP_SRC_PORT_FLAG;
532        buf[*written] = (src_port & !nhc::UDP_8BIT_PORT_MASK) as u8;
533        u16_to_network_slice(dst_port.to_be(), &mut buf[*written + 1..*written + 3]);
534        *written += 3;
535    } else if (dst_port & nhc::UDP_8BIT_PORT_MASK) == nhc::UDP_8BIT_PORT {
536        udp_port_nhc |= nhc::UDP_DST_PORT_FLAG;
537        u16_to_network_slice(src_port.to_be(), &mut buf[*written..*written + 2]);
538        buf[*written + 3] = (dst_port & !nhc::UDP_8BIT_PORT_MASK) as u8;
539        *written += 3;
540    } else {
541        buf[*written] = src_port as u8;
542        buf[*written + 1] = (src_port >> 8) as u8;
543        buf[*written + 2] = dst_port as u8;
544        buf[*written + 3] = (dst_port >> 8) as u8;
545        //buf[*written..*written + 4].copy_from_slice(&udp_header[0..4]);
546        *written += 4;
547    }
548    udp_port_nhc
549}
550
551// NOTE: We currently only support (or intend to support) carrying the UDP
552// checksum inline.
553fn compress_udp_checksum(udp_header: &UDPHeader, buf: &mut [u8], written: &mut usize) -> u8 {
554    // get_cksum returns cksum in host byte order
555    let cksum = udp_header.get_cksum().to_be();
556    buf[*written] = cksum as u8;
557    buf[*written + 1] = (cksum >> 8) as u8;
558    *written += 2;
559    // Inline checksum corresponds to the 0 flag
560    0
561}
562
563/// Decompresses a 6loWPAN header into a full IPv6 header
564///
565/// This function decompresses the header found in `buf` and writes it
566/// `out_buf`. It does not, though, copy payload bytes or a non-compressed next
567/// header. As a result, the caller should copy the `buf.len - consumed`
568/// remaining bytes from `buf` to `out_buf`.
569///
570///
571/// Note that in the case of fragmentation, the total length of the IPv6
572/// packet cannot be inferred from a single frame, and is instead provided
573/// by the dgram_size field in the fragmentation header. Thus, if we are
574/// decompressing a fragment, we rely on the dgram_size field; otherwise,
575/// we infer the length from the size of buf.
576///
577/// # Arguments
578///
579/// * `ctx_store` - ???
580///
581/// * `buf` - A slice containing the 6LowPAN packet along with its payload.
582///
583/// * `src_mac_addr` - the 16-bit MAC address of the frame sender.
584///
585/// * `dst_mac_addr` - the 16-bit MAC address of the frame receiver.
586///
587/// * `out_buf` - A buffer to write the output to. Must be at least large enough
588///   to store an IPv6 header (XX bytes).
589///
590/// * `dgram_size` - If `is_fragment` is `true`, this is used as the IPv6
591///   packets total payload size. Otherwise, this is ignored.
592///
593/// * `is_fragment` - ???
594///
595/// # Returns
596///
597/// `Ok((consumed, written))` if decompression is successful.
598///
599/// * `consumed` is the number of header bytes consumed from the 6LoWPAN header
600///
601/// * `written` is the number of uncompressed header bytes written into
602///   `out_buf`.
603pub fn decompress(
604    ctx_store: &dyn ContextStore,
605    buf: &[u8],
606    src_mac_addr: MacAddress,
607    dst_mac_addr: MacAddress,
608    out_buf: &mut [u8],
609    dgram_size: u16,
610    is_fragment: bool,
611) -> Result<(usize, usize), ()> {
612    // Get the LOWPAN_IPHC header (the first two bytes are the header)
613    let iphc_header_1: u8 = buf[0];
614    let iphc_header_2: u8 = buf[1];
615    let mut consumed: usize = 2;
616
617    let mut ip6_header = IP6Header::new();
618    let mut written: usize = mem::size_of::<IP6Header>();
619
620    // Decompress CID and CIE fields if they exist
621    let (src_ctx, dst_ctx) = decompress_cie(ctx_store, iphc_header_1, buf, &mut consumed)?;
622
623    // Traffic Class & Flow Label
624    decompress_tf(&mut ip6_header, iphc_header_1, buf, &mut consumed);
625
626    // Next Header
627    let (mut is_nhc, mut next_header) = decompress_nh(iphc_header_1, buf, &mut consumed);
628
629    // Hop Limit
630    decompress_hl(&mut ip6_header, iphc_header_1, buf, &mut consumed)?;
631
632    // Source Address
633    decompress_src(
634        &mut ip6_header,
635        iphc_header_2,
636        &src_mac_addr,
637        &src_ctx,
638        buf,
639        &mut consumed,
640    )?;
641
642    // Destination Address
643    if (iphc_header_2 & iphc::MULTICAST) != 0 {
644        decompress_multicast(&mut ip6_header, iphc_header_2, &dst_ctx, buf, &mut consumed)?;
645    } else {
646        decompress_dst(
647            &mut ip6_header,
648            iphc_header_2,
649            &dst_mac_addr,
650            &dst_ctx,
651            buf,
652            &mut consumed,
653        )?;
654    }
655
656    // next_header is already set if is_nhc is false, otherwise it can be
657    // determined from the LoWPAN NHC header byte
658    if is_nhc {
659        next_header = nhc_to_ip6_nh(buf[consumed])?;
660    }
661    ip6_header.set_next_header(next_header);
662
663    // Next headers after the IPv6 fixed header
664    // At each iteration, consumed points to the first byte of the compressed
665    // next header in buf.
666    while is_nhc {
667        // Advance past the LoWPAN NHC byte
668        let nhc_header = buf[consumed];
669        consumed += 1;
670
671        // Scoped mutable borrow of out_buf
672        let next_headers: &mut [u8] = &mut out_buf[written..];
673
674        match next_header {
675            ip6_nh::IP6 => {
676                let (encap_consumed, encap_written) = decompress(
677                    ctx_store,
678                    &buf[consumed..],
679                    src_mac_addr,
680                    dst_mac_addr,
681                    next_headers,
682                    dgram_size,
683                    is_fragment,
684                )?;
685                consumed += encap_consumed;
686                written += encap_written;
687                break;
688            }
689            ip6_nh::UDP => {
690                // UDP length includes UDP header and data in bytes
691                // Below line works bc udp nh must be last nh per 6282
692                let mut udp_length = if is_fragment {
693                    dgram_size - written as u16
694                } else {
695                    buf.len() as u16 - consumed as u16
696                };
697
698                // Decompress UDP header fields
699                let consumed_before_port_decompress = consumed;
700                let (src_port, dst_port) = decompress_udp_ports(nhc_header, buf, &mut consumed);
701
702                //need to add any growth from decompression to the udp length if we used the buf
703                //len to calculate the length
704                if !is_fragment {
705                    // Expansion from port compression
706                    udp_length +=
707                        nhc::UDP_PORTS_SIZE - ((consumed - consumed_before_port_decompress) as u16);
708                    // Expansion from length elision (always applied per RFC 6282, length is 2
709                    // bytes)
710                    udp_length += 2;
711                    // UDP checksum elision
712                    if (nhc_header & nhc::UDP_CHECKSUM_FLAG) != 0 {
713                        udp_length += 2;
714                    }
715                }
716
717                // Fill in uncompressed UDP header
718                // TODO: The current implementation works, but I don't understand the calls to
719                // to_be(), because src_port.to_be() returns the src_port in little endian..
720                // Accordingly, the udp_length must also be written in little endian for this
721                // to work.
722                u16_to_network_slice(src_port.to_be(), &mut next_headers[0..2]);
723                u16_to_network_slice(dst_port.to_be(), &mut next_headers[2..4]);
724                u16_to_network_slice(udp_length, &mut next_headers[4..6]);
725                // Need to fill in header values before computing the checksum
726                let udp_checksum = decompress_udp_checksum(
727                    nhc_header,
728                    &next_headers[0..8],
729                    udp_length,
730                    &ip6_header,
731                    buf,
732                    &mut consumed,
733                    is_fragment,
734                );
735                u16_to_network_slice(udp_checksum.to_be(), &mut next_headers[6..8]);
736
737                written += 8;
738                break;
739            }
740            ip6_nh::FRAGMENT
741            | ip6_nh::HOP_OPTS
742            | ip6_nh::ROUTING
743            | ip6_nh::DST_OPTS
744            | ip6_nh::MOBILITY => {
745                // True if the next header is also compressed
746                is_nhc = (nhc_header & nhc::NH) != 0;
747
748                // len is the number of octets following the length field
749                let len = buf[consumed] as usize;
750                consumed += 1;
751
752                // Check that there is a next header in the buffer,
753                // which must be the case if the last next header specifies
754                // NH = 1
755                if consumed + len >= buf.len() {
756                    return Err(());
757                }
758
759                // Length in 8-octet units after the first 8 octets
760                // (per the IPv6 ext hdr spec)
761                let mut hdr_len_field = (len - 6) / 8;
762                if !(len - 6).is_multiple_of(8) {
763                    hdr_len_field += 1;
764                }
765
766                // Gets the type of the subsequent next header.  If is_nhc
767                // is true, there must be a LoWPAN NHC header byte,
768                // otherwise there is either an uncompressed next header.
769                next_header = if is_nhc {
770                    // The next header is LoWPAN NHC-compressed
771                    nhc_to_ip6_nh(buf[consumed + len])?
772                } else {
773                    // The next header is uncompressed
774                    buf[consumed + len]
775                };
776
777                // Fill in the extended header in uncompressed IPv6 format
778                next_headers[0] = next_header;
779                next_headers[1] = hdr_len_field as u8;
780                // Copies over the remaining options.
781                next_headers[2..2 + len].copy_from_slice(&buf[consumed..consumed + len]);
782
783                // Fill in padding
784                let pad_bytes = hdr_len_field * 8 - len + 6;
785                if pad_bytes == 1 {
786                    // Pad1
787                    next_headers[2 + len] = 0;
788                } else {
789                    // PadN, 2 <= pad_bytes <= 7
790                    next_headers[2 + len] = 1;
791                    next_headers[2 + len + 1] = pad_bytes as u8 - 2;
792                    for i in 2..pad_bytes {
793                        next_headers[2 + len + i] = 0;
794                    }
795                }
796
797                written += 8 + hdr_len_field * 8;
798                consumed += len;
799            }
800            _ => panic!("Unreachable case"),
801        }
802    }
803
804    // The IPv6 header length field is the size of the IPv6 payload,
805    // including extension headers. This is thus the uncompressed
806    // size of the IPv6 packet - the fixed IPv6 header.
807    let payload_len = if is_fragment {
808        (dgram_size as usize) - mem::size_of::<IP6Header>()
809    } else {
810        written + (buf.len() - consumed) - mem::size_of::<IP6Header>()
811    };
812    ip6_header.payload_len = (payload_len as u16).to_be();
813    IP6Header::encode(&ip6_header, out_buf).done().ok_or(())?;
814    Ok((consumed, written))
815}
816
817fn decompress_cie(
818    ctx_store: &dyn ContextStore,
819    iphc_header: u8,
820    buf: &[u8],
821    consumed: &mut usize,
822) -> Result<(Context, Context), ()> {
823    let ctx_0 = ctx_store.get_context_0();
824    let (mut src_ctx, mut dst_ctx) = (ctx_0, ctx_0);
825    if iphc_header & iphc::CID != 0 {
826        let sci = buf[*consumed] >> 4;
827        let dci = buf[*consumed] & 0xf;
828        *consumed += 1;
829
830        if sci != 0 {
831            src_ctx = ctx_store.get_context_from_id(sci).ok_or(())?;
832        }
833        if dci != 0 {
834            dst_ctx = ctx_store.get_context_from_id(dci).ok_or(())?;
835        }
836    }
837    Ok((src_ctx, dst_ctx))
838}
839
840fn decompress_tf(ip6_header: &mut IP6Header, iphc_header: u8, buf: &[u8], consumed: &mut usize) {
841    let fl_compressed = (iphc_header & iphc::TF_FLOW_LABEL) != 0;
842    let tc_compressed = (iphc_header & iphc::TF_TRAFFIC_CLASS) != 0;
843
844    // Determine ECN and DSCP separately because the order is different
845    // from the IPv6 traffic class field.
846    if !fl_compressed || !tc_compressed {
847        let ecn = buf[*consumed] >> 6;
848        ip6_header.set_ecn(ecn);
849    }
850    if !tc_compressed {
851        let dscp = buf[*consumed] & 0b111111;
852        ip6_header.set_dscp(dscp);
853        *consumed += 1;
854    }
855
856    // Flow label is always in the same bit position relative to the last
857    // three bytes in the inline fields
858    if fl_compressed {
859        ip6_header.set_flow_label(0);
860    } else {
861        let flow = (((buf[*consumed] & 0x0f) as u32) << 16)
862            | ((buf[*consumed + 1] as u32) << 8)
863            | (buf[*consumed + 2] as u32);
864        *consumed += 3;
865        ip6_header.set_flow_label(flow);
866    }
867}
868
869fn decompress_nh(iphc_header: u8, buf: &[u8], consumed: &mut usize) -> (bool, u8) {
870    let is_nhc = (iphc_header & iphc::NH) != 0;
871    let mut next_header: u8 = 0;
872    if !is_nhc {
873        next_header = buf[*consumed];
874        *consumed += 1;
875    }
876    (is_nhc, next_header)
877}
878
879fn decompress_hl(
880    ip6_header: &mut IP6Header,
881    iphc_header: u8,
882    buf: &[u8],
883    consumed: &mut usize,
884) -> Result<(), ()> {
885    let hop_limit = match iphc_header & iphc::HLIM_MASK {
886        iphc::HLIM_1 => 1,
887        iphc::HLIM_64 => 64,
888        iphc::HLIM_255 => 255,
889        iphc::HLIM_INLINE => {
890            let hl = buf[*consumed];
891            *consumed += 1;
892            hl
893        }
894        _ => panic!("Unreachable case"),
895    };
896    ip6_header.set_hop_limit(hop_limit);
897    Ok(())
898}
899
900fn decompress_src(
901    ip6_header: &mut IP6Header,
902    iphc_header: u8,
903    mac_addr: &MacAddress,
904    ctx: &Context,
905    buf: &[u8],
906    consumed: &mut usize,
907) -> Result<(), ()> {
908    let uses_context = (iphc_header & iphc::SAC) != 0;
909    let sam_mode = iphc_header & iphc::SAM_MASK;
910    if uses_context && sam_mode == iphc::SAM_INLINE {
911        // SAC = 1, SAM = 00: UNSPECIFIED (::), which is already the default
912    } else if uses_context {
913        // SAC = 1, SAM = 01, 10, 11
914        decompress_iid_context(
915            sam_mode,
916            &mut ip6_header.src_addr,
917            mac_addr,
918            ctx,
919            buf,
920            consumed,
921        )?;
922    } else {
923        // SAC = 0, SAM = 00, 01, 10, 11
924        decompress_iid_link_local(sam_mode, &mut ip6_header.src_addr, mac_addr, buf, consumed)?;
925    }
926    Ok(())
927}
928
929fn decompress_dst(
930    ip6_header: &mut IP6Header,
931    iphc_header: u8,
932    mac_addr: &MacAddress,
933    ctx: &Context,
934    buf: &[u8],
935    consumed: &mut usize,
936) -> Result<(), ()> {
937    let uses_context = (iphc_header & iphc::DAC) != 0;
938    let dam_mode = iphc_header & iphc::DAM_MASK;
939    if uses_context && dam_mode == iphc::DAM_INLINE {
940        // DAC = 1, DAM = 00: Reserved
941        return Err(());
942    } else if uses_context {
943        // DAC = 1, DAM = 01, 10, 11
944        decompress_iid_context(
945            dam_mode,
946            &mut ip6_header.dst_addr,
947            mac_addr,
948            ctx,
949            buf,
950            consumed,
951        )?;
952    } else {
953        // DAC = 0, DAM = 00, 01, 10, 11
954        decompress_iid_link_local(dam_mode, &mut ip6_header.dst_addr, mac_addr, buf, consumed)?;
955    }
956    Ok(())
957}
958
959fn decompress_multicast(
960    ip6_header: &mut IP6Header,
961    iphc_header: u8,
962    ctx: &Context,
963    buf: &[u8],
964    consumed: &mut usize,
965) -> Result<(), ()> {
966    let uses_context = (iphc_header & iphc::DAC) != 0;
967    let dam_mode = iphc_header & iphc::DAM_MASK;
968    let ip_addr: &mut IPAddr = &mut ip6_header.dst_addr;
969    if uses_context {
970        match dam_mode {
971            iphc::DAM_INLINE => {
972                // DAC = 1, DAM = 00: 48 bits
973                // ffXX:XXLL:PPPP:PPPP:PPPP:PPPP:XXXX:XXXX
974                let prefix_bytes = ctx.prefix_len.div_ceil(8) as usize;
975                if prefix_bytes > 8 {
976                    // The maximum prefix length for this mode is 64 bits.
977                    // If the specified prefix exceeds this length, the
978                    // compression is invalid.
979                    return Err(());
980                }
981                ip_addr.0[0] = 0xff;
982                ip_addr.0[1] = buf[*consumed];
983                ip_addr.0[2] = buf[*consumed + 1];
984                ip_addr.0[3] = ctx.prefix_len;
985                ip_addr.0[4..4 + prefix_bytes].copy_from_slice(&ctx.prefix[0..prefix_bytes]);
986                ip_addr.0[12..16].copy_from_slice(&buf[*consumed + 2..*consumed + 6]);
987                *consumed += 6;
988            }
989            _ => {
990                // DAC = 1, DAM = 01, 10, 11: Reserved
991                return Err(());
992            }
993        }
994    } else {
995        match dam_mode {
996            // DAC = 0, DAM = 00: Inline
997            iphc::DAM_INLINE => {
998                ip_addr.0.copy_from_slice(&buf[*consumed..*consumed + 16]);
999                *consumed += 16;
1000            }
1001            // DAC = 0, DAM = 01: 48 bits
1002            // ffXX::00XX:XXXX:XXXX
1003            iphc::DAM_MODE1 => {
1004                ip_addr.0[0] = 0xff;
1005                ip_addr.0[1] = buf[*consumed];
1006                *consumed += 1;
1007                ip_addr.0[11..16].copy_from_slice(&buf[*consumed..*consumed + 5]);
1008                *consumed += 5;
1009            }
1010            // DAC = 0, DAM = 10: 32 bits
1011            // ffXX::00XX:XXXX
1012            iphc::DAM_MODE2 => {
1013                ip_addr.0[0] = 0xff;
1014                ip_addr.0[1] = buf[*consumed];
1015                *consumed += 1;
1016                ip_addr.0[13..16].copy_from_slice(&buf[*consumed..*consumed + 3]);
1017                *consumed += 3;
1018            }
1019            // DAC = 0, DAM = 11: 8 bits
1020            // ff02::00XX
1021            iphc::DAM_MODE3 => {
1022                ip_addr.0[0] = 0xff;
1023                ip_addr.0[1] = 0x02;
1024                ip_addr.0[15] = buf[*consumed];
1025                *consumed += 1;
1026            }
1027            _ => panic!("Unreachable case"),
1028        }
1029    }
1030    Ok(())
1031}
1032
1033fn decompress_iid_link_local(
1034    addr_mode: u8,
1035    ip_addr: &mut IPAddr,
1036    mac_addr: &MacAddress,
1037    buf: &[u8],
1038    consumed: &mut usize,
1039) -> Result<(), ()> {
1040    let mode = addr_mode & (iphc::SAM_MASK | iphc::DAM_MASK);
1041    match mode {
1042        // SAM, DAM = 00: Inline
1043        iphc::SAM_INLINE => {
1044            // SAM_INLINE is equivalent to DAM_INLINE
1045            ip_addr.0.copy_from_slice(&buf[*consumed..*consumed + 16]);
1046            *consumed += 16;
1047        }
1048        // SAM, DAM = 01: 64 bits
1049        // Link-local prefix (64 bits) + 64 bits carried inline
1050        iphc::SAM_MODE1 | iphc::DAM_MODE1 => {
1051            ip_addr.set_unicast_link_local();
1052            ip_addr.0[8..16].copy_from_slice(&buf[*consumed..*consumed + 8]);
1053            *consumed += 8;
1054        }
1055        // SAM, DAM = 11: 16 bits
1056        // Link-local prefix (112 bits) + 0000:00ff:fe00:XXXX
1057        iphc::SAM_MODE2 | iphc::DAM_MODE2 => {
1058            ip_addr.set_unicast_link_local();
1059            ip_addr.0[11..13].copy_from_slice(&iphc::MAC_BASE[3..5]);
1060            ip_addr.0[14..16].copy_from_slice(&buf[*consumed..*consumed + 2]);
1061            *consumed += 2;
1062        }
1063        // SAM, DAM = 11: 0 bits
1064        // Linx-local prefix (64 bits) + IID from outer header (64 bits)
1065        iphc::SAM_MODE3 | iphc::DAM_MODE3 => {
1066            ip_addr.set_unicast_link_local();
1067            ip_addr.0[8..16].copy_from_slice(&compute_iid(mac_addr));
1068        }
1069        _ => panic!("Unreachable case"),
1070    }
1071    Ok(())
1072}
1073
1074fn decompress_iid_context(
1075    addr_mode: u8,
1076    ip_addr: &mut IPAddr,
1077    mac_addr: &MacAddress,
1078    ctx: &Context,
1079    buf: &[u8],
1080    consumed: &mut usize,
1081) -> Result<(), ()> {
1082    let mode = addr_mode & (iphc::SAM_MASK | iphc::DAM_MASK);
1083    match mode {
1084        // DAM = 00: Reserved
1085        // SAM = 0 is handled separately outside this method
1086        iphc::DAM_INLINE => {
1087            return Err(());
1088        }
1089        // SAM, DAM = 01: 64 bits
1090        // Suffix is the 64 bits carried inline
1091        iphc::SAM_MODE1 | iphc::DAM_MODE1 => {
1092            ip_addr.0[8..16].copy_from_slice(&buf[*consumed..*consumed + 8]);
1093            *consumed += 8;
1094        }
1095        // SAM, DAM = 10: 16 bits
1096        // Suffix is 0000:00ff:fe00:XXXX
1097        iphc::SAM_MODE2 | iphc::DAM_MODE2 => {
1098            ip_addr.0[8..16].copy_from_slice(&iphc::MAC_BASE);
1099            ip_addr.0[14..16].copy_from_slice(&buf[*consumed..*consumed + 2]);
1100            *consumed += 2;
1101        }
1102        // SAM, DAM = 11: 0 bits
1103        // Suffix is the IID computed from the encapsulating header
1104        iphc::SAM_MODE3 | iphc::DAM_MODE3 => {
1105            let iid = compute_iid(mac_addr);
1106            ip_addr.0[8..16].copy_from_slice(&iid[0..8]);
1107        }
1108        _ => panic!("Unreachable case"),
1109    }
1110    // The bits covered by the provided context are always used, so we copy
1111    // the context bits into the address after the non-context bits are set.
1112    ip_addr.set_prefix(&ctx.prefix, ctx.prefix_len);
1113    Ok(())
1114}
1115
1116// Returns the UDP ports in host byte-order
1117fn decompress_udp_ports(udp_nhc: u8, buf: &[u8], consumed: &mut usize) -> (u16, u16) {
1118    let src_compressed = (udp_nhc & nhc::UDP_SRC_PORT_FLAG) != 0;
1119    let dst_compressed = (udp_nhc & nhc::UDP_DST_PORT_FLAG) != 0;
1120
1121    let src_port;
1122    let dst_port;
1123    if src_compressed && dst_compressed {
1124        // Both src and dst are compressed to 4 bits
1125        let src_short = ((buf[*consumed] >> 4) & 0xf) as u16;
1126        let dst_short = (buf[*consumed] & 0xf) as u16;
1127        src_port = nhc::UDP_4BIT_PORT | src_short;
1128        dst_port = nhc::UDP_4BIT_PORT | dst_short;
1129        *consumed += 1;
1130    } else if src_compressed {
1131        // Source port is compressed to 8 bits
1132        src_port = nhc::UDP_8BIT_PORT | (buf[*consumed] as u16);
1133        // Destination port is uncompressed
1134        dst_port = u16::from_be(network_slice_to_u16(&buf[*consumed + 1..*consumed + 3]));
1135        *consumed += 3;
1136    } else if dst_compressed {
1137        // Source port is uncompressed
1138        src_port = u16::from_be(network_slice_to_u16(&buf[*consumed..*consumed + 2]));
1139        // Destination port is compressed to 8 bits
1140        dst_port = nhc::UDP_8BIT_PORT | (buf[*consumed + 2] as u16);
1141        *consumed += 3;
1142    } else {
1143        // Both ports are uncompressed
1144        src_port = u16::from_be(network_slice_to_u16(&buf[*consumed..*consumed + 2]));
1145        dst_port = u16::from_be(network_slice_to_u16(&buf[*consumed + 2..*consumed + 4]));
1146        *consumed += 4;
1147    }
1148    (src_port, dst_port)
1149}
1150
1151// Returns the UDP checksum in host byte-order
1152fn decompress_udp_checksum(
1153    udp_nhc: u8,
1154    udp_header: &[u8],
1155    udp_length: u16,
1156    ip6_header: &IP6Header,
1157    buf: &[u8],
1158    consumed: &mut usize,
1159    is_fragment: bool,
1160) -> u16 {
1161    // TODO: In keeping with Postel's Law, we accept UDP packets that elide the
1162    // checksum (per RFC 6282). We are not sure if we should continue to support
1163    // this feature however.
1164    // Also, this implementation currently does not work for multi-frame packets,
1165    // as decompress is called on the first frame before the others arrive.
1166    if (udp_nhc & nhc::UDP_CHECKSUM_FLAG) != 0 && !is_fragment {
1167        let mut udp_header_copy: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
1168        udp_header_copy.copy_from_slice(udp_header);
1169        match UDPHeader::decode(&udp_header_copy).done() {
1170            Some((_offset, hdr)) => u16::from_be(compute_udp_checksum(
1171                ip6_header,
1172                &hdr,
1173                udp_length,
1174                &buf[*consumed..],
1175            )),
1176            None => 0, //Will be dropped  by IP layer
1177        }
1178    } else {
1179        let checksum = u16::from_be(network_slice_to_u16(&buf[*consumed..*consumed + 2]));
1180        *consumed += 2;
1181        checksum
1182    }
1183}