Skip to content

Commit

Permalink
Replace assert with Result. Re: rust-netlink#16
Browse files Browse the repository at this point in the history
Rather than panicking the calling application when the message Kind has
already been set, return Err(Error::InvalidNla).

Note: This adds the error type: Error::InvalidNla

Signed-off-by: Erich Heine <[email protected]>
  • Loading branch information
Erich Heine committed Apr 14, 2023
1 parent 25f0353 commit e9bca14
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
3 changes: 3 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,7 @@ pub enum Error {

#[error("Failed to parse a network address (IP and mask): {0:?}/{1:?}")]
InvalidAddress(Vec<u8>, Vec<u8>),

#[error("Attempting to set and Invalid NLA: {0}")]
InvalidNla(String),
}
27 changes: 22 additions & 5 deletions src/traffic_control/add_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,27 +110,32 @@ impl TrafficFilterNewRequest {

/// The 32bit filter allows to match arbitrary bitfields in the packet.
/// Equivalent to `tc filter ... u32`.
pub fn u32(mut self, data: Vec<tc::u32::Nla>) -> Self {
assert!(!self
pub fn u32(mut self, data: Vec<tc::u32::Nla>) -> Result<Self, Error> {
if self
.message
.nlas
.iter()
.any(|nla| matches!(nla, tc::Nla::Kind(_))));
.any(|nla| matches!(nla, tc::Nla::Kind(_)))
{
return Err(Error::InvalidNla(
"message kind has already been set.".to_string(),
));
}
self.message
.nlas
.push(tc::Nla::Kind(tc::u32::KIND.to_string()));
self.message.nlas.push(tc::Nla::Options(
data.into_iter().map(tc::TcOpt::U32).collect(),
));
self
Ok(self)
}

/// Use u32 to implement traffic redirect.
/// Equivalent to
/// `tc filter add [dev source] [parent ffff:] [protocol all] u32 match u8 0
/// 0 action mirred egress redirect dev dest` You need to set the
/// `parent` and `protocol` before call redirect.
pub fn redirect(self, dst_index: u32) -> Self {
pub fn redirect(self, dst_index: u32) -> Result<Self, Error> {
let mut sel_na = tc::u32::Sel::default();
sel_na.flags = TC_U32_TERMINAL;
sel_na.nkeys = 1;
Expand Down Expand Up @@ -267,10 +272,22 @@ mod test {
.parent(0xffff0000)
.protocol(0x0003)
.redirect(test2.header.index)
.unwrap()
.execute()
.await
.unwrap();

// Verify that attempting to set 2 redirects causes and error
assert!(handle
.traffic_filter(test1.header.index as i32)
.add()
.parent(0xffff0000)
.protocol(0x0003)
.redirect(test2.header.index)
.unwrap()
.redirect(test1.header.index)
.is_err());

let mut filters_iter = handle
.traffic_filter(test1.header.index as i32)
.get()
Expand Down

0 comments on commit e9bca14

Please sign in to comment.