Skip to content

Commit abbce24

Browse files
authored
Merge branch 'master' into dependabot/cargo/rust-dependencies-c9f23a8216
Signed-off-by: Yuwei Ba <dev@watfaq.com>
2 parents d7163fb + f5e7eb0 commit abbce24

22 files changed

Lines changed: 138 additions & 166 deletions

File tree

clash_lib/src/app/dispatcher/dispatcher_impl.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use std::{
1717
collections::HashMap,
1818
fmt::{Debug, Formatter},
1919
net::SocketAddr,
20-
sync::{Arc, Mutex},
20+
sync::Arc,
2121
time::{Duration, Instant},
2222
};
2323
use tokio::{
@@ -35,7 +35,7 @@ pub struct Dispatcher {
3535
outbound_manager: ThreadSafeOutboundManager,
3636
router: ThreadSafeRouter,
3737
resolver: ThreadSafeDNSResolver,
38-
mode: Arc<Mutex<RunMode>>,
38+
mode: Arc<RwLock<RunMode>>,
3939

4040
manager: Arc<Manager>,
4141
}
@@ -59,19 +59,19 @@ impl Dispatcher {
5959
outbound_manager,
6060
router,
6161
resolver,
62-
mode: Arc::new(Mutex::new(mode)),
62+
mode: Arc::new(RwLock::new(mode)),
6363
manager: statistics_manager,
6464
}
6565
}
6666

6767
pub async fn set_mode(&self, mode: RunMode) {
6868
info!("run mode switched to {}", mode);
6969

70-
*self.mode.lock().unwrap() = mode;
70+
*self.mode.write().await = mode;
7171
}
7272

7373
pub async fn get_mode(&self) -> RunMode {
74-
*self.mode.lock().unwrap()
74+
*self.mode.read().await
7575
}
7676

