netstack3_ip/
local_delivery.rs

1// Copyright 2024 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//! Types and helpers used in local-delivery of packets.
6
7use core::num::NonZeroU16;
8
9use net_types::ip::{GenericOverIp, Ip, Ipv4, Ipv6};
10use net_types::SpecifiedAddr;
11use netstack3_base::{IpExt, Marks};
12use packet_formats::ip::DscpAndEcn;
13use packet_formats::ipv4::options::Ipv4Option;
14use packet_formats::ipv4::Ipv4Header as _;
15use packet_formats::ipv6::ext_hdrs::{HopByHopOptionData, Ipv6ExtensionHeaderData};
16use packet_formats::ipv6::Ipv6Header as _;
17
18/// Informs the transport layer of parameters for transparent local delivery.
19#[derive(Debug, GenericOverIp, Clone)]
20#[generic_over_ip(I, Ip)]
21pub struct TransparentLocalDelivery<I: IpExt> {
22    /// The local delivery address.
23    pub addr: SpecifiedAddr<I::Addr>,
24    /// The local delivery port.
25    pub port: NonZeroU16,
26}
27
28/// Meta information for an incoming packet.
29#[derive(Debug, GenericOverIp, Clone)]
30#[generic_over_ip(I, Ip)]
31pub struct ReceiveIpPacketMeta<I: IpExt> {
32    /// Indicates that the packet was sent to a broadcast address.
33    pub broadcast: Option<I::BroadcastMarker>,
34
35    /// Destination overrides for the transparent proxy.
36    pub transparent_override: Option<TransparentLocalDelivery<I>>,
37}
38
39/// Information for an incoming packet.
40///
41/// This is given to upper layers to provide extra information on locally
42/// delivered IP packets.
43#[derive(Debug, Clone)]
44pub struct LocalDeliveryPacketInfo<I: IpExt, H: IpHeaderInfo<I>> {
45    /// Packet metadata calculated by the stack.
46    pub meta: ReceiveIpPacketMeta<I>,
47    /// Accessor for extra information in IP header.
48    pub header_info: H,
49    /// The marks carried by the incoming packet.
50    pub marks: Marks,
51}
52
53/// Abstracts extracting information from IP headers for upper layers.
54///
55/// Implemented for the combination of fixed header and options of IPv4 and IPv6
56/// packets, so we can ensure this information is always extracted from packets,
57/// including when they're rewritten by filters.
58///
59/// This is a trait so:
60/// - We're gating here and acknowledging all the information necessary by upper
61///   layers.
62/// - A [fake implementation] can be provided without constructing a full
63///   IPv4/IPv6 packet.
64///
65/// [fake implementation]: testutil::FakeIpHeaderInfo
66pub trait IpHeaderInfo<I> {
67    /// DSCP and ECN values received in Traffic Class or TOS field.
68    fn dscp_and_ecn(&self) -> DscpAndEcn;
69
70    /// The TTL (IPv4) or Hop Limit (IPv6) of the received packet.
71    fn hop_limit(&self) -> u8;
72
73    /// Returns true if the router alert option (IPv4) or extension header
74    /// (IPv6) is present on the packet.
75    fn router_alert(&self) -> bool;
76}
77
78pub(crate) struct Ipv4HeaderInfo<'a> {
79    pub(crate) prefix: &'a packet_formats::ipv4::HeaderPrefix,
80    pub(crate) options: packet_formats::ipv4::Options<&'a [u8]>,
81}
82
83impl IpHeaderInfo<Ipv4> for Ipv4HeaderInfo<'_> {
84    fn dscp_and_ecn(&self) -> DscpAndEcn {
85        self.prefix.dscp_and_ecn()
86    }
87
88    fn hop_limit(&self) -> u8 {
89        self.prefix.ttl()
90    }
91
92    fn router_alert(&self) -> bool {
93        self.options.iter().any(|opt| matches!(opt, Ipv4Option::RouterAlert { .. }))
94    }
95}
96
97pub(crate) struct Ipv6HeaderInfo<'a> {
98    pub(crate) fixed: &'a packet_formats::ipv6::FixedHeader,
99    pub(crate) extension: packet_formats::ipv6::ExtensionHeaders<'a>,
100}
101
102impl IpHeaderInfo<Ipv6> for Ipv6HeaderInfo<'_> {
103    fn dscp_and_ecn(&self) -> DscpAndEcn {
104        self.fixed.dscp_and_ecn()
105    }
106
107    fn hop_limit(&self) -> u8 {
108        self.fixed.hop_limit()
109    }
110
111    fn router_alert(&self) -> bool {
112        self.extension.iter().any(|h| match h.data() {
113            Ipv6ExtensionHeaderData::HopByHopOptions { options } => {
114                options.iter().any(|h| matches!(h.data, HopByHopOptionData::RouterAlert { .. }))
115            }
116            _ => false,
117        })
118    }
119}
120
121#[cfg(any(test, feature = "testutils"))]
122pub(crate) mod testutil {
123    use super::*;
124
125    /// Handroll a default impl for `ReceiveIpPacketMeta` only for tests to
126    /// prevent accidental usage.
127    impl<I: IpExt> Default for ReceiveIpPacketMeta<I> {
128        fn default() -> Self {
129            Self { broadcast: None, transparent_override: None }
130        }
131    }
132
133    impl<I: IpExt> Default for LocalDeliveryPacketInfo<I, FakeIpHeaderInfo> {
134        fn default() -> Self {
135            Self {
136                meta: Default::default(),
137                header_info: Default::default(),
138                marks: Default::default(),
139            }
140        }
141    }
142
143    /// A fake implementation of [`IpHeaderInfo`].
144    #[derive(Debug, Default)]
145    pub struct FakeIpHeaderInfo {
146        /// The value returned by [`IpHeaderInfo::dscp_and_ecn`].
147        pub dscp_and_ecn: DscpAndEcn,
148        /// The value returned by [`IpHeaderInfo::hop_limit`].
149        pub hop_limit: u8,
150        /// The value returned by [`IpHeaderInfo::router_alert`].
151        pub router_alert: bool,
152    }
153
154    impl<I: IpExt> IpHeaderInfo<I> for FakeIpHeaderInfo {
155        fn dscp_and_ecn(&self) -> DscpAndEcn {
156            self.dscp_and_ecn
157        }
158
159        fn hop_limit(&self) -> u8 {
160            self.hop_limit
161        }
162
163        fn router_alert(&self) -> bool {
164            self.router_alert
165        }
166    }
167}