Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 74 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ members = [
"clash",
"clash_lib",
"clash_doc",
"crates/stack-error-macro",
"crates/stack-error",
"clash_ffi",
]

Expand Down
5 changes: 5 additions & 0 deletions clash_lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ zero_copy = []
tokio-console = ["tokio/tracing"]

[dependencies]

stack-error-macro = { path = "../crates/stack-error-macro" }
stack-error = { path = "../crates/stack-error" }
snafu = "0.8"

# Async
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.7", features = ["net", "codec", "io", "compat"] }
Expand Down
6 changes: 3 additions & 3 deletions clash_lib/src/app/dns/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl Config {

pub fn parse_fallback_ip_cidr(
ipcidr: &[String],
) -> anyhow::Result<Vec<ipnet::IpNet>> {
) -> std::result::Result<Vec<ipnet::IpNet>, crate::Error> {
let mut output = vec![];

for ip in ipcidr.iter() {
Expand All @@ -164,15 +164,15 @@ impl Config {

pub fn parse_hosts(
hosts_mapping: &HashMap<String, String>,
) -> anyhow::Result<trie::StringTrie<IpAddr>> {
) -> std::result::Result<trie::StringTrie<IpAddr>, crate::Error> {
let mut tree = trie::StringTrie::new();
tree.insert(
"localhost",
Arc::new("127.0.0.1".parse::<IpAddr>().unwrap()),
);

for (host, ip_str) in hosts_mapping.iter() {
let ip = ip_str.parse::<IpAddr>()?;
let ip = ip_str.parse::<IpAddr>().map_err(Error::StdNet)?;
tree.insert(host.as_str(), Arc::new(ip));
}

Expand Down
9 changes: 6 additions & 3 deletions clash_lib/src/app/dns/dhcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use crate::{
dns_client::DNSNetMode, helper::make_clients, Client, EnhancedResolver,
ThreadSafeDNSClient,
},
error::dns::{ClientTimeoutSnafu, IoSnafu},
proxy::utils::{new_udp_socket, Interface},
};
use async_trait::async_trait;
use dhcproto::{Decodable, Encodable};
use futures::FutureExt;
use network_interface::{Addr, NetworkInterfaceConfig};
use snafu::ResultExt;
use std::{
env,
fmt::{Debug, Formatter},
Expand Down Expand Up @@ -56,8 +58,8 @@ impl Client for DhcpClient {
format!("dhcp#{}", self.iface)
}

async fn exchange(&self, msg: &Message) -> anyhow::Result<Message> {
let clients = self.resolve().await?;
async fn exchange(&self, msg: &Message) -> crate::error::DnsResult<Message> {
let clients = self.resolve().await.context(IoSnafu)?;
let mut dbg_str = vec![];
for c in &clients {
dbg_str.push(format!("{:?}", c));
Expand All @@ -67,7 +69,8 @@ impl Client for DhcpClient {
DHCP_TIMEOUT,
EnhancedResolver::batch_exchange(&clients, msg),
)
.await?
.await
.context(ClientTimeoutSnafu)?
}
}

Expand Down
16 changes: 9 additions & 7 deletions clash_lib/src/app/dns/dns_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ use hickory_proto::{
udp::UdpClientStream, ProtoError,
};
use rustls::ClientConfig;
use snafu::ResultExt;
use tokio::{sync::RwLock, task::JoinHandle};
use tracing::{info, warn};

use crate::{
common::tls::{self, GLOBAL_ROOT_STORE},
dns::{dhcp::DhcpClient, ThreadSafeDNSClient},
error::dns::ProtoSnafu,
proxy::utils::new_tcp_stream,
};
use hickory_proto::{
Expand Down Expand Up @@ -277,7 +279,7 @@ impl Client for DnsClient {
format!("{}#{}:{}", &self.net, &self.host, &self.port)
}

async fn exchange(&self, msg: &Message) -> anyhow::Result<Message> {
async fn exchange(&self, msg: &Message) -> crate::error::DnsResult<Message> {
let mut inner = self.inner.write().await;

if let Some(bg) = &inner.bg_handle {
Expand Down Expand Up @@ -309,14 +311,14 @@ impl Client for DnsClient {
.send(req)
.first_answer()
.await
.map_err(|x| Error::DNSError(x.to_string()).into())
.context(ProtoSnafu)
.map(|x| x.into())
}
}

async fn dns_stream_builder(
cfg: &DnsConfig,
) -> Result<(client::Client, JoinHandle<Result<(), ProtoError>>), Error> {
) -> crate::error::DnsResult<(client::Client, JoinHandle<Result<(), ProtoError>>)> {
match cfg {
DnsConfig::Udp(addr, iface) => {
let stream = UdpClientStream::builder(
Expand All @@ -329,7 +331,7 @@ async fn dns_stream_builder(
client::Client::connect(stream)
.await
.map(|(x, y)| (x, tokio::spawn(y)))
.map_err(|x| Error::DNSError(x.to_string()))
.context(ProtoSnafu)
}
DnsConfig::Tcp(addr, iface) => {
let (stream, sender) = TcpClientStream::new(
Expand All @@ -342,7 +344,7 @@ async fn dns_stream_builder(
client::Client::new(stream, sender, None)
.await
.map(|(x, y)| (x, tokio::spawn(y)))
.map_err(|x| Error::DNSError(x.to_string()))
.context(ProtoSnafu)
}
DnsConfig::Tls(addr, host, iface) => {
let mut tls_config = ClientConfig::builder()
Expand Down Expand Up @@ -379,7 +381,7 @@ async fn dns_stream_builder(
)
.await
.map(|(x, y)| (x, tokio::spawn(y)))
.map_err(|x| Error::DNSError(x.to_string()))
.context(ProtoSnafu)
}
DnsConfig::Https(addr, host, iface) => {
let mut tls_config = ClientConfig::builder()
Expand All @@ -402,7 +404,7 @@ async fn dns_stream_builder(
client::Client::connect(stream)
.await
.map(|(x, y)| (x, tokio::spawn(y)))
.map_err(|x| Error::DNSError(x.to_string()))
.context(ProtoSnafu)
}
}
}
16 changes: 11 additions & 5 deletions clash_lib/src/app/dns/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ pub use server::get_dns_listener;
pub trait Client: Sync + Send + Debug {
/// used to identify the client for logging
fn id(&self) -> String;
async fn exchange(&self, msg: &op::Message) -> anyhow::Result<op::Message>;
async fn exchange(
&self,
msg: &op::Message,
) -> crate::error::DnsResult<op::Message>;
}

type ThreadSafeDNSClient = Arc<dyn Client>;
Expand All @@ -51,22 +54,25 @@ pub trait ClashResolver: Sync + Send {
&self,
host: &str,
enhanced: bool,
) -> anyhow::Result<Option<std::net::IpAddr>>;
) -> std::result::Result<Option<std::net::IpAddr>, crate::error::DnsError>;
async fn resolve_v4(
&self,
host: &str,
enhanced: bool,
) -> anyhow::Result<Option<std::net::Ipv4Addr>>;
) -> std::result::Result<Option<std::net::Ipv4Addr>, crate::error::DnsError>;
async fn resolve_v6(
&self,
host: &str,
enhanced: bool,
) -> anyhow::Result<Option<std::net::Ipv6Addr>>;
) -> std::result::Result<Option<std::net::Ipv6Addr>, crate::error::DnsError>;

async fn cached_for(&self, ip: std::net::IpAddr) -> Option<String>;

/// Used for DNS Server
async fn exchange(&self, message: &op::Message) -> anyhow::Result<op::Message>;
async fn exchange(
&self,
message: &op::Message,
) -> std::result::Result<op::Message, crate::error::DnsError>;

/// Only used for look up fake IP
async fn reverse_lookup(&self, ip: std::net::IpAddr) -> Option<String>;
Expand Down
Loading
Loading