Skip to content

Commit

Permalink
Clean up routes module
Browse files Browse the repository at this point in the history
Replace update with get_ref/get_mut, add get_default_ipv4_route and get_default_ipv6_routes
  • Loading branch information
jD91mZM2 committed Jun 19, 2018
1 parent d23aee4 commit f659156
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions src/iface/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,13 @@ impl<'a> Routes<'a> {
Routes { storage }
}

/// Update the routes of this node.
pub fn update<F: FnOnce(&mut ManagedMap<'a, IpCidr, Route>)>(&mut self, f: F) {
f(&mut self.storage);
/// Return a reference to the inner map
pub fn get_ref(&mut self) -> &ManagedMap<'a, IpCidr, Route> {
&self.storage
}
/// Return a mutable reference to the inner map
pub fn get_mut(&mut self) -> &mut ManagedMap<'a, IpCidr, Route> {
&mut self.storage
}

/// Add a default ipv4 gateway (ie. "ip route add 0.0.0.0/0 via `gateway`").
Expand All @@ -92,6 +96,13 @@ impl<'a> Routes<'a> {
}
}

/// Get the current default ipv4 gateway, if any
#[cfg(feature = "proto-ipv4")]
pub fn get_default_ipv4_route(&mut self) -> Option<&Route> {
let cidr = IpCidr::new(IpAddress::v4(0, 0, 0, 0), 0);
self.storage.get(&cidr)
}

/// Add a default ipv6 gateway (ie. "ip -6 route add ::/0 via `gateway`").
///
/// On success, returns the previous default route, if any.
Expand All @@ -105,6 +116,14 @@ impl<'a> Routes<'a> {
}
}

/// Get the current default ipv6 gateways, if any
#[cfg(feature = "proto-ipv6")]
pub fn get_default_ipv6_routes(&mut self) -> impl Iterator<Item = &Route> {
let cidr = IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 0), 0);
// TODO: Support multiple default ipv6 gateways
self.storage.get(&cidr).into_iter()
}

pub(crate) fn lookup(&self, addr: &IpAddress, timestamp: Instant) ->
Option<IpAddress> {
assert!(addr.is_unicast());
Expand Down Expand Up @@ -195,9 +214,7 @@ mod test {
via_router: ADDR_1A.into(),
preferred_until: None, expires_at: None,
};
routes.update(|storage| {
storage.insert(cidr_1().into(), route).unwrap();
});
routes.get_mut().insert(cidr_1().into(), route).unwrap();

assert_eq!(routes.lookup(&ADDR_1A.into(), Instant::from_millis(0)), Some(ADDR_1A.into()));
assert_eq!(routes.lookup(&ADDR_1B.into(), Instant::from_millis(0)), Some(ADDR_1A.into()));
Expand All @@ -210,9 +227,7 @@ mod test {
preferred_until: Some(Instant::from_millis(10)),
expires_at: Some(Instant::from_millis(10)),
};
routes.update(|storage| {
storage.insert(cidr_2().into(), route2).unwrap();
});
routes.get_mut().insert(cidr_2().into(), route2).unwrap();

assert_eq!(routes.lookup(&ADDR_1A.into(), Instant::from_millis(0)), Some(ADDR_1A.into()));
assert_eq!(routes.lookup(&ADDR_1B.into(), Instant::from_millis(0)), Some(ADDR_1A.into()));
Expand Down

0 comments on commit f659156

Please sign in to comment.