Skip to main content

packet_formats/
ip.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! IP protocol types.
6
7// TODO(https://fxbug.dev/326330182): this import seems actually necessary. Is this a bug on the
8// lint?
9#[allow(unused_imports)]
10use alloc::vec::Vec;
11use core::cmp::PartialEq;
12use core::convert::Infallible as Never;
13use core::fmt::{Debug, Display};
14use core::hash::Hash;
15
16use net_types::ip::{GenericOverIp, Ip, IpAddr, Ipv4, Ipv4Addr, Ipv6, Ipv6Addr};
17use packet::{BufferViewMut, PacketBuilder, ParsablePacket, ParseMetadata, PartialPacketBuilder};
18use zerocopy::{
19    FromBytes, Immutable, IntoBytes, KnownLayout, SplitByteSlice, SplitByteSliceMut, Unaligned,
20};
21
22use crate::error::{IpParseResult, Ipv6ParseError, ParseError};
23use crate::ethernet::EthernetIpExt;
24use crate::icmp::IcmpIpExt;
25use crate::ipv4::{IPV4_MIN_HDR_LEN, Ipv4Header, Ipv4Packet, Ipv4PacketBuilder, Ipv4PacketRaw};
26use crate::ipv6::{IPV6_FIXED_HDR_LEN, Ipv6Header, Ipv6Packet, Ipv6PacketBuilder, Ipv6PacketRaw};
27use crate::private::Sealed;
28
29/// An [`Ip`] extension trait adding an associated type for the IP protocol
30/// number.
31pub trait IpProtoExt: Ip {
32    /// The type representing an IPv4 or IPv6 protocol number.
33    ///
34    /// For IPv4, this is [`Ipv4Proto`], and for IPv6, this is [`Ipv6Proto`].
35    type Proto: IpProtocol
36        + GenericOverIp<Self, Type = Self::Proto>
37        + GenericOverIp<Ipv4, Type = Ipv4Proto>
38        + GenericOverIp<Ipv6, Type = Ipv6Proto>
39        + Copy
40        + Clone
41        + Hash
42        + Debug
43        + Display
44        + PartialEq
45        + Eq
46        + PartialOrd
47        + Ord;
48}
49
50impl IpProtoExt for Ipv4 {
51    type Proto = Ipv4Proto;
52}
53
54impl IpProtoExt for Ipv6 {
55    type Proto = Ipv6Proto;
56}
57
58/// An extension trait to the `Ip` trait adding associated types relevant for
59/// packet parsing and serialization.
60pub trait IpExt: EthernetIpExt + IcmpIpExt {
61    /// The error type returned when parsing a packet of this IP version fails.
62    type PacketParseError: From<ParseError> + Debug + PartialEq + Send + Sync;
63
64    /// An IP packet type for this IP version.
65    type Packet<B: SplitByteSlice>: IpPacket<B, Self, Builder = Self::PacketBuilder>
66        + GenericOverIp<Self, Type = Self::Packet<B>>
67        + GenericOverIp<Ipv4, Type = Ipv4Packet<B>>
68        + GenericOverIp<Ipv6, Type = Ipv6Packet<B>>;
69    /// A raw IP packet type for this IP version.
70    type PacketRaw<B: SplitByteSlice>: IpPacketRaw<B, Self>
71        + GenericOverIp<Self, Type = Self::PacketRaw<B>>
72        + GenericOverIp<Ipv4, Type = Ipv4PacketRaw<B>>
73        + GenericOverIp<Ipv6, Type = Ipv6PacketRaw<B>>;
74    /// An IP packet builder type for the IP version.
75    type PacketBuilder: IpPacketBuilder<Self> + Eq;
76    /// Minimal IP header size.
77    const MIN_HEADER_LENGTH: usize;
78}
79
80impl IpExt for Ipv4 {
81    type PacketParseError = ParseError;
82    type Packet<B: SplitByteSlice> = Ipv4Packet<B>;
83    type PacketRaw<B: SplitByteSlice> = Ipv4PacketRaw<B>;
84    type PacketBuilder = Ipv4PacketBuilder;
85
86    const MIN_HEADER_LENGTH: usize = IPV4_MIN_HDR_LEN;
87}
88
89impl IpExt for Ipv6 {
90    type PacketParseError = Ipv6ParseError;
91    type Packet<B: SplitByteSlice> = Ipv6Packet<B>;
92    type PacketRaw<B: SplitByteSlice> = Ipv6PacketRaw<B>;
93    type PacketBuilder = Ipv6PacketBuilder;
94
95    const MIN_HEADER_LENGTH: usize = IPV6_FIXED_HDR_LEN;
96}
97
98/// An error encountered during NAT64 translation.
99#[derive(Debug)]
100pub enum Nat64Error {
101    /// Support not yet implemented in the library.
102    NotImplemented,
103}
104
105/// The result of NAT64 translation.
106#[derive(Debug)]
107pub enum Nat64TranslationResult<S, E> {
108    /// Forward the packet encoded in `S`.
109    Forward(S),
110    /// Silently drop the packet.
111    Drop,
112    /// An error was encountered.
113    Err(E),
114}
115
116/// Combines Differentiated Services Code Point (DSCP) and Explicit Congestion
117/// Notification (ECN) values into one. Internally the 2 fields are stored
118/// using the same layout as the Traffic Class field in IPv6 and the Type Of
119/// Service field in IPv4: 6 higher bits for DSCP and 2 lower bits for ECN.
120#[derive(
121    Default,
122    Debug,
123    Clone,
124    Copy,
125    PartialEq,
126    Eq,
127    KnownLayout,
128    FromBytes,
129    IntoBytes,
130    Immutable,
131    Unaligned,
132)]
133#[repr(C)]
134pub struct DscpAndEcn(u8);
135
136const DSCP_OFFSET: u8 = 2;
137const DSCP_MAX: u8 = (1 << (8 - DSCP_OFFSET)) - 1;
138const ECN_MAX: u8 = (1 << DSCP_OFFSET) - 1;
139
140impl DscpAndEcn {
141    /// Returns the default value. Implemented separately from the `Default`
142    /// trait to make it `const`.
143    pub const fn default() -> Self {
144        Self(0)
145    }
146
147    /// Creates a new `DscpAndEcn` instance with the specified DSCP and ECN
148    /// values.
149    pub const fn new(dscp: u8, ecn: u8) -> Self {
150        debug_assert!(dscp <= DSCP_MAX);
151        debug_assert!(ecn <= ECN_MAX);
152        Self((dscp << DSCP_OFFSET) + ecn)
153    }
154
155    /// Constructs a new `DspAndEcn` from a raw value, i.e., both fields packet
156    /// into one byte.
157    pub const fn new_with_raw(value: u8) -> Self {
158        Self(value)
159    }
160
161    /// Returns the Differentiated Services Code Point value.
162    pub fn dscp(self) -> u8 {
163        let Self(v) = self;
164        v >> 2
165    }
166
167    /// Returns the Explicit Congestion Notification value.
168    pub fn ecn(self) -> u8 {
169        let Self(v) = self;
170        v & 0x3
171    }
172
173    /// Returns the raw value, i.e. both fields packed into one byte.
174    pub fn raw(self) -> u8 {
175        let Self(value) = self;
176        value
177    }
178}
179
180impl From<u8> for DscpAndEcn {
181    fn from(value: u8) -> Self {
182        Self::new_with_raw(value)
183    }
184}
185
186/// An IPv4 or IPv6 packet.
187///
188/// `IpPacket` is implemented by `Ipv4Packet` and `Ipv6Packet`.
189pub trait IpPacket<B: SplitByteSlice, I: IpExt>:
190    Sized + Debug + ParsablePacket<B, (), Error = I::PacketParseError>
191{
192    /// A builder for this packet type.
193    type Builder: IpPacketBuilder<I>;
194
195    /// The source IP address.
196    fn src_ip(&self) -> I::Addr;
197
198    /// The destination IP address.
199    fn dst_ip(&self) -> I::Addr;
200
201    /// The protocol number.
202    fn proto(&self) -> I::Proto;
203
204    /// The Time to Live (TTL) (IPv4) or Hop Limit (IPv6) field.
205    fn ttl(&self) -> u8;
206
207    /// The Differentiated Services Code Point (DSCP) and the Explicit
208    /// Congestion Notification (ECN).
209    fn dscp_and_ecn(&self) -> DscpAndEcn;
210
211    /// Set the Time to Live (TTL) (IPv4) or Hop Limit (IPv6) field.
212    ///
213    /// `set_ttl` updates the packet's TTL/Hop Limit in place.
214    fn set_ttl(&mut self, ttl: u8)
215    where
216        B: SplitByteSliceMut;
217
218    /// Get the body.
219    fn body(&self) -> &[u8];
220
221    /// Consume the packet and return some metadata.
222    ///
223    /// Consume the packet and return the source address, destination address,
224    /// protocol, and `ParseMetadata`.
225    fn into_metadata(self) -> (I::Addr, I::Addr, I::Proto, ParseMetadata) {
226        let src_ip = self.src_ip();
227        let dst_ip = self.dst_ip();
228        let proto = self.proto();
229        let meta = self.parse_metadata();
230        (src_ip, dst_ip, proto, meta)
231    }
232
233    /// Converts a packet reference into a dynamically-typed reference.
234    fn as_ip_addr_ref(&self) -> IpAddr<&'_ Ipv4Packet<B>, &'_ Ipv6Packet<B>>;
235
236    /// Reassembles a fragmented packet into a parsed IP packet.
237    fn reassemble_fragmented_packet<BV: BufferViewMut<B>, IT: Iterator<Item = Vec<u8>>>(
238        buffer: BV,
239        header: Vec<u8>,
240        body_fragments: IT,
241    ) -> IpParseResult<I, ()>
242    where
243        B: SplitByteSliceMut;
244
245    /// Copies the full packet into a `Vec`.
246    fn to_vec(&self) -> Vec<u8>;
247
248    /// Constructs a builder with the same contents as this packet's header.
249    fn builder(&self) -> Self::Builder;
250}
251
252impl<B: SplitByteSlice> IpPacket<B, Ipv4> for Ipv4Packet<B> {
253    type Builder = Ipv4PacketBuilder;
254
255    fn src_ip(&self) -> Ipv4Addr {
256        Ipv4Header::src_ip(self)
257    }
258    fn dst_ip(&self) -> Ipv4Addr {
259        Ipv4Header::dst_ip(self)
260    }
261    fn proto(&self) -> Ipv4Proto {
262        Ipv4Header::proto(self)
263    }
264    fn dscp_and_ecn(&self) -> DscpAndEcn {
265        Ipv4Header::dscp_and_ecn(self)
266    }
267    fn ttl(&self) -> u8 {
268        Ipv4Header::ttl(self)
269    }
270    fn set_ttl(&mut self, ttl: u8)
271    where
272        B: SplitByteSliceMut,
273    {
274        Ipv4Packet::set_ttl(self, ttl)
275    }
276    fn body(&self) -> &[u8] {
277        Ipv4Packet::body(self)
278    }
279
280    fn as_ip_addr_ref(&self) -> IpAddr<&'_ Self, &'_ Ipv6Packet<B>> {
281        IpAddr::V4(self)
282    }
283
284    fn reassemble_fragmented_packet<BV: BufferViewMut<B>, IT: Iterator<Item = Vec<u8>>>(
285        buffer: BV,
286        header: Vec<u8>,
287        body_fragments: IT,
288    ) -> IpParseResult<Ipv4, ()>
289    where
290        B: SplitByteSliceMut,
291    {
292        crate::ipv4::reassemble_fragmented_packet(buffer, header, body_fragments)
293    }
294
295    fn to_vec(&self) -> Vec<u8> {
296        self.to_vec()
297    }
298
299    fn builder(&self) -> Self::Builder {
300        Ipv4Header::builder(self)
301    }
302}
303
304impl<B: SplitByteSlice> IpPacket<B, Ipv6> for Ipv6Packet<B> {
305    type Builder = Ipv6PacketBuilder;
306
307    fn src_ip(&self) -> Ipv6Addr {
308        Ipv6Header::src_ip(self)
309    }
310    fn dst_ip(&self) -> Ipv6Addr {
311        Ipv6Header::dst_ip(self)
312    }
313    fn proto(&self) -> Ipv6Proto {
314        Ipv6Packet::proto(self)
315    }
316    fn dscp_and_ecn(&self) -> DscpAndEcn {
317        Ipv6Header::dscp_and_ecn(self)
318    }
319    fn ttl(&self) -> u8 {
320        Ipv6Header::hop_limit(self)
321    }
322    fn set_ttl(&mut self, ttl: u8)
323    where
324        B: SplitByteSliceMut,
325    {
326        Ipv6Packet::set_hop_limit(self, ttl)
327    }
328    fn body(&self) -> &[u8] {
329        Ipv6Packet::body(self)
330    }
331
332    fn as_ip_addr_ref(&self) -> IpAddr<&'_ Ipv4Packet<B>, &'_ Self> {
333        IpAddr::V6(self)
334    }
335    fn reassemble_fragmented_packet<BV: BufferViewMut<B>, IT: Iterator<Item = Vec<u8>>>(
336        buffer: BV,
337        header: Vec<u8>,
338        body_fragments: IT,
339    ) -> IpParseResult<Ipv6, ()>
340    where
341        B: SplitByteSliceMut,
342    {
343        crate::ipv6::reassemble_fragmented_packet(buffer, header, body_fragments)
344    }
345
346    fn to_vec(&self) -> Vec<u8> {
347        self.to_vec()
348    }
349
350    fn builder(&self) -> Self::Builder {
351        self.builder()
352    }
353}
354
355/// A raw IPv4 or IPv6 packet.
356///
357/// `IpPacketRaw` is implemented by `Ipv4PacketRaw` and `Ipv6PacketRaw`.
358pub trait IpPacketRaw<B: SplitByteSlice, I: IpExt>:
359    Sized + ParsablePacket<B, (), Error = I::PacketParseError>
360{
361}
362
363impl<B: SplitByteSlice> IpPacketRaw<B, Ipv4> for Ipv4PacketRaw<B> {}
364impl<B: SplitByteSlice, I: IpExt> GenericOverIp<I> for Ipv4PacketRaw<B> {
365    type Type = <I as IpExt>::PacketRaw<B>;
366}
367
368impl<B: SplitByteSlice> IpPacketRaw<B, Ipv6> for Ipv6PacketRaw<B> {}
369impl<B: SplitByteSlice, I: IpExt> GenericOverIp<I> for Ipv6PacketRaw<B> {
370    type Type = <I as IpExt>::PacketRaw<B>;
371}
372
373/// A builder for IP packets.
374pub trait IpPacketBuilder<I: IpExt>: PacketBuilder + PartialPacketBuilder + Clone + Debug {
375    /// Returns a new packet builder for an associated IP version with the given
376    /// given source and destination IP addresses, TTL (IPv4)/Hop Limit (IPv4)
377    /// and Protocol Number.
378    fn new(src_ip: I::Addr, dst_ip: I::Addr, ttl: u8, proto: I::Proto) -> Self;
379
380    /// Returns the source IP address for the builder.
381    fn src_ip(&self) -> I::Addr;
382
383    /// Sets the source IP address for the builder.
384    fn set_src_ip(&mut self, addr: I::Addr);
385
386    /// Returns the destination IP address for the builder.
387    fn dst_ip(&self) -> I::Addr;
388
389    /// Sets the destination IP address for the builder.
390    fn set_dst_ip(&mut self, addr: I::Addr);
391
392    /// Returns the IP protocol number for the builder.
393    fn proto(&self) -> I::Proto;
394
395    /// Set DSCP & ECN fields.
396    fn set_dscp_and_ecn(&mut self, dscp_and_ecn: DscpAndEcn);
397}
398
399/// An IPv4 or IPv6 protocol number.
400pub trait IpProtocol: From<IpProto> + From<u8> + Sealed + Send + Sync + 'static {}
401
402impl Sealed for Never {}
403
404create_protocol_enum!(
405    /// An IPv4 or IPv6 protocol number.
406    ///
407    /// `IpProto` encodes the protocol numbers whose values are the same for
408    /// both IPv4 and IPv6.
409    ///
410    /// The protocol numbers are maintained [by IANA][protocol-numbers].
411    ///
412    /// [protocol-numbers]: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
413    #[allow(missing_docs)]
414    #[derive(Copy, Clone, Hash, Eq, Ord, PartialEq, PartialOrd)]
415    pub enum IpProto: u8 {
416        Tcp, 6, "TCP";
417        Udp, 17, "UDP";
418        Reserved, 255, "IANA-RESERVED";
419    }
420);
421
422create_protocol_enum!(
423    /// An IPv4 protocol number.
424    ///
425    /// The protocol numbers are maintained [by IANA][protocol-numbers].
426    ///
427    /// [protocol-numbers]: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
428    #[allow(missing_docs)]
429    #[derive(Copy, Clone, Hash, Eq, Ord, PartialEq, PartialOrd)]
430    pub enum Ipv4Proto: u8 {
431        Icmp, 1, "ICMP";
432        Igmp, 2, "IGMP";
433        + Proto(IpProto);
434        _, "IPv4 protocol {}";
435    }
436);
437
438impl IpProtocol for Ipv4Proto {}
439impl<I: Ip + IpProtoExt> GenericOverIp<I> for Ipv4Proto {
440    type Type = I::Proto;
441}
442impl Sealed for Ipv4Proto {}
443
444create_protocol_enum!(
445    /// An IPv6 protocol number.
446    ///
447    /// The protocol numbers are maintained [by IANA][protocol-numbers].
448    ///
449    /// [protocol-numbers]: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
450    #[allow(missing_docs)]
451    #[derive(Copy, Clone, Hash, Eq, Ord, PartialEq, PartialOrd)]
452    pub enum Ipv6Proto: u8 {
453        Icmpv6, 58, "ICMPv6";
454        NoNextHeader, 59, "NO NEXT HEADER";
455        + Proto(IpProto);
456        _, "IPv6 protocol {}";
457    }
458);
459
460impl IpProtocol for Ipv6Proto {}
461impl<I: Ip + IpProtoExt> GenericOverIp<I> for Ipv6Proto {
462    type Type = I::Proto;
463}
464impl Sealed for Ipv6Proto {}
465
466create_protocol_enum!(
467    /// An IPv6 extension header.
468    ///
469    /// These are next header values that encode for extension header types.
470    /// This enum does not include upper layer protocol numbers even though they
471    /// may be valid next header values.
472    #[allow(missing_docs)]
473    #[derive(Copy, Clone, Hash, Eq, PartialEq)]
474    pub enum Ipv6ExtHdrType: u8 {
475        HopByHopOptions, 0, "IPv6 HOP-BY-HOP OPTIONS HEADER";
476        Routing, 43, "IPv6 ROUTING HEADER";
477        Fragment, 44, "IPv6 FRAGMENT HEADER";
478        EncapsulatingSecurityPayload, 50, "ENCAPSULATING SECURITY PAYLOAD";
479        Authentication, 51, "AUTHENTICATION HEADER";
480        DestinationOptions, 60, "IPv6 DESTINATION OPTIONS HEADER";
481        _,  "IPv6 EXTENSION HEADER {}";
482    }
483);
484
485/// An IP fragment offset.
486///
487/// Represents a fragment offset found in an IP header. The offset is expressed
488/// in units of 8 octets and must be smaller than `1 << 13`.
489///
490/// This is valid for both IPv4 ([RFC 791 Section 3.1]) and IPv6 ([RFC 8200
491/// Section 4.5]) headers.
492///
493/// [RFC 791 Section 3.1]: https://datatracker.ietf.org/doc/html/rfc791#section-3.1
494/// [RFC 8200 Section 4.5]: https://datatracker.ietf.org/doc/html/rfc8200#section-4.5
495#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
496pub struct FragmentOffset(u16);
497
498impl FragmentOffset {
499    /// The zero fragment offset.
500    pub const ZERO: FragmentOffset = FragmentOffset(0);
501
502    /// Creates a new offset from a raw u16 value.
503    ///
504    /// Returns `None` if `offset` is not smaller than `1 << 13`.
505    pub const fn new(offset: u16) -> Option<Self> {
506        if offset < 1 << 13 { Some(Self(offset)) } else { None }
507    }
508
509    /// Creates a new offset from a raw u16 value masking to only the lowest 13
510    /// bits.
511    pub(crate) fn new_with_lsb(offset: u16) -> Self {
512        Self(offset & 0x1FFF)
513    }
514
515    /// Creates a new offset from a raw u16 value masking to only the highest 13
516    /// bits.
517    pub(crate) fn new_with_msb(offset: u16) -> Self {
518        Self(offset >> 3)
519    }
520
521    /// Creates a new offset from a raw bytes value.
522    ///
523    /// Returns `None` if `offset_bytes` is not a multiple of `8`.
524    pub const fn new_with_bytes(offset_bytes: u16) -> Option<Self> {
525        if offset_bytes & 0x7 == 0 {
526            // NOTE: check for length above ensures this fits in a u16.
527            Some(Self(offset_bytes >> 3))
528        } else {
529            None
530        }
531    }
532
533    /// Consumes `self` returning the raw offset value in 8-octets multiples.
534    pub const fn into_raw(self) -> u16 {
535        self.0
536    }
537
538    /// Consumes `self` returning the total number of bytes represented by this
539    /// offset.
540    ///
541    /// Equal to 8 times the raw offset value.
542    pub fn into_bytes(self) -> u16 {
543        // NB: Shift can't overflow because `FragmentOffset` is guaranteed to
544        // fit in 13 bits.
545        self.0 << 3
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    #[test]
554    fn fragment_offset_raw() {
555        assert_eq!(FragmentOffset::new(1), Some(FragmentOffset(1)));
556        assert_eq!(FragmentOffset::new(1 << 13), None);
557    }
558
559    #[test]
560    fn fragment_offset_bytes() {
561        assert_eq!(FragmentOffset::new_with_bytes(0), Some(FragmentOffset(0)));
562        for i in 1..=7 {
563            assert_eq!(FragmentOffset::new_with_bytes(i), None);
564        }
565        assert_eq!(FragmentOffset::new_with_bytes(8), Some(FragmentOffset(1)));
566        assert_eq!(FragmentOffset::new_with_bytes(core::u16::MAX), None);
567        assert_eq!(
568            FragmentOffset::new_with_bytes(core::u16::MAX & !0x7),
569            Some(FragmentOffset((1 << 13) - 1)),
570        );
571    }
572}