Skip to content

Commit 206c8c7

Browse files
committed
Set trust-dns as default, optimized most of the context.clone()s
1 parent 4613a05 commit 206c8c7

File tree

15 files changed

+135
-469
lines changed

15 files changed

+135
-469
lines changed

Cargo.lock

Lines changed: 61 additions & 382 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ path = "src/bin/ssurl.rs"
3232
lto = true
3333

3434
[features]
35-
default = ["sodium", "rc4", "aes-cfb", "aes-ctr"]
35+
default = ["sodium", "rc4", "aes-cfb", "aes-ctr", "trust-dns"]
3636
sodium = ["libsodium-ffi"]
3737
rc4 = ["openssl"]
3838
aes-cfb = ["openssl"]
@@ -64,11 +64,9 @@ serde_urlencoded = "0.6"
6464
serde = { version = "1.0", features = ["derive"] }
6565
url = "2.1"
6666
byte_string = "1.0"
67-
# libsodium-ffi = { version = "0.1", optional = true }
68-
libsodium-ffi = { git = "https://github.com/zonyitoo/libsodium-ffi", optional = true }
67+
libsodium-ffi = { version = "0.2", optional = true }
6968
miscreant = { version = "0.4", optional = true }
70-
# trust-dns-resolver = { version = "0.11", features = ["dns-over-rustls", "dns-over-https-rustls"] }
71-
trust-dns-resolver = { git = "https://github.com/bluejekyll/trust-dns", features = ["dns-over-rustls", "dns-over-https-rustls"], optional = true }
69+
trust-dns-resolver = { version = "0.18.0-alpha", features = ["dns-over-rustls", "dns-over-https-rustls"], optional = true }
7270
hkdf = "0.8"
7371
hmac = "0.7"
7472
sha-1 = "0.8"

build/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@ RUN cd /home/rust/libs && \
1111
V=1 make && sudo make install && \
1212
cd .. && rm -rf libsodium-$SODIUM_VERS.tar.gz libsodium-$SODIUM_VERS
1313

14-
ENV SODIUM_STATIC=yes
14+
#ENV SODIUM_STATIC=yes
1515
ENV SODIUM_LIB_DIR=/usr/local/musl/lib

src/context.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,17 @@ use std::sync::{
55
Arc,
66
};
77

8-
#[cfg(futures = "trust-dns")]
8+
#[cfg(feature = "trust-dns")]
99
use trust_dns_resolver::AsyncResolver;
1010

1111
use crate::config::Config;
1212

13-
#[cfg(futures = "trust-dns")]
13+
#[cfg(feature = "trust-dns")]
1414
use crate::relay::dns_resolver::create_resolver;
1515

