From a2d25820985b04f15f3c0f38cabfd7130124d943 Mon Sep 17 00:00:00 2001 From: darkgallium Date: Fri, 22 May 2020 18:51:46 +0200 Subject: add better error handling --- src/fw.rs | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/src/fw.rs b/src/fw.rs index 07282af..7650b3a 100644 --- a/src/fw.rs +++ b/src/fw.rs @@ -1,6 +1,8 @@ use iptables; use regex::Regex; use std::collections::HashSet; +use std::io; + #[derive(PartialEq,Eq,Debug,Hash)] pub struct Port { @@ -8,22 +10,35 @@ pub struct Port { number: u16, } -pub fn setup(ipt: &iptables::IPTables) { - ipt.new_chain("filter", "DIPLONAT").unwrap(); - ipt.insert("filter", "INPUT", "-j DIPLONAT", 1).unwrap(); +#[derive(Debug)] +pub struct FirewallError(String); + +impl From for FirewallError { + fn from(error: iptables::error::IPTError) -> Self { + FirewallError(error.to_string()) + } + } -pub fn open_ports(ipt: &iptables::IPTables, ports: Vec) { +pub fn setup(ipt: &iptables::IPTables) -> Result<(), FirewallError> { + ipt.new_chain("filter", "DIPLONAT")?; + ipt.insert("filter", "INPUT", "-j DIPLONAT", 1)?; + Ok(()) +} + +pub fn open_ports(ipt: &iptables::IPTables, ports: Vec) -> Result<(), FirewallError> { for p in ports { - ipt.append("filter", "DIPLONAT", &format!("-p {} --dport {} -j ACCEPT", p.proto, p.number)).unwrap(); + ipt.append("filter", "DIPLONAT", &format!("-p {} --dport {} -j ACCEPT", p.proto, p.number))?; } + + Ok(()) } -pub fn get_opened_ports(ipt: &iptables::IPTables) -> HashSet { +pub fn get_opened_ports(ipt: &iptables::IPTables) -> Result, FirewallError> { let mut opened_ports: HashSet = HashSet::new(); - let list = ipt.list("filter", "DIPLONAT").unwrap(); + let list = ipt.list("filter", "DIPLONAT")?; let re = Regex::new(r"\-A.*? \-p (\w+).*\-\-dport (\d+).*?\-j ACCEPT").unwrap(); for i in list { let caps = re.captures(&i); @@ -41,13 +56,14 @@ pub fn get_opened_ports(ipt: &iptables::IPTables) -> HashSet { } } - opened_ports + Ok(opened_ports) } -pub fn cleanup(ipt: &iptables::IPTables) { - ipt.flush_chain("filter", "DIPLONAT").unwrap(); - ipt.delete("filter", "INPUT", "-j DIPLONAT").unwrap(); - ipt.delete_chain("filter", "DIPLONAT").unwrap(); +pub fn cleanup(ipt: &iptables::IPTables) -> Result<(), FirewallError> { + ipt.flush_chain("filter", "DIPLONAT")?; + ipt.delete("filter", "INPUT", "-j DIPLONAT")?; + ipt.delete_chain("filter", "DIPLONAT")?; + Ok(()) } /* -- cgit v1.2.3