Skip to content

Commit

Permalink
Define iptables error
Browse files Browse the repository at this point in the history
  • Loading branch information
yaa110 committed Dec 28, 2020
1 parent 1458e1b commit 8b59aba
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "iptables"
version = "0.4.0"
version = "0.4.1"
authors = ["Navid Fathollahzade <[email protected]>", "Pit Kleyersburg <[email protected]>"]
edition = "2018"
description = "Rust bindings for iptables"
Expand Down
27 changes: 27 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::convert::From;
use std::error::Error;
use std::fmt;
use std::process::Output;

#[derive(Debug)]
pub struct IptablesError {
pub code: i32,
pub msg: String,
}

impl fmt::Display for IptablesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "code: {}, msg: {}", self.code, self.msg)
}
}

impl From<Output> for IptablesError {
fn from(output: Output) -> Self {
Self {
code: output.status.code().unwrap_or(-1),
msg: String::from_utf8_lossy(output.stderr.as_slice()).into(),
}
}
}

impl Error for IptablesError {}
11 changes: 5 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
//! assert!(ipt.delete_chain("nat", "NEWCHAINNAME").is_ok());
//! ```
pub mod error;

use error::IptablesError;
use lazy_static::lazy_static;
use nix::fcntl::{flock, FlockArg};
use regex::{Match, Regex};
use std::convert::From;
use std::error::Error;
use std::ffi::OsStr;
use std::fs::File;
Expand Down Expand Up @@ -60,12 +64,7 @@ fn error_from_str(msg: &str) -> Box<dyn Error> {

fn output_to_result(output: Output) -> Result<(), Box<dyn Error>> {
if !output.status.success() {
let msg = format!(
"iptables returned non-zero status code: {} - {}",
output.status.code().unwrap_or(-1),
String::from_utf8_lossy(output.stderr.as_slice()),
);
return Err(error_from_str(msg.as_str()));
return Err(Box::new(IptablesError::from(output)));
}
Ok(())
}
Expand Down

0 comments on commit 8b59aba

Please sign in to comment.