1616
#[derive(Clone)]
1717
pub struct SharedServerState {
18-
#[cfg(futures = "trust-dns")]
18+
#[cfg(feature = "trust-dns")]
1919
dns_resolver: Arc<AsyncResolver>,
2020
server_running: Arc<AtomicBool>,
2121
}
@@ -24,7 +24,7 @@ impl SharedServerState {
2424
#[allow(unused_variables)]
2525
pub fn new(config: &Config) -> SharedServerState {
2626
SharedServerState {
27-
#[cfg(futures = "trust-dns")]
27+
#[cfg(feature = "trust-dns")]
2828
dns_resolver: Arc::new(create_resolver(config.get_dns_config())),
2929
server_running: Arc::new(AtomicBool::new(true)),
3030
}
@@ -41,7 +41,7 @@ impl SharedServerState {
4141
}
4242

4343
/// Get the global shared resolver
44-
#[cfg(futures = "trust-dns")]
44+
#[cfg(feature = "trust-dns")]
4545
pub fn dns_resolver(&self) -> &AsyncResolver {
4646
&*self.dns_resolver
4747
}
@@ -78,7 +78,7 @@ impl Context {
7878
}
7979

8080
/// Get the global shared resolver
81-
#[cfg(futures = "trust-dns")]
81+
#[cfg(feature = "trust-dns")]
8282
pub fn dns_resolver(&self) -> &AsyncResolver {
8383
self.server_state.dns_resolver()
8484
}

src/relay/dns_resolver/trust_dns_resolver.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use log::{debug, error, trace};
99
use tokio;
1010
use trust_dns_resolver::{config::ResolverConfig, AsyncResolver};
1111

12-
use crate::context::SharedContext;
12+
use crate::context::Context;
1313

1414
pub fn create_resolver(dns: Option<ResolverConfig>) -> AsyncResolver {
1515
let (resolver, bg) = {
@@ -69,12 +69,7 @@ pub fn create_resolver(dns: Option<ResolverConfig>) -> AsyncResolver {
6969
resolver
7070
}
7171

72-
async fn inner_resolve(
73-
context: SharedContext,
74-
addr: &str,
75-
port: u16,
76-
check_forbidden: bool,
77-
) -> io::Result<Vec<SocketAddr>> {
72+
async fn inner_resolve(context: &Context, addr: &str, port: u16, check_forbidden: bool) -> io::Result<Vec<SocketAddr>> {
7873
match context.dns_resolver().lookup_ip(addr).await {
7974
Err(err) => {
8075
error!("Failed to resolve {}:{}, err: {}", addr, port, err);
@@ -109,11 +104,6 @@ async fn inner_resolve(
109104
}
110105

111106
/// Resolve address to IP
112-
pub async fn resolve(
113-
context: SharedContext,
114-
addr: &str,
115-
port: u16,
116-
check_forbidden: bool,
117-
) -> io::Result<Vec<SocketAddr>> {
107+
pub async fn resolve(context: &Context, addr: &str, port: u16, check_forbidden: bool) -> io::Result<Vec<SocketAddr>> {
118108
inner_resolve(context, addr, port, check_forbidden).await
119109
}

src/relay/loadbalancing/server/ping.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
use std::{
22
collections::VecDeque,
3-
fmt,
4-
io,
3+
fmt, io,
54
sync::{
65
atomic::{AtomicU64, AtomicUsize, Ordering},
7-
Arc,
8-
Mutex,
6+
Arc, Mutex,
97
},
108
};
119

1210
use crate::{
1311
config::ServerConfig,
14-
context::SharedContext,
12+
context::{Context, SharedContext},
1513
relay::{loadbalancing::server::LoadBalancer, socks5::Address, tcprelay::client::ServerClient},
1614
};
1715

@@ -144,7 +142,7 @@ impl Inner {
144142

145143
while context.server_running() {
146144
interval.tick().await;
147-
let score = match Inner::check_delay(sc.clone(), context.clone()).await {
145+
let score = match Inner::check_delay(&*sc, &*context).await {
148146
Ok(d) => latency.push(d),
149147
Err(..) => latency.push(DEFAULT_CHECK_TIMEOUT_SEC * 2 * 1000), // Penalty
150148
};
@@ -161,7 +159,7 @@ impl Inner {
161159
}
162160
}
163161

164-
async fn check_request(sc: Arc<ServerConfig>, context: SharedContext) -> io::Result<()> {
162+
async fn check_request(sc: Arc<ServerConfig>, context: &Context) -> io::Result<()> {
165163
static GET_BODY: &[u8] =
166164
b"GET /generate_204 HTTP/1.1\r\nHost: dl.google.com\r\nConnection: close\r\nAccept: */*\r\n\r\n";
167165

@@ -176,12 +174,12 @@ impl Inner {
176174
Ok(())
177175
}
178176

179-
async fn check_delay(sc: Arc<Server>, context: SharedContext) -> io::Result<u64> {
177+
async fn check_delay(sc: &Server, context: &Context) -> io::Result<u64> {
180178
let start = Instant::now();
181179

182180
// Send HTTP GET and read the first byte
183181
let timeout = Duration::from_secs(DEFAULT_CHECK_TIMEOUT_SEC);
184-
let res = time::timeout(timeout, Inner::check_request(sc.config.clone(), context.clone())).await;
182+
let res = time::timeout(timeout, Inner::check_request(sc.config.clone(), context)).await;
185183

186184
let elapsed = Instant::now() - start;
187185
let elapsed = elapsed.as_secs() * 1000 + u64::from(elapsed.subsec_millis()); // Converted to ms

src/relay/tcprelay/client.rs

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,18 @@ use std::{
55
net::SocketAddr,
66
pin::Pin,
77
sync::Arc,
8-
task::{Context, Poll},
8+
task::{self, Poll},
99
};
1010

1111
use log::trace;
1212
use tokio::{net::TcpStream, prelude::*};
1313

1414
use crate::relay::socks5::{
15-
self,
16-
Address,
17-
Command,
18-
HandshakeRequest,
19-
HandshakeResponse,
20-
Reply,
21-
TcpRequestHeader,
22-
TcpResponseHeader,
15+
self, Address, Command, HandshakeRequest, HandshakeResponse, Reply, TcpRequestHeader, TcpResponseHeader,
2316
};
2417

2518
use super::{CryptoStream, STcpStream};
26-
use crate::{config::ServerConfig, context::SharedContext};
19+
use crate::{config::ServerConfig, context::Context};
2720

2821
/// Socks5 proxy client
2922
pub struct Socks5Client {
@@ -111,21 +104,21 @@ impl Socks5Client {
111104
}
112105

113106
impl AsyncRead for Socks5Client {
114-
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
107+
fn poll_read(mut self: Pin<&mut Self>, cx: &mut task::Context, buf: &mut [u8]) -> Poll<Result<usize, io::Error>> {
115108
Pin::new(&mut self.stream).poll_read(cx, buf)
116109
}
117110
}
118111

119112
impl AsyncWrite for Socks5Client {
120-
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
113+
fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context, buf: &[u8]) -> Poll<Result<usize, io::Error>> {
121114
Pin::new(&mut self.stream).poll_write(cx, buf)
122115
}
123116

124-
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
117+
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Result<(), io::Error>> {
125118
Pin::new(&mut self.stream).poll_flush(cx)
126119
}
127120

128-
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
121+
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Result<(), io::Error>> {
129122
Pin::new(&mut self.stream).poll_shutdown(cx)
130123
}
131124
}
@@ -136,11 +129,11 @@ pub(crate) struct ServerClient {
136129

137130
impl ServerClient {
138131
pub(crate) async fn connect(
139-
context: SharedContext,
132+
context: &Context,
140133
addr: &Address,
141134
svr_cfg: Arc<ServerConfig>,
142135
) -> io::Result<ServerClient> {
143-
let stream = super::connect_proxy_server(context, svr_cfg.clone()).await?;
136+
let stream = super::connect_proxy_server(context, &*svr_cfg).await?;
144137
Ok(ServerClient {
145138
stream: super::proxy_server_handshake(stream, svr_cfg, addr).await?,
146139
})

src/relay/tcprelay/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ impl TcpServerContext {
102102
ServerAddr::DomainName(ref domain, ref port) => {
103103
use crate::relay::dns_resolver::resolve;
104104

105-
let addrs = resolve(self.context.clone(), &domain[..], *port, false).await?;
105+
let addrs = resolve(&*self.context, &domain[..], *port, false).await?;
106106
socket.send_to(payload.as_ref(), addrs[0]).await?;
107107
}
108108
#[cfg(not(feature = "trust-dns"))]

src/relay/tcprelay/mod.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,22 @@ use std::{
1010
ops::{Deref, DerefMut},
1111
pin::Pin,
1212
sync::Arc,
13-
task::{Context, Poll},
13+
task::{self, Poll},
1414
time::Duration,
1515
};
1616

1717
use crate::{
1818
config::{ConfigType, ServerAddr, ServerConfig},
19-
context::SharedContext,
19+
context::Context,
2020
relay::{socks5::Address, utils::try_timeout},
2121
};
2222

2323
use bytes::BytesMut;
2424
use futures::{future::FusedFuture, ready, select, Future};
2525
use log::trace;
2626
use tokio::{
27-
io::{BufReader, ReadHalf, WriteHalf},
27+
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf},
2828
net::TcpStream,
29-
prelude::*,
3029
time::{self, Delay},
3130
};
3231

@@ -78,7 +77,7 @@ impl<S> Connection<S> {
7877
ErrorKind::TimedOut.into()
7978
}
8079

81-
fn poll_timeout(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
80+
fn poll_timeout(&mut self, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
8281
loop {
8382
if let Some(ref mut timer) = self.timer {
8483
ready!(Pin::new(timer).poll(cx));
@@ -135,7 +134,7 @@ impl<S> AsyncRead for Connection<S>
135134
where
136135
S: AsyncRead + Unpin,
137136
{
138-
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
137+
fn poll_read(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
139138
match Pin::new(&mut self.stream).poll_read(cx, buf) {
140139
Poll::Ready(r) => {
141140
self.cancel_timeout();
@@ -153,7 +152,7 @@ impl<S> AsyncWrite for Connection<S>
153152
where
154153
S: AsyncRead + AsyncWrite + Unpin,
155154
{
156-
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
155+
fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
157156
match Pin::new(&mut self.stream).poll_write(cx, buf) {
158157
Poll::Ready(r) => {
159158
self.cancel_timeout();
@@ -166,7 +165,7 @@ where
166165
}
167166
}
168167

169-
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
168+
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
170169
match Pin::new(&mut self.stream).poll_flush(cx) {
171170
Poll::Ready(r) => {
172171
self.cancel_timeout();
@@ -179,15 +178,15 @@ where
179178
}
180179
}
181180

182-
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
181+
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
183182
Pin::new(&mut self.stream).poll_shutdown(cx)
184183
}
185184
}
186185

187186
pub type STcpStream = Connection<TcpStream>;
188187

189188
/// Connect to proxy server with `ServerConfig`
190-
async fn connect_proxy_server(context: SharedContext, svr_cfg: Arc<ServerConfig>) -> io::Result<STcpStream> {
189+
async fn connect_proxy_server(context: &Context, svr_cfg: &ServerConfig) -> io::Result<STcpStream> {
191190
let timeout = svr_cfg.timeout();
192191

193192
let svr_addr = match context.config().config_type {
@@ -213,7 +212,7 @@ async fn connect_proxy_server(context: SharedContext, svr_cfg: Arc<ServerConfig>
213212
let mut last_err: Option<io::Error> = None;
214213
for addr in &vec_ipaddr {
215214
match try_timeout(TcpStream::connect(addr), timeout).await {
216-
Ok(s) => return Ok(STcpStream::new(BufReader::new(s), timeout)),
215+
Ok(s) => return Ok(STcpStream::new(s, timeout)),
217216
Err(e) => {
218217
error!(
219218
"Failed to connect {}:{}, resolved address {}, try another (err: {})",

src/relay/tcprelay/server.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@ use crate::{context::SharedContext, relay::socks5::Address};
1717
use super::{
1818
context::{SharedTcpServerContext, TcpServerContext},
1919
monitor::TcpMonStream,
20-
CryptoStream,
21-
STcpStream,
20+
CryptoStream, STcpStream,
2221
};
2322

2423
#[allow(clippy::cognitive_complexity)]
@@ -94,7 +93,7 @@ async fn handle_client(
9493
Address::DomainNameAddress(ref dname, port) => {
9594
use crate::relay::dns_resolver::resolve;
9695

97-
let addrs = match resolve(context.clone(), dname.as_str(), port, true).await {
96+
let addrs = match resolve(&*context, dname.as_str(), port, true).await {
9897
Ok(r) => r,
9998
Err(err) => {
10099
error!("Failed to resolve {}, {}", dname, err);

0 commit comments

Comments
 (0)