ipblc/src/utils.rs
Paul Lecuq 678f7e5060
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is failing
added feature to block after max tries for a set
misc:
* updated tests
* updated dependencies
2022-08-28 17:32:23 +02:00

82 lines
2.1 KiB
Rust

use ipnet::IpNet;
use lazy_static::lazy_static;
use nix::unistd;
use regex::Regex;
use std::boxed::Box;
use std::fs::File;
use std::io::*;
use std::path::Path;
use std::time::Duration;
lazy_static! {
static ref R_FILE_GZIP: Regex = Regex::new(r".*\.gz.*").unwrap();
}
pub fn read_lines(filename: &String, offset: u64) -> Option<Box<dyn Read>> {
let mut file = match File::open(filename) {
Ok(f) => f,
Err(err) => {
println!("{err}");
return None;
}
};
file.seek(SeekFrom::Start(offset)).unwrap();
let lines: Box<dyn Read> = Box::new(BufReader::new(file));
Some(lines)
}
pub fn _dedup<T: Ord + PartialOrd>(list: &mut Vec<T>) -> usize {
// Begin with sorting entries
list.sort();
// Then deduplicate
list.dedup();
// Return the length
list.len()
}
pub fn build_trustnets(cfgtrustnets: &Vec<String>) -> Vec<IpNet> {
let mut trustnets: Vec<IpNet> = vec![];
for trustnet in cfgtrustnets {
match trustnet.parse() {
Ok(net) => trustnets.push(net),
Err(err) => {
println!("error parsing {trustnet}, error: {err}");
}
};
}
trustnets
}
pub fn sleep(seconds: u64) {
std::thread::sleep(Duration::from_secs(seconds));
}
pub fn gethostname(show_fqdn: bool) -> String {
let hostname_cstr = unistd::gethostname().expect("Failed getting hostname");
let fqdn = hostname_cstr
.to_str()
.expect("Hostname wasn't valid UTF-8")
.to_string();
let hostname: Vec<&str> = fqdn.split(".").collect();
if show_fqdn {
return fqdn;
}
hostname[0].to_string()
}
pub fn _search_subfolders(path: &Path) -> Vec<String> {
let dirs = std::fs::read_dir(path).unwrap();
let mut folders: Vec<String> = vec![];
for dir in dirs {
let dirpath = dir.unwrap().path();
let path = Path::new(dirpath.as_path());
if path.is_dir() {
folders.push(dirpath.to_str().unwrap().to_string());
for f in _search_subfolders(path) {
folders.push(f);
}
}
}
folders
}