From e0ea7e4f56d917d0b16202c3b08a1f076a39b409 Mon Sep 17 00:00:00 2001 From: LIAUD Corentin Date: Thu, 14 Nov 2024 15:08:34 +0100 Subject: [PATCH] fix: minor refactoring / changes --- adb_cli/src/commands/host.rs | 2 +- adb_client/src/models/adb_server_command.rs | 4 +- adb_client/src/models/mdns_services.rs | 20 ++-- adb_client/src/models/mod.rs | 10 +- adb_client/src/models/server_status.rs | 93 +++++++------------ adb_client/src/server/adb_server.rs | 45 +++++---- .../src/server/device_commands/forward.rs | 2 +- adb_client/src/server/device_commands/mod.rs | 4 +- .../src/server/device_commands/reconnect.rs | 7 +- .../src/server/device_commands/reverse.rs | 2 +- .../src/server/device_commands/tcpip.rs | 7 +- adb_client/src/server/device_commands/usb.rs | 7 +- adb_client/src/server/server_commands/mdns.rs | 28 +++--- adb_client/src/server/server_commands/mod.rs | 2 +- .../src/server/server_commands/reconnect.rs | 5 +- 15 files changed, 107 insertions(+), 131 deletions(-) diff --git a/adb_cli/src/commands/host.rs b/adb_cli/src/commands/host.rs index 3dcc953..ec01b46 100644 --- a/adb_cli/src/commands/host.rs +++ b/adb_cli/src/commands/host.rs @@ -21,6 +21,6 @@ pub enum HostCommand { Connect { address: SocketAddrV4 }, /// Disconnect device over WI-FI Disconnect { address: SocketAddrV4 }, - // Server status + /// Display server status ServerStatus, } diff --git a/adb_client/src/models/adb_server_command.rs b/adb_client/src/models/adb_server_command.rs index a7c651b..658a33d 100644 --- a/adb_client/src/models/adb_server_command.rs +++ b/adb_client/src/models/adb_server_command.rs @@ -32,7 +32,7 @@ pub(crate) enum AdbServerCommand { ReverseRemoveAll, Reconnect, TcpIp(u16), - USB, + Usb, } impl Display for AdbServerCommand { @@ -80,7 +80,7 @@ impl Display for AdbServerCommand { AdbServerCommand::TcpIp(port) => { write!(f, "tcpip:{port}") } - AdbServerCommand::USB => write!(f, "usb:"), + AdbServerCommand::Usb => write!(f, "usb:"), } } } diff --git a/adb_client/src/models/mdns_services.rs b/adb_client/src/models/mdns_services.rs index 078314e..a6b78c6 100644 --- a/adb_client/src/models/mdns_services.rs +++ b/adb_client/src/models/mdns_services.rs @@ -1,13 +1,13 @@ use lazy_static::lazy_static; use regex::bytes::Regex; -use std::{fmt::Display, str::FromStr}; use std::net::SocketAddrV4; +use std::{fmt::Display, str::FromStr}; use crate::RustADBError; lazy_static! { - static ref MDNS_SERVICES_REGEX: Regex = - Regex::new("^(\\S+)\t(\\S+)\t([\\d\\.]+:\\d+)\n?$").expect("Cannot build mdns services regex"); + static ref MDNS_SERVICES_REGEX: Regex = Regex::new("^(\\S+)\t(\\S+)\t([\\d\\.]+:\\d+)\n?$") + .expect("Cannot build mdns services regex"); } /// Represents MDNS Services @@ -23,16 +23,20 @@ pub struct MDNSServices { impl Display for MDNSServices { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}\t{}\t{}", self.service_name, self.reg_type, self.socket_v4) + write!( + f, + "{}\t{}\t{}", + self.service_name, self.reg_type, self.socket_v4 + ) } } -impl TryFrom> for MDNSServices { +impl TryFrom<&[u8]> for MDNSServices { type Error = RustADBError; - fn try_from(value: Vec) -> Result { + fn try_from(value: &[u8]) -> Result { let groups = MDNS_SERVICES_REGEX - .captures(&value) + .captures(value) .ok_or(RustADBError::RegexParsingError)?; Ok(MDNSServices { service_name: String::from_utf8( @@ -58,4 +62,4 @@ impl TryFrom> for MDNSServices { )?)?, }) } -} \ No newline at end of file +} diff --git a/adb_client/src/models/mod.rs b/adb_client/src/models/mod.rs index e286188..305ea87 100644 --- a/adb_client/src/models/mod.rs +++ b/adb_client/src/models/mod.rs @@ -7,10 +7,10 @@ mod device_long; mod device_short; mod device_state; mod host_features; -mod reboot_type; -mod sync_command; mod mdns_services; +mod reboot_type; mod server_status; +mod sync_command; pub(crate) use adb_emulator_command::ADBEmulatorCommand; pub use adb_request_status::AdbRequestStatus; @@ -21,8 +21,8 @@ pub use device_long::DeviceLong; pub use device_short::DeviceShort; pub use device_state::DeviceState; pub use host_features::HostFeatures; -pub use reboot_type::RebootType; -pub use sync_command::SyncCommand; pub use mdns_services::MDNSServices; -pub use server_status::ServerStatus; +pub use reboot_type::RebootType; pub use server_status::MDNSBackend; +pub use server_status::ServerStatus; +pub use sync_command::SyncCommand; diff --git a/adb_client/src/models/server_status.rs b/adb_client/src/models/server_status.rs index 4894750..81e16cd 100644 --- a/adb_client/src/models/server_status.rs +++ b/adb_client/src/models/server_status.rs @@ -2,19 +2,20 @@ use std::fmt::Display; use crate::RustADBError; -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub enum UsbBackend { - UNKNOWN, - NATIVE, - LIBUSB, + #[default] + Unknown, + Native, + LibUSB, } impl Display for UsbBackend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - UsbBackend::UNKNOWN => write!(f, "UNKNOWN"), - UsbBackend::NATIVE => write!(f, "NATIVE"), - UsbBackend::LIBUSB => write!(f, "LIBUSB"), + UsbBackend::Unknown => write!(f, "UNKNOWN"), + UsbBackend::Native => write!(f, "NATIVE"), + UsbBackend::LibUSB => write!(f, "LIBUSB"), } } } @@ -22,26 +23,27 @@ impl Display for UsbBackend { impl From for UsbBackend { fn from(value: i32) -> UsbBackend { match value { - 1 => UsbBackend::NATIVE, - 2 => UsbBackend::LIBUSB, - _ => UsbBackend::UNKNOWN, + 1 => UsbBackend::Native, + 2 => UsbBackend::LibUSB, + _ => UsbBackend::Unknown, } } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub enum MDNSBackend { - UNKNOWN, - BONJOUR, - OPENSCREEN, + #[default] + Unknown, + Bonjour, + OpenScreen, } impl Display for MDNSBackend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - MDNSBackend::UNKNOWN => write!(f, "UNKNOWN"), - MDNSBackend::BONJOUR => write!(f, "BONJOUR"), - MDNSBackend::OPENSCREEN => write!(f, "OPENSCREEN"), + MDNSBackend::Unknown => write!(f, "UNKNOWN"), + MDNSBackend::Bonjour => write!(f, "BONJOUR"), + MDNSBackend::OpenScreen => write!(f, "OPENSCREEN"), } } } @@ -49,59 +51,46 @@ impl Display for MDNSBackend { impl From for MDNSBackend { fn from(value: i32) -> MDNSBackend { match value { - 1 => MDNSBackend::BONJOUR, - 2 => MDNSBackend::OPENSCREEN, - _ => MDNSBackend::UNKNOWN, + 1 => MDNSBackend::Bonjour, + 2 => MDNSBackend::OpenScreen, + _ => MDNSBackend::Unknown, } } } -/// Represents Server Status -#[derive(Debug, Clone)] +/// Structure representing current server status +#[derive(Debug, Clone, Default)] pub struct ServerStatus { - /// usb backend pub usb_backend: UsbBackend, - pub usb_backend_forced: bool, - pub mdns_backend: MDNSBackend, - pub mdns_backend_forced: bool, - pub version: String, - pub build: String, - pub executable_absolute_path: String, - pub log_absolute_path: String, - pub os: String, } impl Display for ServerStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "usb_backend: {}\n", self.usb_backend)?; - if self.usb_backend_forced { - write!(f, "usb_backend_forced: {}\n", self.usb_backend_forced)?; - } - write!(f, "mdns_backend: {}\n", self.mdns_backend)?; - if self.mdns_backend_forced { - write!(f, "mdns_backend_forced: {}\n", self.mdns_backend_forced)?; - } - write!(f, "version: \"{}\"\n", self.version)?; - write!(f, "build: \"{}\"\n", self.build)?; - write!( + writeln!(f, "usb_backend: {}", self.usb_backend)?; + writeln!(f, "usb_backend_forced: {}", self.usb_backend_forced)?; + writeln!(f, "mdns_backend: {}", self.mdns_backend)?; + writeln!(f, "mdns_backend_forced: {}", self.mdns_backend_forced)?; + writeln!(f, "version: \"{}\"", self.version)?; + writeln!(f, "build: \"{}\"", self.build)?; + writeln!( f, - "executable_absolute_path: \"{}\"\n", + "executable_absolute_path: \"{}\"", self.executable_absolute_path )?; - write!(f, "log_absolute_path: \"{}\"\n", self.log_absolute_path)?; - write!(f, "os: \"{}\"\n", self.os) + writeln!(f, "log_absolute_path: \"{}\"", self.log_absolute_path)?; + writeln!(f, "os: \"{}\"", self.os) } } -fn parse_tag(cursor: &mut &[u8]) -> Result<(u8, u8), RustADBError>{ +fn parse_tag(cursor: &mut &[u8]) -> Result<(u8, u8), RustADBError> { if cursor.is_empty() { return Err(RustADBError::ConversionError); } @@ -151,17 +140,7 @@ impl TryFrom> for ServerStatus { type Error = RustADBError; fn try_from(value: Vec) -> Result { - let mut server_status = ServerStatus { - usb_backend: UsbBackend::UNKNOWN, - usb_backend_forced: false, - mdns_backend: MDNSBackend::UNKNOWN, - mdns_backend_forced: false, - version: "".to_string(), - build: "".to_string(), - executable_absolute_path: "".to_string(), - log_absolute_path: "".to_string(), - os: "".to_string(), - }; + let mut server_status = ServerStatus::default(); let mut cursor = &value[..]; while !cursor.is_empty() { let (field_number, wire_type) = parse_tag(&mut cursor)?; diff --git a/adb_client/src/server/adb_server.rs b/adb_client/src/server/adb_server.rs index 4884269..409d283 100644 --- a/adb_client/src/server/adb_server.rs +++ b/adb_client/src/server/adb_server.rs @@ -36,13 +36,6 @@ impl ADBServer { /// Connect to underlying transport pub(crate) fn connect(&mut self) -> Result<&mut TCPServerTransport> { - self.connect_with_envs(None) - } - - pub(crate) fn connect_with_envs( - &mut self, - envs: Option>, - ) -> Result<&mut TCPServerTransport> { let mut is_local_ip = false; let mut transport = if let Some(addr) = &self.socket_addr { let ip = addr.ip(); @@ -57,22 +50,7 @@ impl ADBServer { if is_local_ip { // ADB Server is local, we start it if not already running - let mut command = Command::new("adb"); - command.arg("start-server"); - if let Some(envs) = envs { - for (env_k, env_v) in envs { - command.env(env_k, env_v); - } - } - let child = command.spawn(); - match child { - Ok(mut child) => { - if let Err(e) = child.wait() { - log::error!("error while starting adb server: {e}") - } - } - Err(e) => log::error!("error while starting adb server: {e}"), - } + self.start_server(HashMap::default())?; } transport.connect()?; @@ -80,6 +58,27 @@ impl ADBServer { self.get_transport() } + + /// Start a new instance of adb-server using given environment variables + pub fn start_server(&self, envs: HashMap) -> Result<()> { + let mut command = Command::new("adb"); + command.arg("start-server"); + for (env_k, env_v) in envs { + command.env(env_k, env_v); + } + + let child = command.spawn(); + match child { + Ok(mut child) => { + if let Err(e) = child.wait() { + log::error!("error while starting adb server: {e}") + } + } + Err(e) => log::error!("error while starting adb server: {e}"), + } + + Ok(()) + } } impl Drop for ADBServer { diff --git a/adb_client/src/server/device_commands/forward.rs b/adb_client/src/server/device_commands/forward.rs index 76ce98f..80b538a 100644 --- a/adb_client/src/server/device_commands/forward.rs +++ b/adb_client/src/server/device_commands/forward.rs @@ -12,7 +12,7 @@ impl ADBServerDevice { .map(|_| ()) } - /// remove all forward rules + /// Remove all previously applied forward rules pub fn forward_remove_all(&mut self) -> Result<()> { let serial = self.identifier.clone(); self.connect()? diff --git a/adb_client/src/server/device_commands/mod.rs b/adb_client/src/server/device_commands/mod.rs index cb5a954..be7b8fd 100644 --- a/adb_client/src/server/device_commands/mod.rs +++ b/adb_client/src/server/device_commands/mod.rs @@ -4,11 +4,11 @@ mod host_features; mod list; mod logcat; mod reboot; +mod reconnect; mod recv; mod reverse; mod send; mod stat; -mod transport; mod tcpip; +mod transport; mod usb; -mod reconnect; diff --git a/adb_client/src/server/device_commands/reconnect.rs b/adb_client/src/server/device_commands/reconnect.rs index a6c5aca..4f65abe 100644 --- a/adb_client/src/server/device_commands/reconnect.rs +++ b/adb_client/src/server/device_commands/reconnect.rs @@ -1,10 +1,7 @@ -use crate::{ - models::AdbServerCommand, - ADBServerDevice, Result, -}; +use crate::{models::AdbServerCommand, ADBServerDevice, Result}; impl ADBServerDevice { - /// reconnect device + /// Reconnect device pub fn reconnect(&mut self) -> Result<()> { let serial = self.identifier.clone(); self.connect()? diff --git a/adb_client/src/server/device_commands/reverse.rs b/adb_client/src/server/device_commands/reverse.rs index feb544e..a7f3a56 100644 --- a/adb_client/src/server/device_commands/reverse.rs +++ b/adb_client/src/server/device_commands/reverse.rs @@ -12,7 +12,7 @@ impl ADBServerDevice { .map(|_| ()) } - /// remove all reverse rules + /// Remove all reverse rules pub fn reverse_remove_all(&mut self) -> Result<()> { let serial = self.identifier.clone(); self.connect()? diff --git a/adb_client/src/server/device_commands/tcpip.rs b/adb_client/src/server/device_commands/tcpip.rs index 888e4b0..8d06d31 100644 --- a/adb_client/src/server/device_commands/tcpip.rs +++ b/adb_client/src/server/device_commands/tcpip.rs @@ -1,10 +1,7 @@ -use crate::{ - models::AdbServerCommand, - ADBServerDevice, Result, -}; +use crate::{models::AdbServerCommand, ADBServerDevice, Result}; impl ADBServerDevice { - /// Set adb daemon to tcpip mode + /// Set adb daemon to tcp/ip mode pub fn tcpip(&mut self, port: u16) -> Result<()> { let serial = self.identifier.clone(); self.connect()? diff --git a/adb_client/src/server/device_commands/usb.rs b/adb_client/src/server/device_commands/usb.rs index 524cf4a..8d4fb07 100644 --- a/adb_client/src/server/device_commands/usb.rs +++ b/adb_client/src/server/device_commands/usb.rs @@ -1,7 +1,4 @@ -use crate::{ - models::AdbServerCommand, - ADBServerDevice, Result, -}; +use crate::{models::AdbServerCommand, ADBServerDevice, Result}; impl ADBServerDevice { /// Set adb daemon to usb mode @@ -11,7 +8,7 @@ impl ADBServerDevice { .send_adb_request(AdbServerCommand::TransportSerial(serial))?; self.get_transport_mut() - .proxy_connection(AdbServerCommand::USB, false) + .proxy_connection(AdbServerCommand::Usb, false) .map(|_| ()) } } diff --git a/adb_client/src/server/server_commands/mdns.rs b/adb_client/src/server/server_commands/mdns.rs index 3268123..5f08411 100644 --- a/adb_client/src/server/server_commands/mdns.rs +++ b/adb_client/src/server/server_commands/mdns.rs @@ -1,10 +1,12 @@ -use std::collections::HashMap; +use std::{collections::HashMap, io::BufRead}; use crate::{ models::{AdbServerCommand, MDNSBackend, MDNSServices}, ADBServer, Result, }; +const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN"; + impl ADBServer { /// Check if mdns discovery is available pub fn mdns_check(&mut self) -> Result { @@ -19,19 +21,20 @@ impl ADBServer { } } - /// List all discovered services + /// List all discovered mdns services pub fn mdns_services(&mut self) -> Result> { let services = self .connect()? .proxy_connection(AdbServerCommand::MDNSServices, true)?; let mut vec_services: Vec = vec![]; - for service in services.split(|x| x.eq(&b'\n')) { - if service.is_empty() { - break; + for service in services.lines() { + match service { + Ok(service) => { + vec_services.push(MDNSServices::try_from(service.as_bytes())?); + } + Err(e) => log::error!("{}", e), } - - vec_services.push(MDNSServices::try_from(service.to_vec())?); } Ok(vec_services) @@ -39,13 +42,14 @@ impl ADBServer { /// Check if openscreen mdns service is used, otherwise restart adb server with envs pub fn mdns_force_openscreen_backend(&mut self) -> Result<()> { - let status = self.server_status()?; - if status.mdns_backend != MDNSBackend::OPENSCREEN { + let server_status = self.server_status()?; + if server_status.mdns_backend != MDNSBackend::OpenScreen { self.kill()?; - self.connect_with_envs(Some(HashMap::from([( - "ADB_MDNS_OPENSCREEN".to_string(), + self.start_server(HashMap::from([( + OPENSCREEN_MDNS_BACKEND.to_string(), "1".to_string(), - )])))?; + )]))?; + self.connect()?; } Ok(()) diff --git a/adb_client/src/server/server_commands/mod.rs b/adb_client/src/server/server_commands/mod.rs index aa87a72..3931b39 100644 --- a/adb_client/src/server/server_commands/mod.rs +++ b/adb_client/src/server/server_commands/mod.rs @@ -4,6 +4,6 @@ mod disconnect; mod kill; mod mdns; mod pair; +mod reconnect; mod server_status; mod version; -mod reconnect; diff --git a/adb_client/src/server/server_commands/reconnect.rs b/adb_client/src/server/server_commands/reconnect.rs index 7df16cd..e7b9338 100644 --- a/adb_client/src/server/server_commands/reconnect.rs +++ b/adb_client/src/server/server_commands/reconnect.rs @@ -3,9 +3,8 @@ use crate::{models::AdbServerCommand, ADBServer, Result}; impl ADBServer { /// Reconnect the device pub fn reconnect_offline(&mut self) -> Result<()> { - self - .connect()? + self.connect()? .proxy_connection(AdbServerCommand::ReconnectOffline, false) .map(|_| ()) } -} \ No newline at end of file +}