mirror of
https://github.com/EasyTier/EasyTier.git
synced 2026-05-15 02:15:36 +00:00
clippy all codes (#1214)
1. clippy code 2. add fmt and clippy check in ci
This commit is contained in:
@@ -59,7 +59,7 @@ impl MagicDnsClientInstance {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
continue;
|
||||
}
|
||||
prev_last_update = Some(last_update);
|
||||
|
||||
let mut routes = peer_mgr.list_routes().await;
|
||||
// add self as a route
|
||||
let ctx = peer_mgr.get_global_ctx();
|
||||
@@ -79,6 +79,11 @@ impl MagicDnsClientInstance {
|
||||
rpc_stub
|
||||
.update_dns_record(BaseController::default(), req)
|
||||
.await?;
|
||||
|
||||
let last_update_after_rpc = peer_mgr.get_route_peer_info_last_update_time().await;
|
||||
if last_update_after_rpc == last_update {
|
||||
prev_last_update = Some(last_update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ impl Record {
|
||||
}
|
||||
|
||||
fn rr_type(&self) -> rr::RecordType {
|
||||
self.rr_type.clone().into()
|
||||
self.rr_type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ ttl = "61s"
|
||||
let (domain, records) = config
|
||||
.zones
|
||||
.get_key_value("et.internal")
|
||||
.map_or(Err(anyhow!("parse error")), |x| Ok(x))?;
|
||||
.ok_or(anyhow!("et.internal not found"))?;
|
||||
assert_eq!(domain, "et.internal");
|
||||
assert_eq!(records.len(), 1);
|
||||
let record = &records[0];
|
||||
@@ -179,7 +179,7 @@ ttl = "61s"
|
||||
let (domain, records) = config
|
||||
.zones
|
||||
.get_key_value("et.top")
|
||||
.map_or(Err(anyhow!("parse error")), |x| Ok(x))?;
|
||||
.ok_or(anyhow!("et.top not found"))?;
|
||||
assert_eq!(domain, "et.top");
|
||||
assert_eq!(records.len(), 1);
|
||||
let record = &records[0];
|
||||
|
||||
@@ -65,7 +65,7 @@ impl DnsRunner {
|
||||
self.client = Some(client);
|
||||
self.client.as_mut().unwrap().run_and_wait().await;
|
||||
|
||||
return Err(anyhow::anyhow!("Client instance exit"));
|
||||
Err(anyhow::anyhow!("Client instance exit"))
|
||||
}
|
||||
|
||||
pub async fn run(&mut self, canel_token: CancellationToken) {
|
||||
|
||||
@@ -96,12 +96,12 @@ impl Server {
|
||||
.0
|
||||
.name_servers()
|
||||
.iter()
|
||||
.cloned()
|
||||
.filter(|x| {
|
||||
.filter(|&x| {
|
||||
!config
|
||||
.excluded_forward_nameservers()
|
||||
.contains(&x.socket_addr.ip())
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
options: Some(system_conf.1),
|
||||
@@ -148,7 +148,7 @@ impl Server {
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"DNS Server failed to create UDP socket for address {}",
|
||||
address.to_string()
|
||||
address
|
||||
)
|
||||
})?;
|
||||
socket2::SockRef::from(&socket)
|
||||
@@ -156,7 +156,7 @@ impl Server {
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"DNS Server failed to set reuse address on socket {}",
|
||||
address.to_string()
|
||||
address
|
||||
)
|
||||
})?;
|
||||
socket.bind(&bind_addr.into()).with_context(|| {
|
||||
@@ -164,17 +164,17 @@ impl Server {
|
||||
})?;
|
||||
socket
|
||||
.set_nonblocking(true)
|
||||
.with_context(|| format!("DNS Server failed to set socket to non-blocking"))?;
|
||||
.with_context(|| "DNS Server failed to set socket to non-blocking".to_string())?;
|
||||
let socket = UdpSocket::from_std(socket.into()).with_context(|| {
|
||||
format!(
|
||||
"DNS Server failed to convert socket to UdpSocket for address {}",
|
||||
address.to_string()
|
||||
address
|
||||
)
|
||||
})?;
|
||||
|
||||
let local_addr = socket
|
||||
.local_addr()
|
||||
.with_context(|| format!("DNS Server failed to get local address"))?;
|
||||
.with_context(|| "DNS Server failed to get local address".to_string())?;
|
||||
self.server.register_socket(socket);
|
||||
|
||||
Ok(local_addr)
|
||||
|
||||
@@ -70,6 +70,20 @@ pub(super) struct MagicDnsServerInstanceData {
|
||||
}
|
||||
|
||||
impl MagicDnsServerInstanceData {
|
||||
fn is_valid_subdomain_label(s: &str) -> bool {
|
||||
let s = s.trim();
|
||||
|
||||
// 长度检查:1-63 个字符
|
||||
if s.is_empty() || s.len() > 63 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查每个字符是否合法,并确保不以 '-' 开头或结尾
|
||||
s.chars().all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
|
||||
&& !s.starts_with('-')
|
||||
&& !s.ends_with('-')
|
||||
}
|
||||
|
||||
pub async fn update_dns_records<'a, T: Iterator<Item = &'a Route>>(
|
||||
&self,
|
||||
routes: T,
|
||||
@@ -81,6 +95,11 @@ impl MagicDnsServerInstanceData {
|
||||
continue;
|
||||
}
|
||||
|
||||
// check host name valid for dns
|
||||
if !Self::is_valid_subdomain_label(&route.hostname) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(ipv4_addr) = route.ipv4_addr.unwrap_or_default().address else {
|
||||
continue;
|
||||
};
|
||||
@@ -432,7 +451,7 @@ impl MagicDnsServerInstance {
|
||||
if !self.tun_inet.contains(&self.data.fake_ip) && self.data.tun_dev.is_some() {
|
||||
let ifcfg = IfConfiger {};
|
||||
let _ = ifcfg
|
||||
.remove_ipv4_route(&self.data.tun_dev.as_ref().unwrap(), self.data.fake_ip, 32)
|
||||
.remove_ipv4_route(self.data.tun_dev.as_ref().unwrap(), self.data.fake_ip, 32)
|
||||
.await;
|
||||
}
|
||||
|
||||
|
||||
@@ -26,13 +26,19 @@ struct DNSConfigError {
|
||||
source: Option<anyhow::Error>,
|
||||
}
|
||||
|
||||
type DbusPingFn = dyn Fn(&str, &str) -> Result<()>;
|
||||
type DbusReadStringFn = dyn Fn(&str, &str, &str, &str) -> Result<String>;
|
||||
type NmIsUsingResolvedFn = dyn Fn() -> Result<()>;
|
||||
type NmVersionBetweenFn = dyn Fn(&str, &str) -> Result<bool>;
|
||||
type ResolvconfStyleFn = dyn Fn() -> String;
|
||||
|
||||
// 配置环境结构体
|
||||
struct OSConfigEnv {
|
||||
fs: Box<dyn FileSystem>,
|
||||
dbus_ping: Box<dyn Fn(&str, &str) -> Result<()>>,
|
||||
dbus_read_string: Box<dyn Fn(&str, &str, &str, &str) -> Result<String>>,
|
||||
nm_is_using_resolved: Box<dyn Fn() -> Result<()>>,
|
||||
nm_version_between: Box<dyn Fn(&str, &str) -> Result<bool>>,
|
||||
dbus_ping: Box<DbusPingFn>,
|
||||
dbus_read_string: Box<DbusReadStringFn>,
|
||||
nm_is_using_resolved: Box<NmIsUsingResolvedFn>,
|
||||
nm_version_between: Box<NmVersionBetweenFn>,
|
||||
resolvconf_style: Box<dyn Fn() -> String>,
|
||||
}
|
||||
|
||||
@@ -86,8 +92,7 @@ pub fn nm_is_using_resolved() -> Result<()> {
|
||||
return Err(anyhow::anyhow!(
|
||||
"NetworkManager is not using systemd-resolved, found: {:?}",
|
||||
value
|
||||
)
|
||||
.into());
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -41,7 +41,7 @@ pub async fn prepare_env(dns_name: &str, tun_ip: Ipv4Inet) -> (Arc<PeerManager>,
|
||||
|
||||
pub async fn check_dns_record(fake_ip: &Ipv4Addr, domain: &str, expected_ip: &str) {
|
||||
let stream = UdpClientStream::builder(
|
||||
SocketAddr::new(fake_ip.clone().into(), 53),
|
||||
SocketAddr::new((*fake_ip).into(), 53),
|
||||
TokioRuntimeProvider::default(),
|
||||
)
|
||||
.build();
|
||||
|
||||
@@ -258,7 +258,7 @@ pub struct Instance {
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
pub fn new(config: impl ConfigLoader + Send + Sync + 'static) -> Self {
|
||||
pub fn new(config: impl ConfigLoader + 'static) -> Self {
|
||||
let global_ctx = Arc::new(GlobalCtx::new(config));
|
||||
|
||||
tracing::info!(
|
||||
@@ -304,10 +304,10 @@ impl Instance {
|
||||
#[cfg(feature = "socks5")]
|
||||
let socks5_server = Socks5Server::new(global_ctx.clone(), peer_manager.clone(), None);
|
||||
|
||||
let rpc_server = global_ctx.config.get_rpc_portal().and_then(|s| {
|
||||
Some(StandAloneServer::new(TcpTunnelListener::new(
|
||||
let rpc_server = global_ctx.config.get_rpc_portal().map(|s| {
|
||||
StandAloneServer::new(TcpTunnelListener::new(
|
||||
format!("tcp://{}", s).parse().unwrap(),
|
||||
)))
|
||||
))
|
||||
});
|
||||
|
||||
Instance {
|
||||
@@ -470,7 +470,7 @@ impl Instance {
|
||||
continue;
|
||||
}
|
||||
|
||||
let last_ip = current_dhcp_ip.clone();
|
||||
let last_ip = current_dhcp_ip;
|
||||
tracing::debug!(
|
||||
?current_dhcp_ip,
|
||||
?candidate_ipv4_addr,
|
||||
@@ -509,11 +509,7 @@ impl Instance {
|
||||
Self::use_new_nic_ctx(
|
||||
nic_ctx.clone(),
|
||||
new_nic_ctx,
|
||||
Self::create_magic_dns_runner(
|
||||
peer_manager_c.clone(),
|
||||
ifname,
|
||||
ip.clone(),
|
||||
),
|
||||
Self::create_magic_dns_runner(peer_manager_c.clone(), ifname, ip),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -890,7 +886,7 @@ impl Instance {
|
||||
) -> Result<GetStatsResponse, rpc_types::error::Error> {
|
||||
let stats_manager = self.global_ctx.stats_manager();
|
||||
let snapshots = stats_manager.get_all_metrics();
|
||||
|
||||
|
||||
let metrics = snapshots
|
||||
.into_iter()
|
||||
.map(|snapshot| {
|
||||
@@ -898,7 +894,7 @@ impl Instance {
|
||||
for label in snapshot.labels.labels() {
|
||||
labels.insert(label.key.clone(), label.value.clone());
|
||||
}
|
||||
|
||||
|
||||
MetricSnapshot {
|
||||
name: snapshot.name_str(),
|
||||
value: snapshot.value,
|
||||
@@ -906,7 +902,7 @@ impl Instance {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
Ok(GetStatsResponse { metrics })
|
||||
}
|
||||
|
||||
@@ -917,7 +913,7 @@ impl Instance {
|
||||
) -> Result<GetPrometheusStatsResponse, rpc_types::error::Error> {
|
||||
let stats_manager = self.global_ctx.stats_manager();
|
||||
let prometheus_text = stats_manager.export_prometheus();
|
||||
|
||||
|
||||
Ok(GetPrometheusStatsResponse { prometheus_text })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn get_listener_by_url(
|
||||
}
|
||||
|
||||
pub fn is_url_host_ipv6(l: &url::Url) -> bool {
|
||||
l.host_str().map_or(false, |h| h.contains(':'))
|
||||
l.host_str().is_some_and(|h| h.contains(':'))
|
||||
}
|
||||
|
||||
pub fn is_url_host_unspecified(l: &url::Url) -> bool {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
pub mod dns_server;
|
||||
#[allow(clippy::module_inception)]
|
||||
pub mod instance;
|
||||
|
||||
pub mod listeners;
|
||||
|
||||
#[cfg(feature = "tun")]
|
||||
|
||||
@@ -68,10 +68,10 @@ impl Stream for TunStream {
|
||||
type Item = StreamItem;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<StreamItem>> {
|
||||
let mut self_mut = self.project();
|
||||
let self_mut = self.project();
|
||||
let mut g = ready!(self_mut.l.poll_lock(cx));
|
||||
reserve_buf(&mut self_mut.cur_buf, 2500, 4 * 1024);
|
||||
if self_mut.cur_buf.len() == 0 {
|
||||
reserve_buf(self_mut.cur_buf, 2500, 4 * 1024);
|
||||
if self_mut.cur_buf.is_empty() {
|
||||
unsafe {
|
||||
self_mut.cur_buf.set_len(*self_mut.payload_offset);
|
||||
}
|
||||
@@ -117,10 +117,7 @@ impl PacketProtocol {
|
||||
match self {
|
||||
PacketProtocol::IPv4 => Ok(libc::ETH_P_IP as u16),
|
||||
PacketProtocol::IPv6 => Ok(libc::ETH_P_IPV6 as u16),
|
||||
PacketProtocol::Other(_) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
"neither an IPv4 nor IPv6 packet",
|
||||
)),
|
||||
PacketProtocol::Other(_) => Err(io::Error::other("neither an IPv4 nor IPv6 packet")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +172,7 @@ impl TunZCPacketToBytes {
|
||||
}
|
||||
|
||||
impl ZCPacketToBytes for TunZCPacketToBytes {
|
||||
fn into_bytes(&self, zc_packet: ZCPacket) -> Result<Bytes, TunnelError> {
|
||||
fn zcpacket_into_bytes(&self, zc_packet: ZCPacket) -> Result<Bytes, TunnelError> {
|
||||
let payload_offset = zc_packet.payload_offset();
|
||||
let mut inner = zc_packet.inner();
|
||||
// we have peer manager header, so payload offset must larger than 4
|
||||
@@ -383,11 +380,11 @@ impl VirtualNic {
|
||||
|
||||
let dev_name = self.global_ctx.get_flags().dev_name;
|
||||
if !dev_name.is_empty() {
|
||||
config.tun_name(format!("{}", dev_name));
|
||||
config.tun_name(&dev_name);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos"))]
|
||||
#[cfg(target_os = "macos")]
|
||||
config.platform_config(|config| {
|
||||
// disable packet information so we can process the header by ourselves, see tun2 impl for more details
|
||||
config.packet_information(false);
|
||||
@@ -515,9 +512,7 @@ impl VirtualNic {
|
||||
{
|
||||
// set mtu by ourselves, rust-tun does not handle it correctly on windows
|
||||
let _g = self.global_ctx.net_ns.guard();
|
||||
self.ifcfg
|
||||
.set_mtu(ifname.as_str(), mtu_in_config as u32)
|
||||
.await?;
|
||||
self.ifcfg.set_mtu(ifname.as_str(), mtu_in_config).await?;
|
||||
}
|
||||
|
||||
let has_packet_info = cfg!(target_os = "macos");
|
||||
@@ -643,7 +638,7 @@ impl NicCtx {
|
||||
) -> Self {
|
||||
NicCtx {
|
||||
global_ctx: global_ctx.clone(),
|
||||
peer_mgr: Arc::downgrade(&peer_manager),
|
||||
peer_mgr: Arc::downgrade(peer_manager),
|
||||
peer_packet_receiver,
|
||||
nic: Arc::new(Mutex::new(VirtualNic::new(global_ctx))),
|
||||
tasks: JoinSet::new(),
|
||||
|
||||
Reference in New Issue
Block a user