diff options
author | Bo Zhang <[email protected]> | 2022-08-02 15:52:01 +0800 |
---|---|---|
committer | dlhxzb <[email protected]> | 2023-01-06 18:48:18 +0900 |
commit | 60a6d672c5b148cada689046389984fdaaad9a1d (patch) | |
tree | e17b95bf89f7eac440922cf312d83ad4aa7b82f9 /src | |
parent | d7b2060a5b179a0c9f4c905f39c7497faab0fa9b (diff) | |
download | rustdesk-server-60a6d672c5b148cada689046389984fdaaad9a1d.tar.gz rustdesk-server-60a6d672c5b148cada689046389984fdaaad9a1d.zip |
Fix: clippy warning in rust 1.66.0
Diffstat (limited to 'src')
-rw-r--r-- | src/common.rs | 18 | ||||
-rw-r--r-- | src/database.rs | 36 | ||||
-rw-r--r-- | src/peer.rs | 50 | ||||
-rw-r--r-- | src/relay_server.rs | 66 | ||||
-rw-r--r-- | src/rendezvous_server.rs | 75 | ||||
-rw-r--r-- | src/utils.rs | 26 | ||||
-rw-r--r-- | src/version.rs | 3 |
7 files changed, 125 insertions, 149 deletions
diff --git a/src/common.rs b/src/common.rs index e5171b7..9ea4a1e 100644 --- a/src/common.rs +++ b/src/common.rs @@ -12,15 +12,17 @@ use std::{ time::{Instant, SystemTime}, }; +#[allow(dead_code)] pub(crate) fn get_expired_time() -> Instant { let now = Instant::now(); now.checked_sub(std::time::Duration::from_secs(3600)) .unwrap_or(now) } +#[allow(dead_code)] pub(crate) fn test_if_valid_server(host: &str, name: &str) -> ResultType<SocketAddr> { use std::net::ToSocketAddrs; - let res = if host.contains(":") { + let res = if host.contains(':') { host.to_socket_addrs()?.next().context("") } else { format!("{}:{}", host, 0) @@ -34,9 +36,10 @@ pub(crate) fn test_if_valid_server(host: &str, name: &str) -> ResultType<SocketA res } +#[allow(dead_code)] pub(crate) fn get_servers(s: &str, tag: &str) -> Vec<String> { let servers: Vec<String> = s - .split(",") + .split(',') .filter(|x| !x.is_empty() && test_if_valid_server(x, tag).is_ok()) .map(|x| x.to_owned()) .collect(); @@ -44,17 +47,19 @@ pub(crate) fn get_servers(s: &str, tag: &str) -> Vec<String> { servers } +#[allow(dead_code)] #[inline] fn arg_name(name: &str) -> String { - name.to_uppercase().replace("_", "-") + name.to_uppercase().replace('_', "-") } +#[allow(dead_code)] pub fn init_args(args: &str, name: &str, about: &str) { let matches = App::new(name) .version(crate::version::VERSION) .author("Purslane Ltd. <[email protected]>") .about(about) - .args_from_usage(&args) + .args_from_usage(args) .get_matches(); if let Ok(v) = Ini::load_from_file(".env") { if let Some(section) = v.section(None::<String>) { @@ -79,16 +84,19 @@ pub fn init_args(args: &str, name: &str, about: &str) { } } +#[allow(dead_code)] #[inline] pub fn get_arg(name: &str) -> String { get_arg_or(name, "".to_owned()) } +#[allow(dead_code)] #[inline] pub fn get_arg_or(name: &str, default: String) -> String { std::env::var(arg_name(name)).unwrap_or(default) } +#[allow(dead_code)] #[inline] pub fn now() -> u64 { SystemTime::now() @@ -121,7 +129,7 @@ pub fn gen_sk(wait: u64) -> (String, Option<sign::SecretKey>) { }; let (mut pk, mut sk) = gen_func(); for _ in 0..300 { - if !pk.contains("/") && !pk.contains(":") { + if !pk.contains('/') && !pk.contains(':') { break; } (pk, sk) = gen_func(); diff --git a/src/database.rs b/src/database.rs index 41ad5e3..fa1b6ed 100644 --- a/src/database.rs +++ b/src/database.rs @@ -1,6 +1,5 @@ use async_trait::async_trait; use hbb_common::{log, ResultType}; -use serde_json::value::Value; use sqlx::{ sqlite::SqliteConnectOptions, ConnectOptions, Connection, Error as SqlxError, SqliteConnection, }; @@ -8,7 +7,6 @@ use std::{ops::DerefMut, str::FromStr}; //use sqlx::postgres::PgPoolOptions; //use sqlx::mysql::MySqlPoolOptions; -pub(crate) type MapValue = serde_json::map::Map<String, Value>; type Pool = deadpool::managed::Pool<DbPool>; pub struct DbPool { @@ -54,7 +52,7 @@ impl Database { std::fs::File::create(url).ok(); } let n: usize = std::env::var("MAX_DATABASE_CONNECTIONS") - .unwrap_or("1".to_owned()) + .unwrap_or_else(|_| "1".to_owned()) .parse() .unwrap_or(1); log::debug!("MAX_DATABASE_CONNECTIONS={}", n); @@ -105,24 +103,6 @@ impl Database { .await?) } - #[inline] - pub async fn get_conn(&self) -> ResultType<deadpool::managed::Object<DbPool>> { - Ok(self.pool.get().await?) - } - - pub async fn update_peer(&self, payload: MapValue, guid: &[u8]) -> ResultType<()> { - let mut conn = self.get_conn().await?; - let mut tx = conn.begin().await?; - if let Some(v) = payload.get("note") { - let v = get_str(v); - sqlx::query!("update peer set note = ? where guid = ?", v, guid) - .execute(&mut tx) - .await?; - } - tx.commit().await?; - Ok(()) - } - pub async fn insert_peer( &self, id: &str, @@ -199,17 +179,3 @@ mod tests { hbb_common::futures::future::join_all(jobs).await; } } - -pub(crate) fn get_str(v: &Value) -> Option<&str> { - match v { - Value::String(v) => { - let v = v.trim(); - if v.is_empty() { - None - } else { - Some(v) - } - } - _ => None, - } -} diff --git a/src/peer.rs b/src/peer.rs index 1ce5a2e..4c3ab72 100644 --- a/src/peer.rs +++ b/src/peer.rs @@ -10,10 +10,13 @@ use hbb_common::{ use serde_derive::{Deserialize, Serialize}; use std::{collections::HashMap, collections::HashSet, net::SocketAddr, sync::Arc, time::Instant}; +type IpBlockMap = HashMap<String, ((u32, Instant), (HashSet<String>, Instant))>; +type UserStatusMap = HashMap<Vec<u8>, Arc<(Option<Vec<u8>>, bool)>>; +type IpChangesMap = HashMap<String, (Instant, HashMap<String, i32>)>; lazy_static::lazy_static! { - pub(crate) static ref IP_BLOCKER: Mutex<HashMap<String, ((u32, Instant), (HashSet<String>, Instant))>> = Default::default(); - pub(crate) static ref USER_STATUS: RwLock<HashMap<Vec<u8>, Arc<(Option<Vec<u8>>, bool)>>> = Default::default(); - pub(crate) static ref IP_CHANGES: Mutex<HashMap<String, (Instant, HashMap<String, i32>)>> = Default::default(); + pub(crate) static ref IP_BLOCKER: Mutex<IpBlockMap> = Default::default(); + pub(crate) static ref USER_STATUS: RwLock<UserStatusMap> = Default::default(); + pub(crate) static ref IP_CHANGES: Mutex<IpChangesMap> = Default::default(); } pub static IP_CHANGE_DUR: u64 = 180; pub static IP_CHANGE_DUR_X2: u64 = IP_CHANGE_DUR * 2; @@ -32,9 +35,9 @@ pub(crate) struct Peer { pub(crate) guid: Vec<u8>, pub(crate) uuid: Bytes, pub(crate) pk: Bytes, - pub(crate) user: Option<Vec<u8>>, + // pub(crate) user: Option<Vec<u8>>, pub(crate) info: PeerInfo, - pub(crate) disabled: bool, + // pub(crate) disabled: bool, pub(crate) reg_pk: (u32, Instant), // how often register_pk } @@ -47,8 +50,8 @@ impl Default for Peer { uuid: Bytes::new(), pk: Bytes::new(), info: Default::default(), - user: None, - disabled: false, + // user: None, + // disabled: false, reg_pk: (0, get_expired_time()), } } @@ -65,7 +68,6 @@ pub(crate) struct PeerMap { impl PeerMap { pub(crate) async fn new() -> ResultType<Self> { let db = std::env::var("DB_URL").unwrap_or({ - #[allow(unused_mut)] let mut db = "db_v2.sqlite3".to_owned(); #[cfg(all(windows, not(debug_assertions)))] { @@ -132,24 +134,22 @@ impl PeerMap { #[inline] pub(crate) async fn get(&self, id: &str) -> Option<LockPeer> { - let p = self.map.read().await.get(id).map(|x| x.clone()); + let p = self.map.read().await.get(id).cloned(); if p.is_some() { return p; - } else { - if let Ok(Some(v)) = self.db.get_peer(id).await { - let peer = Peer { - guid: v.guid, - uuid: v.uuid.into(), - pk: v.pk.into(), - user: v.user, - info: serde_json::from_str::<PeerInfo>(&v.info).unwrap_or_default(), - disabled: v.status == Some(0), - ..Default::default() - }; - let peer = Arc::new(RwLock::new(peer)); - self.map.write().await.insert(id.to_owned(), peer.clone()); - return Some(peer); - } + } else if let Ok(Some(v)) = self.db.get_peer(id).await { + let peer = Peer { + guid: v.guid, + uuid: v.uuid.into(), + pk: v.pk.into(), + // user: v.user, + info: serde_json::from_str::<PeerInfo>(&v.info).unwrap_or_default(), + // disabled: v.status == Some(0), + ..Default::default() + }; + let peer = Arc::new(RwLock::new(peer)); + self.map.write().await.insert(id.to_owned(), peer.clone()); + return Some(peer); } None } @@ -170,7 +170,7 @@ impl PeerMap { #[inline] pub(crate) async fn get_in_memory(&self, id: &str) -> Option<LockPeer> { - self.map.read().await.get(id).map(|x| x.clone()) + self.map.read().await.get(id).cloned() } #[inline] diff --git a/src/relay_server.rs b/src/relay_server.rs index be8a69d..d6c4788 100644 --- a/src/relay_server.rs +++ b/src/relay_server.rs @@ -37,12 +37,12 @@ lazy_static::lazy_static! { } static mut DOWNGRADE_THRESHOLD: f64 = 0.66; -static mut DOWNGRADE_START_CHECK: usize = 1800_000; // in ms +static mut DOWNGRADE_START_CHECK: usize = 1_800_000; // in ms static mut LIMIT_SPEED: usize = 4 * 1024 * 1024; // in bit/s static mut TOTAL_BANDWIDTH: usize = 1024 * 1024 * 1024; // in bit/s static mut SINGLE_BANDWIDTH: usize = 16 * 1024 * 1024; // in bit/s -const BLACKLIST_FILE: &'static str = "blacklist.txt"; -const BLOCKLIST_FILE: &'static str = "blocklist.txt"; +const BLACKLIST_FILE: &str = "blacklist.txt"; +const BLOCKLIST_FILE: &str = "blocklist.txt"; #[tokio::main(flavor = "multi_thread")] pub async fn start(port: &str, key: &str) -> ResultType<()> { @@ -50,8 +50,8 @@ pub async fn start(port: &str, key: &str) -> ResultType<()> { if let Ok(mut file) = std::fs::File::open(BLACKLIST_FILE) { let mut contents = String::new(); if file.read_to_string(&mut contents).is_ok() { - for x in contents.split("\n") { - if let Some(ip) = x.trim().split(' ').nth(0) { + for x in contents.split('\n') { + if let Some(ip) = x.trim().split(' ').next() { BLACKLIST.write().await.insert(ip.to_owned()); } } @@ -65,8 +65,8 @@ pub async fn start(port: &str, key: &str) -> ResultType<()> { if let Ok(mut file) = std::fs::File::open(BLOCKLIST_FILE) { let mut contents = String::new(); if file.read_to_string(&mut contents).is_ok() { - for x in contents.split("\n") { - if let Some(ip) = x.trim().split(' ').nth(0) { + for x in contents.split('\n') { + if let Some(ip) = x.trim().split(' ').next() { BLOCKLIST.write().await.insert(ip.to_owned()); } } @@ -158,8 +158,10 @@ fn check_params() { } async fn check_cmd(cmd: &str, limiter: Limiter) -> String { + use std::fmt::Write; + let mut res = "".to_owned(); - let mut fds = cmd.trim().split(" "); + let mut fds = cmd.trim().split(' '); match fds.next() { Some("h") => { res = format!( @@ -180,7 +182,7 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { } Some("blacklist-add" | "ba") => { if let Some(ip) = fds.next() { - for ip in ip.split("|") { + for ip in ip.split('|') { BLACKLIST.write().await.insert(ip.to_owned()); } } @@ -190,7 +192,7 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { if ip == "all" { BLACKLIST.write().await.clear(); } else { - for ip in ip.split("|") { + for ip in ip.split('|') { BLACKLIST.write().await.remove(ip); } } @@ -201,13 +203,13 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { res = format!("{}\n", BLACKLIST.read().await.get(ip).is_some()); } else { for ip in BLACKLIST.read().await.clone().into_iter() { - res += &format!("{}\n", ip); + let _ = writeln!(res, "{ip}"); } } } Some("blocklist-add" | "Ba") => { if let Some(ip) = fds.next() { - for ip in ip.split("|") { + for ip in ip.split('|') { BLOCKLIST.write().await.insert(ip.to_owned()); } } @@ -217,7 +219,7 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { if ip == "all" { BLOCKLIST.write().await.clear(); } else { - for ip in ip.split("|") { + for ip in ip.split('|') { BLOCKLIST.write().await.remove(ip); } } @@ -228,7 +230,7 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { res = format!("{}\n", BLOCKLIST.read().await.get(ip).is_some()); } else { for ip in BLOCKLIST.read().await.clone().into_iter() { - res += &format!("{}\n", ip); + let _ = writeln!(res, "{ip}"); } } } @@ -313,15 +315,16 @@ async fn check_cmd(cmd: &str, limiter: Limiter) -> String { .read() .await .iter() - .map(|x| (x.0.clone(), x.1.clone())) + .map(|x| (x.0.clone(), *x.1)) .collect(); tmp.sort_by(|a, b| ((b.1).1).partial_cmp(&(a.1).1).unwrap()); for (ip, (elapsed, total, highest, speed)) in tmp { - if elapsed <= 0 { + if elapsed == 0 { continue; } - res += &format!( - "{}: {}s {:.2}MB {}kb/s {}kb/s {}kb/s\n", + let _ = writeln!( + res, + "{}: {}s {:.2}MB {}kb/s {}kb/s {}kb/s", ip, elapsed / 1000, total as f64 / 1024. / 1024. / 8., @@ -496,7 +499,7 @@ async fn relay( total_limiter.consume(nb).await; total += nb; total_s += nb; - if bytes.len() > 0 { + if !bytes.is_empty() { stream.send_raw(bytes.into()).await?; } } else { @@ -515,7 +518,7 @@ async fn relay( total_limiter.consume(nb).await; total += nb; total_s += nb; - if bytes.len() > 0 { + if !bytes.is_empty() { peer.send_raw(bytes.into()).await?; } } else { @@ -537,7 +540,7 @@ async fn relay( } blacked = BLACKLIST.read().await.get(&ip).is_some(); tm = std::time::Instant::now(); - let speed = total_s / (n as usize); + let speed = total_s / n; if speed > highest_s { highest_s = speed; } @@ -547,16 +550,17 @@ async fn relay( (elapsed as _, total as _, highest_s as _, speed as _), ); total_s = 0; - if elapsed > unsafe { DOWNGRADE_START_CHECK } && !downgrade { - if total > elapsed * downgrade_threshold { - downgrade = true; - log::info!( - "Downgrade {}, exceed downgrade threshold {}bit/ms in {}ms", - id, - downgrade_threshold, - elapsed - ); - } + if elapsed > unsafe { DOWNGRADE_START_CHECK } + && !downgrade + && total > elapsed * downgrade_threshold + { + downgrade = true; + log::info!( + "Downgrade {}, exceed downgrade threshold {}bit/ms in {}ms", + id, + downgrade_threshold, + elapsed + ); } } } diff --git a/src/rendezvous_server.rs b/src/rendezvous_server.rs index 7a63c11..48a9a23 100644 --- a/src/rendezvous_server.rs +++ b/src/rendezvous_server.rs @@ -40,7 +40,7 @@ const ADDR_127: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); #[derive(Clone, Debug)] enum Data { - Msg(RendezvousMessage, SocketAddr), + Msg(Box<RendezvousMessage>, SocketAddr), RelayServers0(String), RelayServers(RelayServers), } @@ -233,7 +233,7 @@ impl RendezvousServer { } Some(data) = rx.recv() => { match data { - Data::Msg(msg, addr) => { allow_err!(socket.send(&msg, addr).await); } + Data::Msg(msg, addr) => { allow_err!(socket.send(msg.as_ref(), addr).await); } Data::RelayServers0(rs) => { self.parse_relay_servers(&rs); } Data::RelayServers(rs) => { self.relay_servers = Arc::new(rs); } } @@ -303,11 +303,11 @@ impl RendezvousServer { socket: &mut FramedSocket, key: &str, ) -> ResultType<()> { - if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) { + if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(bytes) { match msg_in.union { Some(rendezvous_message::Union::RegisterPeer(rp)) => { // B registered - if rp.id.len() > 0 { + if !rp.id.is_empty() { log::trace!("New peer registered: {:?} {:?}", &rp.id, &addr); self.update_addr(rp.id, addr, socket).await?; if self.inner.serial > rp.serial { @@ -384,12 +384,10 @@ impl RendezvousServer { *tm = Instant::now(); ips.clear(); ips.insert(ip.clone(), 1); + } else if let Some(v) = ips.get_mut(&ip) { + *v += 1; } else { - if let Some(v) = ips.get_mut(&ip) { - *v += 1; - } else { - ips.insert(ip.clone(), 1); - } + ips.insert(ip.clone(), 1); } } else { lock.insert( @@ -472,14 +470,14 @@ impl RendezvousServer { key: &str, ws: bool, ) -> bool { - if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) { + if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(bytes) { match msg_in.union { Some(rendezvous_message::Union::PunchHoleRequest(ph)) => { // there maybe several attempt, so sink can be none if let Some(sink) = sink.take() { self.tcp_punch.lock().await.insert(addr, sink); } - allow_err!(self.handle_tcp_punch_hole_request(addr, ph, &key, ws).await); + allow_err!(self.handle_tcp_punch_hole_request(addr, ph, key, ws).await); return true; } Some(rendezvous_message::Union::RequestRelay(mut rf)) => { @@ -492,7 +490,7 @@ impl RendezvousServer { rf.socket_addr = AddrMangle::encode(addr).into(); msg_out.set_request_relay(rf); let peer_addr = peer.read().await.socket_addr; - self.tx.send(Data::Msg(msg_out, peer_addr)).ok(); + self.tx.send(Data::Msg(msg_out.into(), peer_addr)).ok(); } return true; } @@ -747,14 +745,14 @@ impl RendezvousServer { ..Default::default() }); } - return Ok((msg_out, Some(peer_addr))); + Ok((msg_out, Some(peer_addr))) } else { let mut msg_out = RendezvousMessage::new(); msg_out.set_punch_hole_response(PunchHoleResponse { failure: punch_hole_response::Failure::ID_NOT_EXIST.into(), ..Default::default() }); - return Ok((msg_out, None)); + Ok((msg_out, None)) } } @@ -765,8 +763,8 @@ impl RendezvousServer { peers: Vec<String>, ) -> ResultType<()> { let mut states = BytesMut::zeroed((peers.len() + 7) / 8); - for i in 0..peers.len() { - if let Some(peer) = self.pm.get_in_memory(&peers[i]).await { + for (i, peer_id) in peers.iter().enumerate() { + if let Some(peer) = self.pm.get_in_memory(peer_id).await { let elapsed = peer.read().await.last_reg_time.elapsed().as_millis() as i32; // bytes index from left to right let states_idx = i / 8; @@ -832,7 +830,7 @@ impl RendezvousServer { ) -> ResultType<()> { let (msg, to_addr) = self.handle_punch_hole_request(addr, ph, key, ws).await?; if let Some(addr) = to_addr { - self.tx.send(Data::Msg(msg, addr))?; + self.tx.send(Data::Msg(msg.into(), addr))?; } else { self.send_to_tcp_sync(msg, addr).await?; } @@ -848,7 +846,7 @@ impl RendezvousServer { ) -> ResultType<()> { let (msg, to_addr) = self.handle_punch_hole_request(addr, ph, key, false).await?; self.tx.send(Data::Msg( - msg, + msg.into(), match to_addr { Some(addr) => addr, None => addr, @@ -907,8 +905,10 @@ impl RendezvousServer { } async fn check_cmd(&self, cmd: &str) -> String { + use std::fmt::Write as _; + let mut res = "".to_owned(); - let mut fds = cmd.trim().split(" "); + let mut fds = cmd.trim().split(' '); match fds.next() { Some("h") => { res = format!( @@ -926,7 +926,7 @@ impl RendezvousServer { self.tx.send(Data::RelayServers0(rs.to_owned())).ok(); } else { for ip in self.relay_servers.iter() { - res += &format!("{}\n", ip); + let _ = writeln!(res, "{ip}"); } } } @@ -942,8 +942,9 @@ impl RendezvousServer { if start < 0 { if let Some(ip) = ip { if let Some((a, b)) = lock.get(ip) { - res += &format!( - "{}/{}s {}/{}s\n", + let _ = writeln!( + res, + "{}/{}s {}/{}s", a.0, a.1.elapsed().as_secs(), b.0.len(), @@ -968,8 +969,9 @@ impl RendezvousServer { continue; } if let Some((ip, (a, b))) = x { - res += &format!( - "{}: {}/{}s {}/{}s\n", + let _ = writeln!( + res, + "{}: {}/{}s {}/{}s", ip, a.0, a.1.elapsed().as_secs(), @@ -986,10 +988,10 @@ impl RendezvousServer { res = format!("{}\n", lock.len()); let id = fds.next(); let mut start = id.map(|x| x.parse::<i32>().unwrap_or(-1)).unwrap_or(-1); - if start < 0 || start > 10_000_000 { + if !(0..=10_000_000).contains(&start) { if let Some(id) = id { if let Some((tm, ips)) = lock.get(id) { - res += &format!("{}s {:?}\n", tm.elapsed().as_secs(), ips); + let _ = writeln!(res, "{}s {:?}", tm.elapsed().as_secs(), ips); } if fds.next() == Some("-") { lock.remove(id); @@ -1009,7 +1011,7 @@ impl RendezvousServer { continue; } if let Some((id, (tm, ips))) = x { - res += &format!("{}: {}s {:?}\n", id, tm.elapsed().as_secs(), ips,); + let _ = writeln!(res, "{}: {}s {:?}", id, tm.elapsed().as_secs(), ips,); } } } @@ -1023,7 +1025,7 @@ impl RendezvousServer { } self.tx.send(Data::RelayServers0(rs.to_owned())).ok(); } else { - res += &format!("ALWAYS_USE_RELAY: {:?}\n", unsafe { ALWAYS_USE_RELAY }); + let _ = writeln!(res, "ALWAYS_USE_RELAY: {:?}", unsafe { ALWAYS_USE_RELAY }); } } Some("test-geo" | "tg") => { @@ -1106,13 +1108,10 @@ impl RendezvousServer { let (a, mut b) = ws_stream.split(); sink = Some(Sink::Ws(a)); while let Ok(Some(Ok(msg))) = timeout(30_000, b.next()).await { - match msg { - tungstenite::Message::Binary(bytes) => { - if !self.handle_tcp(&bytes, &mut sink, addr, key, ws).await { - break; - } + if let tungstenite::Message::Binary(bytes) = msg { + if !self.handle_tcp(&bytes, &mut sink, addr, key, ws).await { + break; } - _ => {} } } } else { @@ -1138,7 +1137,7 @@ impl RendezvousServer { } else { match self.pm.get(&id).await { Some(peer) => { - let pk = peer.read().await.pk.clone().into(); + let pk = peer.read().await.pk.clone(); sign::sign( &hbb_common::message_proto::IdPk { id, @@ -1147,7 +1146,7 @@ impl RendezvousServer { } .write_to_bytes() .unwrap_or_default(), - &self.inner.sk.as_ref().unwrap(), + self.inner.sk.as_ref().unwrap(), ) .into() } @@ -1203,7 +1202,7 @@ async fn check_relay_servers(rs0: Arc<RelayServers>, tx: Sender) { let rs = Arc::new(Mutex::new(Vec::new())); for x in rs0.iter() { let mut host = x.to_owned(); - if !host.contains(":") { + if !host.contains(':') { host = format!("{}:{}", host, hbb_common::config::RELAY_PORT); } let rs = rs.clone(); @@ -1219,7 +1218,7 @@ async fn check_relay_servers(rs0: Arc<RelayServers>, tx: Sender) { } join_all(futs).await; log::debug!("check_relay_servers"); - let rs = std::mem::replace(&mut *rs.lock().await, Default::default()); + let rs = std::mem::take(&mut *rs.lock().await); if !rs.is_empty() { tx.send(Data::RelayServers(rs)).ok(); } diff --git a/src/utils.rs b/src/utils.rs index 7b36aed..b37878a 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -33,7 +33,7 @@ fn gen_keypair() { } fn validate_keypair(pk: &str, sk: &str) -> ResultType<()> { - let sk1 = base64::decode(&sk); + let sk1 = base64::decode(sk); if sk1.is_err() { bail!("Invalid secret key"); } @@ -45,7 +45,7 @@ fn validate_keypair(pk: &str, sk: &str) -> ResultType<()> { } let secret_key = secret_key.unwrap(); - let pk1 = base64::decode(&pk); + let pk1 = base64::decode(pk); if pk1.is_err() { bail!("Invalid public key"); } @@ -96,14 +96,13 @@ fn doctor_ip(server_ip_address: std::net::IpAddr, server_address: Option<&str>) // reverse dns lookup // TODO: (check) doesn't seem to do reverse lookup on OSX... let reverse = lookup_addr(&server_ip_address).unwrap(); - if server_address.is_some() { - if reverse == server_address.unwrap() { + if let Some(server_address) = server_address { + if reverse == server_address { println!("Reverse DNS lookup: '{}' MATCHES server address", reverse); } else { println!( "Reverse DNS lookup: '{}' DOESN'T MATCH server address '{}'", - reverse, - server_address.unwrap() + reverse, server_address ); } } @@ -126,19 +125,18 @@ fn doctor(server_address_unclean: &str) { let server_address2 = server_address3.to_lowercase(); let server_address = server_address2.as_str(); println!("Checking server: {}\n", server_address); - let server_ipaddr = server_address.parse::<IpAddr>(); - if server_ipaddr.is_err() { + if let Ok(server_ipaddr) = server_address.parse::<IpAddr>() { + // user requested an ip address + doctor_ip(server_ipaddr, None); + } else { // the passed string is not an ip address let ips: Vec<std::net::IpAddr> = lookup_host(server_address).unwrap(); - println!("Found {} IP addresses: ", ips.iter().count()); + println!("Found {} IP addresses: ", ips.len()); ips.iter().for_each(|ip| println!(" - {ip}")); - ips.iter().for_each(|ip| doctor_ip(*ip, Some(server_address))); - - } else { - // user requested an ip address - doctor_ip(server_ipaddr.unwrap(), None); + ips.iter() + .for_each(|ip| doctor_ip(*ip, Some(server_address))); } } diff --git a/src/version.rs b/src/version.rs index 3d00084..f8a74a8 100644 --- a/src/version.rs +++ b/src/version.rs @@ -1,2 +1,3 @@ pub const VERSION: &str = "1.1.6"; -pub const BUILD_DATE: &str = "2023-01-06 11:03"; +#[allow(dead_code)] +pub const BUILD_DATE: &str = "2023-01-06 18:48";
\ No newline at end of file |