7777
#[instrument(skip(self, sess, lhs))]
@@ -120,7 +120,7 @@ impl Dispatcher {
120120

121121
sess.destination = dest.clone();
122122

123-
let mode = *self.mode.lock().unwrap();
123+
let mode = *self.mode.read().await;
124124
let (outbound_name, rule) = match mode {
125125
RunMode::Global => (PROXY_GLOBAL, None),
126126
RunMode::Rule => self.router.match_route(&mut sess).await,
@@ -241,7 +241,7 @@ impl Dispatcher {
241241
/// Dispatch a UDP packet to outbound handler
242242
/// returns the close sender
243243
#[instrument]
244-
pub fn dispatch_datagram(
244+
pub async fn dispatch_datagram(
245245
&self,
246246
sess: Session,
247247
udp_inbound: AnyInboundDatagram,
@@ -311,7 +311,7 @@ impl Dispatcher {
311311
// do Ip though?
312312
packet.dst_addr = dest;
313313

314-
let mode = *mode.lock().unwrap();
314+
let mode = *mode.read().await;
315315

316316
let (outbound_name, rule) = match mode {
317317
RunMode::Global => (PROXY_GLOBAL, None),

clash_lib/src/app/dns/filters.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ impl GeoIPFilter {
1717
impl FallbackIPFilter for GeoIPFilter {
1818
fn apply(&self, ip: &net::IpAddr) -> bool {
1919
self.1
20-
.lookup_contry(*ip)
20+
.lookup_country(*ip)
2121
.map(|x| x.country)
2222
.is_ok_and(|x| x.is_some_and(|x| x.iso_code == Some(self.0.as_str())))
2323
}

clash_lib/src/app/logging.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ pub struct LogEvent {
4949
pub struct EventCollector(Vec<Sender<LogEvent>>);
5050

5151
impl EventCollector {
52-
pub fn new(recivers: Vec<Sender<LogEvent>>) -> Self {
53-
Self(recivers)
52+
pub fn new(receivers: Vec<Sender<LogEvent>>) -> Self {
53+
Self(receivers)
5454
}
5555
}
5656

@@ -180,8 +180,8 @@ pub fn setup_logging(
180180
tracing::subscriber::set_global_default(subscriber)
181181
.map_err(|x| anyhow!("setup logging error: {}", x))?;
182182

183-
if let Ok(jager_endpiont) = std::env::var("JAGER_ENDPOINT") {
184-
debug!("jager endpoint: {}", jager_endpiont);
183+
if let Ok(jager_endpoint) = std::env::var("JAGER_ENDPOINT") {
184+
debug!("jager endpoint: {}", jager_endpoint);
185185
}
186186

187187
Ok(g)

clash_lib/src/app/profile/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl CacheFile {
108108
Ok(db) => db,
109109
Err(e) => {
110110
error!(
111-
"failed to parse cache file: {}, initilizing a new one",
111+
"failed to parse cache file: {}, initializing a new one",
112112
e
113113
);
114114
Db {

clash_lib/src/app/router/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl Router {
108108
let mayby_ip = sess.resolved_ip.or(sess.destination.ip());
109109
if let (Some(ip), Some(asn_mmdb)) = (mayby_ip, &self.asn_mmdb) {
110110
// try simplified mmdb first
111-
let rv = asn_mmdb.lookup_contry(ip);
111+
let rv = asn_mmdb.lookup_country(ip);
112112
if let Ok(country) = rv {
113113
sess.asn = country
114114
.country

clash_lib/src/app/router/rules/geoip.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl RuleMatcher for GeoIP {
2929
};
3030

3131
if let Some(ip) = ip {
32-
match self.mmdb.lookup_contry(ip) {
32+
match self.mmdb.lookup_country(ip) {
3333
Ok(country) => {
3434
country
3535
.country

clash_lib/src/common/io.rs

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
use std::future::Future;
33
use std::{
44
io,
5+
mem::MaybeUninit,
56
pin::Pin,
67
task::{Context, Poll},
78
time::Duration,
89
};
910

11+
use bytes::BytesMut;
1012
use futures::ready;
1113
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
1214

@@ -91,7 +93,7 @@ impl CopyBuffer {
9193
})
9294
}
9395

94-
pub fn amount_transfered(&self) -> u64 {
96+
pub fn amount_transferred(&self) -> u64 {
9597
self.amt
9698
}
9799

@@ -235,7 +237,7 @@ where
235237
match delay.as_mut().poll(cx) {
236238
Poll::Ready(()) => {
237239
*a_to_b = TransferState::ShuttingDown(
238-
buf.amount_transfered(),
240+
buf.amount_transferred(),
239241
);
240242
continue;
241243
}
@@ -285,7 +287,7 @@ where
285287
match delay.as_mut().poll(cx) {
286288
Poll::Ready(()) => {
287289
*b_to_a = TransferState::ShuttingDown(
288-
buf.amount_transfered(),
290+
buf.amount_transferred(),
289291
);
290292
continue;
291293
}
@@ -352,3 +354,56 @@ where
352354
}
353355
.await
354356
}
357+
358+
pub trait ReadExactBase {
359+
/// inner stream to be polled
360+
type I: AsyncRead + Unpin;
361+
/// prepare the inner stream, read buffer and read position
362+
fn decompose(&mut self) -> (&mut Self::I, &mut BytesMut, &mut usize);
363+
}
364+
365+
pub trait ReadExt: ReadExactBase {
366+
fn poll_read_exact(
367+
&mut self,
368+
cx: &mut std::task::Context,
369+
size: usize,
370+
) -> Poll<std::io::Result<()>>;
371+
}
372+
373+
impl<T: ReadExactBase> ReadExt for T {
374+
fn poll_read_exact(
375+
&mut self,
376+
cx: &mut std::task::Context,
377+
size: usize,
378+
) -> Poll<std::io::Result<()>> {
379+
let (raw, read_buf, read_pos) = self.decompose();
380+
read_buf.reserve(size);
381+
// # safety: read_buf has reserved `size`
382+
unsafe { read_buf.set_len(size) }
383+
loop {
384+
if *read_pos < size {
385+
// # safety: read_pos<size==read_buf.len(), and
386+
// read_buf[0..read_pos] is initialized
387+
let dst = unsafe {
388+
&mut *((&mut read_buf[*read_pos..size]) as *mut _
389+
as *mut [MaybeUninit<u8>])
390+
};
391+
let mut buf = ReadBuf::uninit(dst);
392+
let ptr = buf.filled().as_ptr();
393+
ready!(Pin::new(&mut *raw).poll_read(cx, &mut buf))?;
394+
assert_eq!(ptr, buf.filled().as_ptr());
395+
if buf.filled().is_empty() {
396+
return Poll::Ready(Err(std::io::Error::new(
397+
std::io::ErrorKind::UnexpectedEof,
398+
"unexpected eof",
399+
)));
400+
}
401+
*read_pos += buf.filled().len();
402+
} else {
403+
assert!(*read_pos == size);
404+
*read_pos = 0;
405+
return Poll::Ready(Ok(()));
406+
}
407+
}
408+
}
409+
}

clash_lib/src/common/mmdb.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ impl Mmdb {
9292
}
9393
}
9494

95-
pub fn lookup_contry(&self, ip: IpAddr) -> std::io::Result<geoip2::Country> {
95+
pub fn lookup_country(&self, ip: IpAddr) -> std::io::Result<geoip2::Country> {
9696
self.reader
9797
.lookup::<geoip2::Country>(ip)
9898
.map_err(map_io_error)

clash_lib/src/config/def.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ impl FromStr for Config {
377377
fn from_str(s: &str) -> Result<Self, Self::Err> {
378378
let mut val: Value = serde_yaml::from_str(s).map_err(|x| {
379379
Error::InvalidConfig(format!(
380-
"cound not parse config content {}: {}",
380+
"couldn't not parse config content {}: {}",
381381
s, x
382382
))
383383
})?;
@@ -391,7 +391,7 @@ impl FromStr for Config {
391391

392392
serde_yaml::from_value(val).map_err(|x| {
393393
Error::InvalidConfig(format!(
394-
"cound not parse config content {}: {}",
394+
"counldn't not parse config content {}: {}",
395395
s, x
396396
))
397397
})

clash_lib/src/lib.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ async fn start_async(opts: Options) -> Result<(), Error> {
249249

250250
let controller_cfg = config.general.controller.clone();
251251

252-
let new_componenets = create_components(cwd.clone(), config).await?;
252+
let new_components = create_components(cwd.clone(), config).await?;
253253

254254
done.send(()).unwrap();
255255

@@ -267,31 +267,31 @@ async fn start_async(opts: Options) -> Result<(), Error> {
267267
}
268268

269269
debug!("reloading inbound listener");
270-
let inbound_listener_handle = new_componenets
270+
let inbound_listener_handle = new_components
271271
.inbound_manager
272272
.lock()
273273
.await
274274
.get_runner()
275275
.map(tokio::spawn)?;
276276

277277
debug!("reloading tun runner");
278-
let tun_runner_handle = new_componenets.tun_runner.map(tokio::spawn);
278+
let tun_runner_handle = new_components.tun_runner.map(tokio::spawn);
279279

280280
debug!("reloading dns listener");
281-
let dns_listener_handle = new_componenets.dns_listener.map(tokio::spawn);
281+
let dns_listener_handle = new_components.dns_listener.map(tokio::spawn);
282282

283283
debug!("reloading api listener");
284284
let api_listener_handle = app::api::get_api_runner(
285285
controller_cfg,
286286
log_tx.clone(),
287-
new_componenets.inbound_manager,
288-
new_componenets.dispatcher,
287+
new_components.inbound_manager,
288+
new_components.dispatcher,
289289
global_state.clone(),
290-
new_componenets.dns_resolver,
291-
new_componenets.outbound_manager,
292-
new_componenets.statistics_manager,
293-
new_componenets.cache_store,
294-
new_componenets.router,
290+
new_components.dns_resolver,
291+
new_components.outbound_manager,
292+
new_components.statistics_manager,
293+
new_components.cache_store,
294+
new_components.router,
295295
cwd.to_string_lossy().to_string(),
296296
)
297297
.map(tokio::spawn);

0 commit comments

Comments
 (0)