Skip to content

Commit

Permalink
use async dns
Browse files Browse the repository at this point in the history
  • Loading branch information
lazytiger committed Nov 21, 2024
1 parent b4468b7 commit 140a9e0
Show file tree
Hide file tree
Showing 9 changed files with 151 additions and 30 deletions.
96 changes: 94 additions & 2 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ async_smoltcp = { path = "async_smoltcp" }
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] }
rustls-pki-types = "1.8"
futures = "0.3"
trust-dns-resolver = "0.23"

[dev-dependencies]
env_logger = "0.11"
Expand Down
25 changes: 9 additions & 16 deletions src/aproxy/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::{
net::{IpAddr, SocketAddr},
sync::{Arc, atomic::AtomicBool},
sync::{atomic::AtomicBool, Arc},
};

use rustls::{
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
ClientConfig,
crypto::ring::default_provider, DigitallySignedStruct, Error, RootCertStore, SignatureScheme,
crypto::ring::default_provider,
ClientConfig, DigitallySignedStruct, Error, RootCertStore, SignatureScheme,
};
use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
use tokio::{
Expand Down Expand Up @@ -191,12 +191,7 @@ pub async fn init_tls_conn(
connector: TlsConnector,
server_name: ServerName<'static>,
) -> types::Result<TlsStream<TcpStream>> {
let ips: Vec<_> = lookup_host((
OPTIONS.proxy_args().hostname.as_str(),
OPTIONS.proxy_args().port,
))
.await?
.collect();
let ip = OPTIONS.proxy_args().server_addr().await?;
#[cfg(target_os = "linux")]
{
let mut proxy_data = OPTIONS
Expand All @@ -206,16 +201,14 @@ pub async fn init_tls_conn(
.unwrap()
.lock()
.await;
for ip in &ips {
if !proxy_data.server_ips.contains(&ip.ip()) {
proxy_data.server_ips.push(ip.ip());
if let Err(err) = proxy_data.bypass_session.add(ip.ip(), vec![]) {
log::error!("add ip:{} to session failed:{}", ip, err);
}
if !proxy_data.server_ips.contains(&ip.ip()) {
proxy_data.server_ips.push(ip.ip());
if let Err(err) = proxy_data.bypass_session.add(ip.ip(), vec![]) {
log::error!("add ip:{} to session failed:{}", ip, err);
}
}
}
let stream = tokio::net::TcpStream::connect(ips.as_slice()).await?;
let stream = tokio::net::TcpStream::connect(ip).await?;
let conn = connector.connect(server_name, stream).await?;
Ok(conn)
}
6 changes: 3 additions & 3 deletions src/aproxy/profiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ use bytes::{Buf, BufMut, BytesMut};
use itertools::Itertools;
use rand::random;
use ringbuf::{
HeapRb,
traits::{Consumer, Observer, RingBuffer},
HeapRb,
};
use rustls_pki_types::ServerName;
use surge_ping::{Client, ConfigBuilder, ICMP, Pinger, PingIdentifier, PingSequence};
use surge_ping::{Client, ConfigBuilder, PingIdentifier, PingSequence, Pinger, ICMP};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, ReadHalf, split},
io::{split, AsyncReadExt, AsyncWriteExt, ReadHalf},
net::TcpStream,
spawn,
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
Expand Down
4 changes: 2 additions & 2 deletions src/aserver/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{
net::{IpAddr, SocketAddr},
sync::{
Arc,
atomic::{AtomicU32, Ordering},
Arc,
},
time::{Duration, Instant},
};
Expand All @@ -25,7 +25,7 @@ use crate::{
udp::start_udp,
},
config::OPTIONS,
proto::{CONNECT, PING, RequestParseResult, Sock5Address, TrojanRequest, UDP_ASSOCIATE},
proto::{RequestParseResult, Sock5Address, TrojanRequest, CONNECT, PING, UDP_ASSOCIATE},
server::{init_config, ping_backend::PingResult},
types::{Result, TrojanError},
};
Expand Down
34 changes: 31 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@ use std::{
time::Duration,
};

use clap::Parser;
use sha2::{Digest, Sha224};

use crate::{
types,
types::TrojanError,
utils::{get_system_dns, resolve},
};
use clap::Parser;
use rand::prelude::IteratorRandom;
use sha2::{Digest, Sha224};
use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts},
name_server::{GenericConnector, TokioRuntimeProvider},
AsyncResolver,
};

#[derive(Parser)]
#[clap(
Expand Down Expand Up @@ -212,6 +218,24 @@ pub struct ProxyArgs {
#[clap(skip)]
#[cfg(target_os = "linux")]
pub proxy_data: Option<tokio::sync::Mutex<crate::types::ProxyData>>,

#[clap(skip)]
pub resolver: Option<AsyncResolver<GenericConnector<TokioRuntimeProvider>>>,
}

impl ProxyArgs {
pub async fn server_addr(&self) -> types::Result<SocketAddr> {
let ip = self
.resolver
.as_ref()
.unwrap()
.lookup_ip(&self.hostname)
.await?
.iter()
.choose(&mut rand::thread_rng())
.ok_or(types::TrojanError::Resolve)?;
Ok(SocketAddr::new(ip, self.port))
}
}

#[derive(Parser)]
Expand Down Expand Up @@ -374,6 +398,10 @@ impl Opts {
}
args.proxy_data = Some(tokio::sync::Mutex::new(proxy_data));
}
args.resolver.replace(AsyncResolver::tokio(
ResolverConfig::default(),
ResolverOpts::default(),
));
let hostname = args.hostname.clone();
let port = args.port;
self.resolve(hostname, port, None);
Expand Down
4 changes: 2 additions & 2 deletions src/proxy/net_profiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ use itertools::Itertools;
use mio::{event::Event, Poll, Token};
use rand::random;
use ringbuf::{
HeapRb,
traits::{Consumer, Observer, RingBuffer},
HeapRb,
};
use surge_ping::{Client, ConfigBuilder, ICMP, PingIdentifier, PingSequence};
use surge_ping::{Client, ConfigBuilder, PingIdentifier, PingSequence, ICMP};
use tokio::{
runtime::{Builder, Runtime},
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
Expand Down
1 change: 1 addition & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub enum TrojanError {
#[from(ignore)]
Resolve,
Elapsed(tokio::time::error::Elapsed),
Resolver(trust_dns_resolver::error::ResolveError),
}

unsafe impl Send for TrojanError {}
Expand Down
10 changes: 8 additions & 2 deletions src/wintun/tun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,14 @@ impl<'a> WintunDevice<'a> {
}

impl<'b> Device for WintunDevice<'b> {
type RxToken<'a> = RxToken where Self: 'a;
type TxToken<'a> = TxToken<'a> where Self: 'a;
type RxToken<'a>
= RxToken
where
Self: 'a;
type TxToken<'a>
= TxToken<'a>
where
Self: 'a;

fn receive(
&mut self,
Expand Down

0 comments on commit 140a9e0

Please sign in to comment.