From 28dbf92ab0c9eaf923c0e83ba7c3127113d1e7a0 Mon Sep 17 00:00:00 2001 From: zyj Date: Wed, 27 Dec 2023 10:02:11 +0800 Subject: [PATCH] replace failure with thiserror --- CHANGELOG.md | 17 +++++++----- Cargo.lock | 73 ++++++++------------------------------------------ Cargo.toml | 4 +-- src/config.rs | 53 +++++++++++++++++++++--------------- src/domain.rs | 5 ++-- src/handler.rs | 5 ++-- src/main.rs | 29 ++++++-------------- 7 files changed, 67 insertions(+), 119 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d164eb3..f164c0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,21 +1,24 @@ +# 0.3.7 + +- replace failure with thiserror + # 0.3.5 -* update trust dns to hickory dns +- update trust dns to hickory dns # 0.3.1 -* Optimize memory usage +- Optimize memory usage # 0.2.0 -* add response soa record -* fix bugs +- add response soa record +- fix bugs # 0.1.1 -* fix mips build error +- fix mips build error # 0.1.0 -* First version - +- First version diff --git a/Cargo.lock b/Cargo.lock index ae5855a..3685aa1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,7 +82,7 @@ checksum = "5fd55a5ba1179988837d24ab4c7cc8ed6efdeff578ede0416b4225a5fca35bd0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -93,7 +93,7 @@ checksum = "fdf6721fb0140e4f897002dd086c06f6c27775df19cfe1fccb21181a48fd2c98" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -198,7 +198,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -277,7 +277,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -286,28 +286,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" -[[package]] -name = "failure" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" -dependencies = [ - "backtrace", - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "synstructure", -] - [[package]] name = "fnv" version = "1.0.7" @@ -740,7 +718,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -1027,7 +1005,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -1107,17 +1085,6 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - [[package]] name = "syn" version = "2.0.43" @@ -1129,18 +1096,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "unicode-xid", -] - [[package]] name = "take_mut" version = "0.2.2" @@ -1175,7 +1130,7 @@ checksum = "e7fbe9b594d6568a6a1443250a7e67d80b74e1e96f6d1715e1e21cc1888291d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -1259,7 +1214,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -1351,7 +1306,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn", ] [[package]] @@ -1384,12 +1339,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-xid" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" - [[package]] name = "untrusted" version = "0.9.0" @@ -1590,12 +1539,11 @@ dependencies = [ [[package]] name = "yadns" -version = "0.3.5" +version = "0.3.7" dependencies = [ "async-recursion", "async-trait", "clap", - "failure", "futures", "hickory-proto", "hickory-resolver", @@ -1611,6 +1559,7 @@ dependencies = [ "slog", "slog-async", "slog-term", + "thiserror", "tokio", "toml", ] diff --git a/Cargo.toml b/Cargo.toml index 277100c..a80bbcd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yadns" -version = "0.3.5" +version = "0.3.7" authors = ["zyj"] edition = "2021" @@ -18,7 +18,6 @@ dns-over-https = ["hickory-resolver"] async-recursion = "1" async-trait = "0.1" clap = { version = "4", features = ["derive"] } -failure = "0.1" futures = { version = "0.3", default-features = false } hickory-proto = "0.24" hickory-resolver = { version = "0.24", default-features = false, features = ["tokio-runtime"] } @@ -33,6 +32,7 @@ serde_derive = "1" slog = "2" slog-async = "2" slog-term = "2" +thiserror = "1" tokio = "1" toml = "0.8" diff --git a/src/config.rs b/src/config.rs index 3509424..dc69bee 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,6 @@ use crate::ip::IpRange; -use failure::{err_msg, Error}; use hickory_proto::rr::RecordType; +use ipnet::AddrParseError; use ipnet::IpNet; use serde_derive::Deserialize; use std::collections::HashMap; @@ -10,6 +10,17 @@ use std::io::BufReader; use std::net::IpAddr; use std::net::SocketAddr; use std::str::FromStr; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum ConfigError { + #[error("You must configure at least one default upstream server!")] + NoUpstream, + #[error("Invalid address: {0}")] + InvalidAddress(String), + #[error("tls-host is missing")] + NoTlsHost, +} #[derive(Debug)] pub struct Config { @@ -53,7 +64,7 @@ pub enum Upstream { } impl ConfigBuilder { - pub fn build(self) -> Result { + pub fn build(self) -> Result { let mut default_upstreams = Vec::new(); let upstreams = self @@ -65,12 +76,10 @@ impl ConfigBuilder { } upstream.build().map(move |upstream| (key, upstream)) }) - .collect::, Error>>()?; + .collect::, ConfigError>>()?; if default_upstreams.is_empty() { - return Err(err_msg( - "You must configure at least one default upstream server!", - )); + return Err(ConfigError::NoUpstream); } let domains = self @@ -78,7 +87,7 @@ impl ConfigBuilder { .unwrap_or_default() .into_iter() .map(|(key, domains)| domains.build().map(move |domains| (key, domains))) - .collect::, Error>>()?; + .collect::, ConfigError>>()?; let ranges = self .ranges @@ -88,14 +97,15 @@ impl ConfigBuilder { let mut range = IpRange::new(); conf.read_to(&mut range).map(|()| (key, range)) }) - .collect::, Error>>()?; + .collect::, AddrParseError>>() + .unwrap(); let request_rules: Vec = self .requests .unwrap_or_default() .into_iter() .map(|r| r.build()) - .collect::, Error>>()?; + .collect::, ConfigError>>()?; Ok(Config { bind: self.bind, @@ -125,7 +135,7 @@ impl UpstreamConfig { true } - fn build(self) -> Result { + fn build(self) -> Result { let mut address = self.address.parse::(); if let Err(_) = address { address = self @@ -133,18 +143,18 @@ impl UpstreamConfig { .parse::() .map(|addr| SocketAddr::new(addr, self.network.default_port())); } - let address = address.map_err(|_| err_msg(format!("Invalid address: {}", self.address)))?; + let address = address.map_err(|_| ConfigError::InvalidAddress(self.address))?; match self.network { NetworkType::Tcp => Ok(Upstream::TcpUpstream { address }), NetworkType::Udp => Ok(Upstream::UdpUpstream { address }), #[cfg(feature = "dns-over-tls")] NetworkType::Tls => { - let tls_host = self.tls_host.ok_or(err_msg("tls-host is missing"))?; + let tls_host = self.tls_host.ok_or(ConfigError::NoTlsHost)?; Ok(Upstream::TlsUpstream { address, tls_host }) } #[cfg(feature = "dns-over-https")] NetworkType::Https => { - let tls_host = self.tls_host.ok_or(err_msg("tls-host is missing"))?; + let tls_host = self.tls_host.ok_or(ConfigError::NoTlsHost)?; Ok(Upstream::HttpsUpstream { address, tls_host }) } } @@ -184,13 +194,13 @@ struct IpRangeConf { } impl IpRangeConf { - fn read_to(&self, range: &mut IpRange) -> Result<(), Error> { + fn read_to(&self, range: &mut IpRange) -> Result<(), AddrParseError> { if let Some(files) = &self.files { for file in files { - let file = File::open(file)?; + let file = File::open(file).unwrap(); let reader = BufReader::new(file); for line in reader.lines() { - let line = line?; + let line = line.unwrap(); let line = line.trim(); if line.is_empty() || line.starts_with("#") { continue; @@ -226,7 +236,7 @@ struct DomainsConf { } impl DomainsConf { - fn build(self) -> Result { + fn build(self) -> Result { let mut regex_set = Vec::new(); let mut suffix_set = Vec::new(); suffix_set.push(String::from("// BEGIN ICANN DOMAINS")); @@ -246,10 +256,10 @@ impl DomainsConf { if let Some(files) = &self.files { for file in files { - let file = File::open(file)?; + let file = File::open(file).unwrap(); let reader = BufReader::new(file); for line in reader.lines() { - let line = line?; + let line = line.unwrap(); let line = line.trim(); push(line); } @@ -277,12 +287,13 @@ struct RequestRuleConfig { } impl RequestRuleConfig { - fn build(self) -> Result { + fn build(self) -> Result { let types = Transpose::transpose(self.types.map(|v| { v.iter() .map(|t| RecordType::from_str(t)) .collect::, _>>() - }))?; + })) + .unwrap(); Ok(RequestRule { domains: self.domains, diff --git a/src/domain.rs b/src/domain.rs index 5e6d7c8..0ee3d39 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -1,6 +1,5 @@ -use failure::Error; use publicsuffix::{List, Psl}; -use std::str::FromStr; +use std::{io, str::FromStr}; #[derive(Clone, Debug)] pub struct DomainSuffix { @@ -15,7 +14,7 @@ impl DomainSuffix { } impl FromStr for DomainSuffix { - type Err = Error; + type Err = io::Error; fn from_str(s: &str) -> Result { let list = match s.parse() { diff --git a/src/handler.rs b/src/handler.rs index 238d1b0..f7398d6 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -1,6 +1,5 @@ use crate::{config::RuleAction, filter, handler_config::HandlerConfig, logger::stderr}; use async_recursion::async_recursion; -use failure::Error; use futures::{ future::{self, MapErr, MapOk}, Future, FutureExt, TryFutureExt, @@ -48,7 +47,7 @@ impl Handler { &self, request: &Request, mut responder: R, - ) -> Result { + ) -> Result { //self.counter.fetch_add(1, Ordering::SeqCst); let resolvers = filter::resolvers(handler_config(), request.query()); let tasks: Vec<_> = resolvers @@ -154,7 +153,7 @@ impl Handler { &self, request: &Request, mut response: R, - ) -> Result { + ) -> Result { debug!( stderr(), "DNS requests are forwarded to [{}].", diff --git a/src/main.rs b/src/main.rs index b8a4935..7b8dcd7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,11 +2,10 @@ use crate::config::{Config, ConfigBuilder}; use crate::handler::Handler; use crate::logger::{stderr, stdout}; use clap::Parser; -use failure::Error; +use config::ConfigError; use hickory_server::ServerFuture; use option::Args; -use slog::{crit, debug, info}; -use std::fmt::Display; +use slog::{crit, info}; use std::fs::File; use std::io::prelude::*; use std::process::exit; @@ -41,14 +40,14 @@ async fn main() { server.block_until_done().await.unwrap(); } -fn config() -> Result { +fn config() -> Result { let args = Args::parse(); let config_path = args.config; - let mut file = File::open(config_path)?; + let mut file = File::open(config_path).unwrap(); let mut content = String::new(); - file.read_to_string(&mut content)?; + file.read_to_string(&mut content).unwrap(); - let builder: ConfigBuilder = toml::from_str(&content)?; + let builder: ConfigBuilder = toml::from_str(&content).unwrap(); builder.build() } @@ -56,30 +55,18 @@ trait ShouldSuccess { type Item; fn unwrap_or_log(self) -> Self::Item; - - fn unwrap_or_log_with(self, description: D) -> Self::Item; } impl ShouldSuccess for Result where - F: Into, + F: Into, { type Item = T; fn unwrap_or_log(self) -> T { self.unwrap_or_else(|e| { - let e: Error = e.into(); + let e: ConfigError = e.into(); crit!(stderr(), "{}", e); - debug!(stderr(), "{:?}", e.backtrace()); - exit(1); - }) - } - - fn unwrap_or_log_with(self, description: D) -> T { - self.unwrap_or_else(|e| { - let e: Error = e.into(); - crit!(stderr(), "{}: {}", description, e); - debug!(stderr(), "{:?}", e.backtrace()); exit(1); }) }