Skip to content

Commit

Permalink
apply cargo-clippy (#221)
Browse files Browse the repository at this point in the history
* fix

* apply auto fix

* up

* up

* up

* ci

* Update .github/workflows/ci.yml

Signed-off-by: Yuwei Ba <contact@yba.dev>

* Update .github/workflows/ci.yml

Signed-off-by: Yuwei Ba <contact@yba.dev>

* up

---------

Signed-off-by: Yuwei Ba <contact@yba.dev>
  • Loading branch information
ibigbug authored Dec 25, 2023
1 parent 73fe07e commit 1c76eb2
Show file tree
Hide file tree
Showing 85 changed files with 479 additions and 528 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ jobs:
- uses: Swatinem/rust-cache@v2
- name: Run cargo check
run: cargo check --all --all-features
# - name Run cargo clippy
# run: cargo clippy --all --all-features
- name: Run cargo clippy
run: cargo clippy --all --all-features -- -D warnings
- name: Run cargo test
run: cargo test --all --all-features

Expand Down
7 changes: 3 additions & 4 deletions clash_lib/src/app/api/handlers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async fn update_configs(
let g = state.global_state.lock().await;
match (req.path, req.payload) {
(_, Some(payload)) => {
let msg = format!("config reloading from payload");
let msg = "config reloading from payload".to_string();
let cfg = crate::Config::Str(payload);
match g.reload_tx.send(cfg).await {
Ok(_) => (StatusCode::ACCEPTED, msg).into_response(),
Expand Down Expand Up @@ -208,10 +208,9 @@ async fn patch_configs(

inbound_manager.rebuild_listeners(ports);

global_state
if let Some(h) = global_state
.inbound_listener_handle
.take()
.map(|h| h.abort());
.take() { h.abort() }

let r = inbound_manager.get_runner().unwrap();

Expand Down
2 changes: 1 addition & 1 deletion clash_lib/src/app/api/handlers/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ async fn update_provider(
format!(
"update proxy provider {} failed with error {}",
provider.name(),
err.to_string()
err
),
)
.into_response(),
Expand Down
1 change: 1 addition & 0 deletions clash_lib/src/app/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct AppState {
statistics_manager: Arc<StatisticsManager>,
}

#[allow(clippy::too_many_arguments)]
pub fn get_api_runner(
controller_cfg: Controller,
log_source: Sender<LogEvent>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ impl Dispatcher {
while let Some(packet) = remote_r.next().await {
// NAT
let mut packet = packet;
packet.src_addr = sess.destination.clone().into();
packet.src_addr = sess.destination.clone();
packet.dst_addr = sess.source.into();

debug!("UDP NAT for packet: {:?}, session: {}", packet, sess);
Expand Down Expand Up @@ -394,7 +394,9 @@ struct TimeoutUdpSessionManager {
impl Drop for TimeoutUdpSessionManager {
fn drop(&mut self) {
trace!("dropping timeout udp session manager");
self.cleaner.take().map(|x| x.abort());
if let Some(x) = self.cleaner.take() {
x.abort()
}
}
}

Expand Down Expand Up @@ -467,18 +469,16 @@ impl TimeoutUdpSessionManager {
}
}

struct OutboundHandleMap(
HashMap<
(String, SocketAddr),
(
JoinHandle<()>,
JoinHandle<()>,
OutboundPacketSender,
Instant,
),
>,
type OutboundHandleKey = (String, SocketAddr);
type OutboundHandleVal = (
JoinHandle<()>,
JoinHandle<()>,
OutboundPacketSender,
Instant,
);

struct OutboundHandleMap(HashMap<OutboundHandleKey, OutboundHandleVal>);

impl OutboundHandleMap {
fn new() -> Self {
Self(HashMap::new())
Expand Down
4 changes: 2 additions & 2 deletions clash_lib/src/app/dispatcher/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
mod dispatcher;
mod dispatcher_impl;
mod statistics_manager;
mod tracked;

pub use dispatcher::Dispatcher;
pub use dispatcher_impl::Dispatcher;
pub use statistics_manager::Manager as StatisticsManager;
pub use tracked::BoxedChainedDatagram;
pub use tracked::BoxedChainedStream;
Expand Down
4 changes: 3 additions & 1 deletion clash_lib/src/app/dispatcher/statistics_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ pub struct Snapshot {
connections: Vec<TrackerInfo>,
}

type ConnectionMap = HashMap<uuid::Uuid, (Tracked, Sender<()>)>;

pub struct Manager {
connections: Arc<Mutex<HashMap<uuid::Uuid, (Tracked, Sender<()>)>>>,
connections: Arc<Mutex<ConnectionMap>>,
upload_temp: AtomicI64,
download_temp: AtomicI64,
upload_blip: AtomicI64,
Expand Down
6 changes: 4 additions & 2 deletions clash_lib/src/app/dispatcher/tracked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ pub struct TrackedStream {
}

impl TrackedStream {
#[allow(clippy::borrowed_box)]
pub async fn new(
inner: BoxedChainedStream,
manager: Arc<Manager>,
Expand Down Expand Up @@ -164,7 +165,7 @@ impl TrackedStream {
impl Drop for TrackedStream {
fn drop(&mut self) {
debug!("untrack connection: {}", self.id());
let _ = self.manager.untrack(self.id());
self.manager.untrack(self.id());
}
}

Expand Down Expand Up @@ -355,6 +356,7 @@ pub struct TrackedDatagram {
}

impl TrackedDatagram {
#[allow(clippy::borrowed_box)]
pub async fn new(
inner: BoxedChainedDatagram,
manager: Arc<Manager>,
Expand Down Expand Up @@ -400,7 +402,7 @@ impl TrackedDatagram {
impl Drop for TrackedDatagram {
fn drop(&mut self) {
debug!("untrack connection: {}", self.id());
let _ = self.manager.untrack(self.id());
self.manager.untrack(self.id());
}
}

Expand Down
43 changes: 21 additions & 22 deletions clash_lib/src/app/dns/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,10 @@ pub struct Config {
}

impl Config {
pub fn parse_nameserver(servers: &Vec<String>) -> Result<Vec<NameServer>, Error> {
pub fn parse_nameserver(servers: &[String]) -> Result<Vec<NameServer>, Error> {
let mut nameservers = vec![];

for (i, server) in servers.into_iter().enumerate() {
for (i, server) in servers.iter().enumerate() {
let mut server = server.clone();

if !server.contains("://") {
Expand All @@ -106,31 +106,31 @@ impl Config {

match url.scheme() {
"udp" => {
addr = Config::host_with_default_port(&host, "53")?;
addr = Config::host_with_default_port(host, "53")?;
net = "UDP";
}
"tcp" => {
addr = Config::host_with_default_port(&host, "53")?;
addr = Config::host_with_default_port(host, "53")?;
net = "TCP";
}
"tls" => {
addr = Config::host_with_default_port(&host, "853")?;
addr = Config::host_with_default_port(host, "853")?;
net = "DoT";
}
"https" => {
addr = Config::host_with_default_port(&host, "443")?;
addr = Config::host_with_default_port(host, "443")?;
net = "DoH";
}
"dhcp" => {
addr = host.to_string();
net = "DHCP";
}
_ => {
return Err(Error::InvalidConfig(String::from(format!(
return Err(Error::InvalidConfig(format!(
"DNS nameserver [{}] unsupported scheme: {}",
i,
url.scheme()
))));
)));
}
}

Expand All @@ -150,9 +150,9 @@ impl Config {
let mut policy = HashMap::new();

for (domain, server) in policy_map {
let nameservers = Config::parse_nameserver(&vec![server.to_owned()])?;
let nameservers = Config::parse_nameserver(&[server.to_owned()])?;

let (_, valid) = trie::valid_and_split_domain(&domain);
let (_, valid) = trie::valid_and_split_domain(domain);
if !valid {
return Err(Error::InvalidConfig(format!(
"DNS ResolverRule invalid domain: {}",
Expand All @@ -164,7 +164,7 @@ impl Config {
Ok(policy)
}

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

for (_i, ip) in ipcidr.iter().enumerate() {
Expand All @@ -186,7 +186,7 @@ impl Config {
Arc::new("127.0.0.1".parse::<IpAddr>().unwrap()),
);

for (host, ip_str) in hosts_mapping.into_iter() {
for (host, ip_str) in hosts_mapping.iter() {
let ip = ip_str.parse::<IpAddr>()?;
tree.insert(host.as_str(), Arc::new(ip));
}
Expand All @@ -197,7 +197,7 @@ impl Config {
pub fn host_with_default_port(host: &str, port: &str) -> Result<String, Error> {
let has_port_suffix = Regex::new(r":\d+$").unwrap();

if has_port_suffix.is_match(&host) {
if has_port_suffix.is_match(host) {
Ok(host.into())
} else {
Ok(format!("{}:{}", host, port))
Expand All @@ -218,7 +218,7 @@ impl TryFrom<&crate::config::def::Config> for Config {

fn try_from(c: &crate::config::def::Config) -> Result<Self, Self::Error> {
let dc = &c.dns;
if dc.enable && dc.nameserver.len() == 0 {
if dc.enable && dc.nameserver.is_empty() {
return Err(Error::InvalidConfig(String::from(
"dns enabled, no nameserver specified",
)));
Expand All @@ -228,7 +228,7 @@ impl TryFrom<&crate::config::def::Config> for Config {
let fallback = Config::parse_nameserver(&dc.fallback)?;
let nameserver_policy = Config::parse_nameserver_policy(&dc.nameserver_policy)?;

if dc.default_nameserver.len() == 0 {
if dc.default_nameserver.is_empty() {
return Err(Error::InvalidConfig(String::from(
"default nameserver empty",
)));
Expand All @@ -253,9 +253,7 @@ impl TryFrom<&crate::config::def::Config> for Config {
.map(|l| match l {
DNSListen::Udp(u) => {
let addr = u.parse::<SocketAddr>().map_err(|_| {
Error::InvalidConfig(
format!("invalid dns udp listen address: {}", u).into(),
)
Error::InvalidConfig(format!("invalid dns udp listen address: {}", u))
})?;
Ok(DNSListenAddr {
udp: Some(addr),
Expand All @@ -270,9 +268,10 @@ impl TryFrom<&crate::config::def::Config> for Config {

for (k, v) in map {
let addr = v.parse::<SocketAddr>().map_err(|_| {
Error::InvalidConfig(
format!("invalid DNS listen address: {} -> {}", k, v).into(),
)
Error::InvalidConfig(format!(
"invalid DNS listen address: {} -> {}",
k, v
))
})?;
match k.as_str() {
"udp" => udp = Some(addr),
Expand Down Expand Up @@ -336,7 +335,7 @@ impl TryFrom<&crate::config::def::Config> for Config {
.map_err(|_| Error::InvalidConfig(String::from("invalid fake ip range")))?,
fake_ip_filter: dc.fake_ip_filter.clone(),
store_fake_ip: c.profile.store_fake_ip,
hosts: if dc.user_hosts && c.hosts.len() > 0 {
hosts: if dc.user_hosts && !c.hosts.is_empty() {
Config::parse_hosts(&c.hosts).ok()
} else {
let mut tree = trie::StringTrie::new();
Expand Down
8 changes: 4 additions & 4 deletions clash_lib/src/app/dns/dhcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ impl DhcpClient {
inner.clients = make_clients(
dns.into_iter()
.map(|s| NameServer {
net: DNSNetMode::UDP,
address: format!("{}:53", s.to_string()),
net: DNSNetMode::Udp,
address: format!("{}:53", s),
interface: None,
})
.collect(),
Expand Down Expand Up @@ -200,7 +200,7 @@ async fn probe_dns_server(iface: &str) -> io::Result<Vec<Ipv4Addr>> {
io::ErrorKind::Other,
format!("no MAC address on interface: {}", iface),
))?
.split(":")
.split(':')
.map(|x| {
u8::from_str_radix(x, 16)
.map_err(|_x| io::Error::new(io::ErrorKind::Other, "malformed MAC addr"))
Expand Down Expand Up @@ -290,7 +290,7 @@ async fn probe_dns_server(iface: &str) -> io::Result<Vec<Ipv4Addr>> {

_ = tokio::time::sleep(Duration::from_secs(10)) => {
dns_debug!("DHCP timeout after 10 secs");
return Err(io::Error::new(io::ErrorKind::Other, "dhcp timeout"));
Err(io::Error::new(io::ErrorKind::Other, "dhcp timeout"))
}
}
}
Expand Down
Loading

0 comments on commit 1c76eb2

Please sign in to comment.