Skip to main content

routes_common/
common.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
5use fidl::endpoints::ProtocolMarker;
6use fidl_fuchsia_net_interfaces_ext as fnet_interfaces_ext;
7use fidl_fuchsia_net_matchers_ext as fnet_matchers_ext;
8use fidl_fuchsia_net_routes as fnet_routes;
9use fidl_fuchsia_net_routes_ext::admin::FidlRouteAdminIpExt;
10use fidl_fuchsia_net_routes_ext::rules::{FidlRuleAdminIpExt, RuleIndex};
11use fidl_fuchsia_net_routes_ext::{self as fnet_routes_ext, FidlRouteIpExt};
12use net_types::SpecifiedAddr;
13use net_types::ip::Ip;
14use netstack_testing_common::realms::{Netstack3, TestSandboxExt as _};
15
16/// Common test setup that can be shared by all routes tests.
17pub struct TestSetup<'a, I: Ip + FidlRouteIpExt + FidlRouteAdminIpExt> {
18    pub realm: netemul::TestRealm<'a>,
19    pub network: netemul::TestNetwork<'a>,
20    pub interface: netemul::TestInterface<'a>,
21    pub route_table: <I::RouteTableMarker as ProtocolMarker>::Proxy,
22    pub global_route_table: <I::GlobalRouteTableMarker as ProtocolMarker>::Proxy,
23    pub state: <I::StateMarker as ProtocolMarker>::Proxy,
24}
25
26impl<'a, I: Ip + FidlRouteIpExt + FidlRouteAdminIpExt> TestSetup<'a, I> {
27    /// Creates a new test setup.
28    pub async fn new(sandbox: &'a netemul::TestSandbox, name: &str) -> TestSetup<'a, I> {
29        let realm = sandbox
30            .create_netstack_realm::<Netstack3, _>(format!("routes-admin-{name}"))
31            .expect("create realm");
32        let network =
33            sandbox.create_network(format!("routes-admin-{name}")).await.expect("create network");
34        let interface = realm.join_network(&network, "ep1").await.expect("join network");
35        let route_table = realm
36            .connect_to_protocol::<I::RouteTableMarker>()
37            .expect("connect to routes-admin RouteTable");
38        let global_route_table = realm
39            .connect_to_protocol::<I::GlobalRouteTableMarker>()
40            .expect("connect to global route set provider");
41
42        let state = realm.connect_to_protocol::<I::StateMarker>().expect("connect to routes State");
43        TestSetup { realm, network, interface, route_table, global_route_table, state }
44    }
45}
46
47/// A route for testing.
48pub fn test_route<I: Ip>(
49    interface: &netemul::TestInterface<'_>,
50    metric: fnet_routes::SpecifiedMetric,
51) -> fnet_routes_ext::Route<I> {
52    let destination = I::map_ip(
53        (),
54        |()| net_declare::net_subnet_v4!("192.0.2.0/24"),
55        |()| net_declare::net_subnet_v6!("2001:DB8::/64"),
56    );
57    let next_hop_addr = I::map_ip(
58        (),
59        |()| net_declare::net_ip_v4!("192.0.2.1"),
60        |()| net_declare::net_ip_v6!("2001:DB8::1"),
61    );
62
63    fnet_routes_ext::Route {
64        destination,
65        action: fnet_routes_ext::RouteAction::Forward(fnet_routes_ext::RouteTarget {
66            outbound_interface: interface.id(),
67            next_hop: Some(SpecifiedAddr::new(next_hop_addr).expect("is specified")),
68        }),
69        properties: fnet_routes_ext::RouteProperties {
70            specified_properties: fnet_routes_ext::SpecifiedRouteProperties { metric },
71        },
72    }
73}
74
75/// Possible mark matcher settings for a rule.
76pub enum MarkMatcher {
77    /// The matcher is not present, it does not match on the marks.
78    DontMatch,
79    /// The matcher only matches when the mark is not present.
80    MatchUnmarked,
81    /// The matcher only matches when the mark is set to the given number.
82    MatchMarked(u32),
83}
84
85impl From<MarkMatcher> for Option<fnet_matchers_ext::Mark> {
86    fn from(value: MarkMatcher) -> Self {
87        match value {
88            MarkMatcher::DontMatch => None,
89            MarkMatcher::MatchUnmarked => Some(fnet_matchers_ext::Mark::Unmarked),
90            MarkMatcher::MatchMarked(m) => {
91                Some(fnet_matchers_ext::Mark::Marked { mask: !0, between: m..=m, invert: false })
92            }
93        }
94    }
95}
96
97// Creates a new route table that has a default route using the given
98// `interface`; Also installs a rule that matches on the given `mark`
99// to lookup the created route table.
100pub async fn add_default_route_for_mark<
101    I: FidlRouteAdminIpExt + FidlRuleAdminIpExt + FidlRouteIpExt,
102>(
103    route_table_provider: &<I::RouteTableProviderMarker as ProtocolMarker>::Proxy,
104    rule_set: &<I::RuleSetMarker as ProtocolMarker>::Proxy,
105    interface: &netemul::TestInterface<'_>,
106    next_hop: Option<SpecifiedAddr<I::Addr>>,
107    index: u32,
108    mark_1: MarkMatcher,
109    mark_2: MarkMatcher,
110) -> <I::RouteSetMarker as ProtocolMarker>::Proxy {
111    let route_table = fnet_routes_ext::admin::new_route_table::<I>(route_table_provider, None)
112        .expect("new route table");
113    let route_set =
114        fnet_routes_ext::admin::new_route_set::<I>(&route_table).expect("new route set");
115    let route_to_add = fnet_routes_ext::Route {
116        destination: I::ALL_ADDRS_SUBNET,
117        action: fnet_routes_ext::RouteAction::Forward(fnet_routes_ext::RouteTarget::<I> {
118            outbound_interface: interface.id(),
119            next_hop,
120        }),
121        properties: fnet_routes_ext::RouteProperties {
122            specified_properties: fnet_routes_ext::SpecifiedRouteProperties {
123                metric: fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
124            },
125        },
126    };
127    let grant = interface.get_authorization().await.expect("getting grant should succeed");
128    let proof = fnet_interfaces_ext::admin::proof_from_grant(&grant);
129    fnet_routes_ext::admin::authenticate_for_interface::<I>(&route_set, proof)
130        .await
131        .expect("no FIDL error")
132        .expect("authentication should succeed");
133    assert!(
134        fnet_routes_ext::admin::add_route::<I>(
135            &route_set,
136            &route_to_add.try_into().expect("convert to FIDL")
137        )
138        .await
139        .expect("fidl")
140        .expect("add route")
141    );
142    fnet_routes_ext::admin::detach_route_table::<I>(&route_table).await.expect("fidl error");
143
144    let table_id =
145        fnet_routes_ext::admin::get_table_id::<I>(&route_table).await.expect("fidl error");
146
147    let auth = fnet_routes_ext::admin::get_authorization_for_route_table::<I>(&route_table)
148        .await
149        .expect("fidl error");
150    fnet_routes_ext::rules::authenticate_for_route_table::<I>(&rule_set, auth.table_id, auth.token)
151        .await
152        .expect("fidl error")
153        .expect("authentication error");
154    fnet_routes_ext::rules::add_rule::<I>(
155        &rule_set,
156        RuleIndex::new(index),
157        fnet_routes_ext::rules::RuleMatcher {
158            mark_1: mark_1.into(),
159            mark_2: mark_2.into(),
160            ..Default::default()
161        },
162        fnet_routes_ext::rules::RuleAction::Lookup(table_id),
163    )
164    .await
165    .expect("fidl")
166    .expect("add rule");
167
168    route_set
169}