18 Commits

Author SHA1 Message Date
Corentin LIAUD
9016b7fab4 chore: minor code improvements 2025-12-26 10:53:26 +01:00
Corentin LIAUD
558ef4df7f Track individual sessions (local and remote id) for each operation
This allows multiple operations to be performed simultaneously

Co-authored-by: gaykitty
2025-12-26 10:41:21 +01:00
Corentin LIAUD
989ba34a20 chore: clippy lints + v2.1.19 2025-12-23 21:14:21 +01:00
cocool97
da3423bc4a Merge pull request #116 from wxitcode/feat/115
feat: add Shell v2 protocol when the host supports Shell v2.
2025-12-23 21:09:20 +01:00
Corentin LIAUD
44742ada24 chore: add shell_v2 logging 2025-12-23 21:03:19 +01:00
LIAUD Corentin
dc05e85147 fix: inverted command & args 2025-12-23 20:56:24 +01:00
wxitcode
3f1a529c2b Refactor shell command handling to support v2 2025-12-23 20:54:59 +01:00
wxitcode
c3e4ea9eb8 feat: add Shell v2 protocol when the host supports Shell v2. 2025-12-23 20:54:57 +01:00
cocool97
22ceceb26a Merge pull request #103 from J05HM0N5TER/adb-list
feat: adb list
2025-12-23 20:53:26 +01:00
Corentin LIAUD
ed242808aa feat: rebase from main branch 2025-12-23 20:48:09 +01:00
J05HM0N5TER
c49378182e feat: adb list fixes 2025-12-23 20:38:41 +01:00
LIAUD Corentin
7fbea238c0 fix: remove duplicate list command 2025-12-23 20:38:39 +01:00
J05HM0N5TER
757b0f9523 feat: adb list
ADB List (ls) for both direct device communication and for communication though the adb server.
2025-12-23 20:38:31 +01:00
Himadri Bhattacharjee
d7dbc76727 Acknowledge shell_command response with OKAY messages for long responses (#154)
* fix: acknowledge write commands to continue partial data streams

* fix: read spurious close messages with a small timeout

* fix: clippy in CI not erro'ing on warnings

* breaking: bump msrv to 1.91.0

* fix: handle as many spurious CLSE messages as possible

---------

Co-authored-by: Corentin LIAUD <corentinliaud26@gmail.com>
2025-12-23 09:16:12 +01:00
Corentin LIAUD
739b3e1cee breaking: bump msrv to 1.91.0 2025-12-22 20:20:21 +01:00
Corentin LIAUD
4193779cd4 fix: clippy in CI not erro'ing on warnings 2025-12-22 19:32:22 +01:00
Corentin LIAUD
1564e99aa7 feat: improve error management in adb_cli
- adds an explicit error message when error needs to be filled with an
  issue
- remove anyhow dependency in adb_cli
- update deps
2025-12-12 19:30:05 +01:00
Pieter
c9d5df55d4 doc: adb_tcp_device.rs usb to tcp 2025-11-15 05:36:46 +01:00
53 changed files with 700 additions and 282 deletions

View File

@@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- run: rustup component add clippy - run: rustup component add clippy
- name: Run clippy - name: Run clippy
run: cargo clippy --all-features run: cargo clippy --all-features -- -Dwarnings
fmt: fmt:
name: "fmt" name: "fmt"

View File

@@ -9,8 +9,8 @@ homepage = "https://github.com/cocool97/adb_client"
keywords = ["adb", "android", "tcp", "usb"] keywords = ["adb", "android", "tcp", "usb"]
license = "MIT" license = "MIT"
repository = "https://github.com/cocool97/adb_client" repository = "https://github.com/cocool97/adb_client"
version = "2.1.18" version = "2.1.19"
rust-version = "1.85.1" rust-version = "1.91.0"
# To build locally when working on a new release # To build locally when working on a new release
[patch.crates-io] [patch.crates-io]

View File

@@ -11,11 +11,10 @@ rust-version.workspace = true
version.workspace = true version.workspace = true
[dependencies] [dependencies]
adb_client = { version = "^2.1.17" } adb_client = { version = "^2.1.18" }
anyhow = { version = "1.0.100" } clap = { version = "4.5.53", features = ["derive"] }
clap = { version = "4.5.51", features = ["derive"] }
env_logger = { version = "0.11.8" } env_logger = { version = "0.11.8" }
log = { version = "0.4.28" } log = { version = "0.4.29" }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
termios = { version = "0.3.3" } termios = { version = "0.3.3" }

View File

@@ -1,4 +1,4 @@
# adb_cli # `adb_cli`
[![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli) ![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli)

View File

@@ -4,7 +4,7 @@ use std::os::unix::prelude::{AsRawFd, RawFd};
use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr}; use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
use crate::Result; use crate::models::{ADBCliError, ADBCliResult};
pub struct ADBTermios { pub struct ADBTermios {
fd: RawFd, fd: RawFd,
@@ -13,7 +13,7 @@ pub struct ADBTermios {
} }
impl ADBTermios { impl ADBTermios {
pub fn new(fd: &impl AsRawFd) -> Result<Self> { pub fn new(fd: &impl AsRawFd) -> Result<Self, ADBCliError> {
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?; let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
let old_termios = new_termios; // Saves previous state let old_termios = new_termios; // Saves previous state
new_termios.c_lflag = 0; new_termios.c_lflag = 0;
@@ -27,7 +27,7 @@ impl ADBTermios {
}) })
} }
pub fn set_adb_termios(&mut self) -> Result<()> { pub fn set_adb_termios(&mut self) -> ADBCliResult<()> {
Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?) Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?)
} }
} }

View File

@@ -1,8 +1,8 @@
use adb_client::ADBEmulatorDevice; use adb_client::ADBEmulatorDevice;
use crate::models::{EmuCommand, EmulatorCommand}; use crate::models::{ADBCliResult, EmuCommand, EmulatorCommand};
pub fn handle_emulator_commands(emulator_command: EmulatorCommand) -> anyhow::Result<()> { pub fn handle_emulator_commands(emulator_command: EmulatorCommand) -> ADBCliResult<()> {
let mut emulator = ADBEmulatorDevice::new(emulator_command.serial, None)?; let mut emulator = ADBEmulatorDevice::new(emulator_command.serial, None)?;
match emulator_command.command { match emulator_command.command {

View File

@@ -1,14 +1,13 @@
use std::{fs::File, io::Write}; use std::{fs::File, io::Write};
use adb_client::ADBServerDevice; use crate::ADBCliResult;
use anyhow::{Result, anyhow};
use crate::models::LocalDeviceCommand; use crate::models::LocalDeviceCommand;
use adb_client::ADBServerDevice;
pub fn handle_local_commands( pub fn handle_local_commands(
mut device: ADBServerDevice, mut device: ADBServerDevice,
local_device_commands: LocalDeviceCommand, local_device_commands: LocalDeviceCommand,
) -> Result<()> { ) -> ADBCliResult<()> {
match local_device_commands { match local_device_commands {
LocalDeviceCommand::HostFeatures => { LocalDeviceCommand::HostFeatures => {
let features = device let features = device
@@ -16,12 +15,11 @@ pub fn handle_local_commands(
.iter() .iter()
.map(ToString::to_string) .map(ToString::to_string)
.reduce(|a, b| format!("{a},{b}")) .reduce(|a, b| format!("{a},{b}"))
.ok_or(anyhow!("cannot list features"))?; .unwrap_or_default();
log::info!("Available host features: {features}"); log::info!("Available host features: {features}");
Ok(()) Ok(())
} }
LocalDeviceCommand::List { path } => Ok(device.list(path)?),
LocalDeviceCommand::Logcat { path } => { LocalDeviceCommand::Logcat { path } => {
let writer: Box<dyn Write> = if let Some(path) = path { let writer: Box<dyn Write> = if let Some(path) = path {
let f = File::create(path)?; let f = File::create(path)?;

View File

@@ -8,13 +8,13 @@ mod models;
mod utils; mod utils;
use adb_client::{ use adb_client::{
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService, ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
MDNSDiscoveryService,
}; };
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
use adb_termios::ADBTermios; use adb_termios::ADBTermios;
use anyhow::Result;
use clap::Parser; use clap::Parser;
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands}; use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
use models::{DeviceCommands, LocalCommand, MainCommand, Opts}; use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
@@ -24,87 +24,10 @@ use std::io::Write;
use std::path::Path; use std::path::Path;
use utils::setup_logger; use utils::setup_logger;
fn main() -> Result<()> { use crate::models::{ADBCliError, ADBCliResult};
// This depends on `clap`
let opts = Opts::parse();
// SAFETY: fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> ADBCliResult<()> {
// We are assuming the entire process is single-threaded match command {
// at this point.
// This seems true for the current version of `clap`,
// but there's no guarantee for future updates
unsafe { setup_logger(opts.debug) };
// Directly handling methods / commands that aren't linked to [`ADBDeviceExt`] trait.
// Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it.
// This instance will then be used to execute desired command.
let (mut device, commands) = match opts.command {
MainCommand::Host(server_command) => return Ok(handle_host_commands(server_command)?),
MainCommand::Emu(emulator_command) => return handle_emulator_commands(emulator_command),
MainCommand::Local(server_command) => {
// Must start server to communicate with device, but only if this is a local one.
let server_address_ip = server_command.address.ip();
if server_address_ip.is_loopback() || server_address_ip.is_unspecified() {
ADBServer::start(&HashMap::default(), &None);
}
let device = match server_command.serial {
Some(serial) => ADBServerDevice::new(serial, Some(server_command.address)),
None => ADBServerDevice::autodetect(Some(server_command.address)),
};
match server_command.command {
LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
LocalCommand::LocalDeviceCommand(local_device_command) => {
return handle_local_commands(device, local_device_command);
}
}
}
MainCommand::Usb(usb_command) => {
let device = match (usb_command.vendor_id, usb_command.product_id) {
(Some(vid), Some(pid)) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBUSBDevice::new(vid, pid)?,
},
(None, None) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
None => ADBUSBDevice::autodetect()?,
},
_ => {
anyhow::bail!(
"please either supply values for both the --vendor-id and --product-id flags or none."
);
}
};
(device.boxed(), usb_command.commands)
}
MainCommand::Tcp(tcp_command) => {
let device = match tcp_command.path_to_private_key {
Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
None => ADBTcpDevice::new(tcp_command.address)?,
};
(device.boxed(), tcp_command.commands)
}
MainCommand::Mdns => {
let mut service = MDNSDiscoveryService::new()?;
let (tx, rx) = std::sync::mpsc::channel();
service.start(tx)?;
log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() {
log::info!(
"Found device {} with addresses {:?}",
device.fullname,
device.addresses
);
}
return Ok(service.shutdown()?);
}
};
match commands {
DeviceCommands::Shell { commands } => { DeviceCommands::Shell { commands } => {
if commands.is_empty() { if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state. // Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
@@ -162,7 +85,106 @@ fn main() -> Result<()> {
device.framebuffer(&path)?; device.framebuffer(&path)?;
log::info!("Successfully dumped framebuffer at path {path}"); log::info!("Successfully dumped framebuffer at path {path}");
} }
DeviceCommands::List { path } => {
let dirs = device.list(&path)?;
for dir in dirs {
let list_item_type = match dir.item_type {
ADBListItemType::File => "File".to_string(),
ADBListItemType::Directory => "Directory".to_string(),
ADBListItemType::Symlink => "Symlink".to_string(),
};
log::info!(
"type: {}, name: {}, time: {}, size: {}, permissions: {:#o}",
list_item_type,
dir.name,
dir.time,
dir.size,
dir.permissions
);
}
}
} }
Ok(()) Ok(())
} }
fn main() -> ADBCliResult<()> {
// This depends on `clap`
let opts = Opts::parse();
setup_logger(opts.debug);
// Directly handling methods / commands that aren't linked to [`ADBDeviceExt`] trait.
// Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it.
// This instance will then be used to execute desired command.
let (device, commands) = match opts.command {
MainCommand::Host(server_command) => return Ok(handle_host_commands(server_command)?),
MainCommand::Emu(emulator_command) => return handle_emulator_commands(emulator_command),
MainCommand::Local(server_command) => {
// Must start server to communicate with device, but only if this is a local one.
let server_address_ip = server_command.address.ip();
if server_address_ip.is_loopback() || server_address_ip.is_unspecified() {
ADBServer::start(&HashMap::default(), &None);
}
let device = match server_command.serial {
Some(serial) => ADBServerDevice::new(serial, Some(server_command.address)),
None => ADBServerDevice::autodetect(Some(server_command.address)),
};
match server_command.command {
LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
LocalCommand::LocalDeviceCommand(local_device_command) => {
return handle_local_commands(device, local_device_command);
}
}
}
MainCommand::Usb(usb_command) => {
let device = match (usb_command.vendor_id, usb_command.product_id) {
(Some(vid), Some(pid)) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBUSBDevice::new(vid, pid)?,
},
(None, None) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
None => ADBUSBDevice::autodetect()?,
},
_ => {
return Err(ADBCliError::Standard(
"cannot specify flags --vendor-id without --product-id or vice versa"
.into(),
));
}
};
(device.boxed(), usb_command.commands)
}
MainCommand::Tcp(tcp_command) => {
let device = match tcp_command.path_to_private_key {
Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
None => ADBTcpDevice::new(tcp_command.address)?,
};
(device.boxed(), tcp_command.commands)
}
MainCommand::Mdns => {
let mut service = MDNSDiscoveryService::new()?;
let (tx, rx) = std::sync::mpsc::channel();
service.start(tx)?;
log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() {
log::info!(
"Found device {} with addresses {:?}",
device.fullname,
device.addresses
);
}
return Ok(service.shutdown()?);
}
};
run_command(device, commands)?;
Ok(())
}

View File

@@ -0,0 +1,85 @@
use std::fmt::Debug;
use adb_client::RustADBError;
pub type ADBCliResult<T> = Result<T, ADBCliError>;
pub enum ADBCliError {
Standard(Box<dyn std::error::Error>),
MayNeedAnIssue(Box<dyn std::error::Error>),
}
impl Debug for ADBCliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ADBCliError::Standard(error) => write!(f, "{error}"),
ADBCliError::MayNeedAnIssue(error) => write!(
f,
r"
This error is abnormal and may need to fill an issue.
Please submit it to this project's repository here: https://github.com/cocool97/adb_client/issues.
Error source:
{error}
",
),
}
}
}
impl From<std::io::Error> for ADBCliError {
fn from(value: std::io::Error) -> Self {
// We do not consider adb_cli related `std::io::error` as critical
Self::Standard(Box::new(value))
}
}
impl From<adb_client::RustADBError> for ADBCliError {
fn from(value: adb_client::RustADBError) -> Self {
let value = Box::new(value);
match value.as_ref() {
// List of [`RustADBError`] that may need an issue as abnormal
RustADBError::RegexParsingError
| RustADBError::WrongResponseReceived(_, _)
| RustADBError::FramebufferImageError(_)
| RustADBError::FramebufferConversionError
| RustADBError::UnimplementedFramebufferImageVersion(_)
| RustADBError::IOError(_)
| RustADBError::ADBRequestFailed(_)
| RustADBError::UnknownDeviceState(_)
| RustADBError::Utf8StrError(_)
| RustADBError::Utf8StringError(_)
| RustADBError::RegexError(_)
| RustADBError::ParseIntError(_)
| RustADBError::ConversionError
| RustADBError::IntegerConversionError(_)
| RustADBError::HomeError
| RustADBError::NoHomeDirectory
| RustADBError::UsbError(_)
| RustADBError::InvalidIntegrity(_, _)
| RustADBError::Base64DecodeError(_)
| RustADBError::Base64EncodeError(_)
| RustADBError::RSAError(_)
| RustADBError::TryFromSliceError(_)
| RustADBError::RsaPkcs8Error(_)
| RustADBError::CertificateGenerationError(_)
| RustADBError::TLSError(_)
| RustADBError::PemCertError(_)
| RustADBError::PoisonError
| RustADBError::UpgradeError(_)
| RustADBError::MDNSError(_)
| RustADBError::SendError(_)
| RustADBError::UnknownFileMode(_)
| RustADBError::UnknownTransport(_) => Self::MayNeedAnIssue(value),
// List of [`RustADBError`] that may occur in standard contexts and therefore do not require for issues
RustADBError::ADBDeviceNotPaired
| RustADBError::UnknownResponseType(_)
| RustADBError::DeviceNotFound(_)
| RustADBError::USBNoDescriptorFound
| RustADBError::ADBShellNotSupported
| RustADBError::USBDeviceNotFound(_, _)
| RustADBError::WrongFileExtension(_)
| RustADBError::AddrParseError(_) => Self::Standard(value),
}
}
}

View File

@@ -43,4 +43,9 @@ pub enum DeviceCommands {
/// Framebuffer image destination path /// Framebuffer image destination path
path: String, path: String,
}, },
/// List files on device
List {
/// Path to list files from
path: String,
},
} }

View File

@@ -1,4 +1,4 @@
use std::net::SocketAddrV4; use std::{net::SocketAddrV4, str::FromStr};
use adb_client::{RustADBError, WaitForDeviceTransport}; use adb_client::{RustADBError, WaitForDeviceTransport};
use clap::Parser; use clap::Parser;
@@ -6,7 +6,7 @@ use clap::Parser;
fn parse_wait_for_device_device_transport( fn parse_wait_for_device_device_transport(
value: &str, value: &str,
) -> Result<WaitForDeviceTransport, RustADBError> { ) -> Result<WaitForDeviceTransport, RustADBError> {
WaitForDeviceTransport::try_from(value) WaitForDeviceTransport::from_str(value)
} }
#[derive(Parser, Debug)] #[derive(Parser, Debug)]

View File

@@ -14,8 +14,6 @@ pub enum LocalCommand {
pub enum LocalDeviceCommand { pub enum LocalDeviceCommand {
/// List available server features. /// List available server features.
HostFeatures, HostFeatures,
/// List a directory on device
List { path: String },
/// Get logs of device /// Get logs of device
Logcat { Logcat {
/// Path to output file (created if not exists) /// Path to output file (created if not exists)

View File

@@ -1,3 +1,4 @@
mod adb_cli_error;
mod device; mod device;
mod emu; mod emu;
mod host; mod host;
@@ -7,6 +8,7 @@ mod reboot_type;
mod tcp; mod tcp;
mod usb; mod usb;
pub use adb_cli_error::{ADBCliError, ADBCliResult};
pub use device::DeviceCommands; pub use device::DeviceCommands;
pub use emu::{EmuCommand, EmulatorCommand}; pub use emu::{EmuCommand, EmulatorCommand};
pub use host::{HostCommand, MdnsCommand}; pub use host::{HostCommand, MdnsCommand};

View File

@@ -1,14 +1,9 @@
/// # Safety use env_logger::{Builder, Env};
///
/// This conditionally mutates the process' environment.
/// See [`std::env::set_var`] for more info.
pub unsafe fn setup_logger(debug: bool) {
// RUST_LOG variable has more priority then "--debug" flag
if std::env::var("RUST_LOG").is_err() {
let level = if debug { "trace" } else { "info" };
unsafe { std::env::set_var("RUST_LOG", level) }; /// Sets up appropriate logger level:
} /// - if `RUST_LOG` environment variable is set, use its value
/// - else, use `debug` CLI option
env_logger::init(); pub fn setup_logger(debug: bool) {
Builder::from_env(Env::default().default_filter_or(if debug { "debug" } else { "info" }))
.init();
} }

View File

@@ -15,21 +15,21 @@ base64 = { version = "0.22.1" }
bincode = { version = "2.0.1", features = ["serde"] } bincode = { version = "2.0.1", features = ["serde"] }
byteorder = { version = "1.5.0" } byteorder = { version = "1.5.0" }
chrono = { version = "0.4.42", default-features = false, features = ["std"] } chrono = { version = "0.4.42", default-features = false, features = ["std"] }
image = { version = "0.25.8", default-features = false } image = { version = "0.25.9", default-features = false }
log = { version = "0.4.28" } log = { version = "0.4.29" }
mdns-sd = { version = "0.17.0", default-features = false, features = [ mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging", "logging",
] } ] }
num-bigint = { version = "0.8.5", package = "num-bigint-dig" } num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" } num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" } quick-protobuf = { version = "0.8.1" }
rand = { version = "0.9.2" } rand = { version = "0.9.2" }
rcgen = { version = "0.14.5" } rcgen = { version = "0.14.6" }
regex = { version = "1.12.2", features = ["perf", "std", "unicode"] } regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
rsa = { version = "0.9.8" } rsa = { version = "0.9.9" }
rusb = { version = "0.9.4", features = ["vendored"] } rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.35" } rustls = { version = "0.23.35" }
rustls-pki-types = { version = "1.13.0" } rustls-pki-types = { version = "1.13.2" }
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_repr = { version = "0.1.20" } serde_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] } sha1 = { version = "0.10.6", features = ["oid"] }

View File

@@ -1,4 +1,4 @@
# adb_client # `adb_client`
[![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT)
[![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client) [![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client)

View File

@@ -4,7 +4,7 @@ use std::path::Path;
use image::{ImageBuffer, ImageFormat, Rgba}; use image::{ImageBuffer, ImageFormat, Rgba};
use crate::models::AdbStatResponse; use crate::models::AdbStatResponse;
use crate::{RebootType, Result}; use crate::{ADBListItem, RebootType, Result};
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`] /// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
pub trait ADBDeviceExt { pub trait ADBDeviceExt {
@@ -24,6 +24,9 @@ pub trait ADBDeviceExt {
/// Push `stream` to `path` on the device. /// Push `stream` to `path` on the device.
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()>; fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()>;
/// List the items in a directory on the device
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<ADBListItem>>;
/// Reboot the device using given reboot type /// Reboot the device using given reboot type
fn reboot(&mut self, reboot_type: RebootType) -> Result<()>; fn reboot(&mut self, reboot_type: RebootType) -> Result<()>;

View File

@@ -1,5 +1,6 @@
use super::{ADBRsaKey, ADBTransportMessage, MessageCommand, models::MessageSubcommand}; use super::{ADBRsaKey, ADBTransportMessage, MessageCommand, models::MessageSubcommand};
use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN}; use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::device::models::ADBSession;
use crate::{ADBMessageTransport, AdbStatResponse, Result, RustADBError, constants::BUFFER_SIZE}; use crate::{ADBMessageTransport, AdbStatResponse, Result, RustADBError, constants::BUFFER_SIZE};
use bincode::config::{Configuration, Fixint, LittleEndian, NoLimit}; use bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
use byteorder::ReadBytesExt; use byteorder::ReadBytesExt;
@@ -27,18 +28,12 @@ pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -
#[derive(Debug)] #[derive(Debug)]
pub struct ADBMessageDevice<T: ADBMessageTransport> { pub struct ADBMessageDevice<T: ADBMessageTransport> {
transport: T, transport: T,
local_id: Option<u32>,
remote_id: Option<u32>,
} }
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Instantiate a new [`ADBMessageTransport`] /// Instantiate a new [`ADBMessageTransport`]
pub fn new(transport: T) -> Self { pub fn new(transport: T) -> Self {
Self { Self { transport }
transport,
local_id: None,
remote_id: None,
}
} }
pub(crate) fn get_transport(&mut self) -> &T { pub(crate) fn get_transport(&mut self) -> &T {
@@ -110,12 +105,15 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
} }
/// Receive a message and acknowledge it by replying with an `OKAY` command /// Receive a message and acknowledge it by replying with an `OKAY` command
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> { pub(crate) fn recv_and_reply_okay(
&mut self,
session: ADBSession,
) -> Result<ADBTransportMessage> {
let message = self.transport.read_message()?; let message = self.transport.read_message()?;
self.transport.write_message(ADBTransportMessage::new( self.transport.write_message(ADBTransportMessage::new(
MessageCommand::Okay, MessageCommand::Okay,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
&[], &[],
))?; ))?;
Ok(message) Ok(message)
@@ -136,11 +134,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn recv_file<W: std::io::Write>( pub(crate) fn recv_file<W: std::io::Write>(
&mut self, &mut self,
session: ADBSession,
mut output: W, mut output: W,
) -> std::result::Result<(), RustADBError> { ) -> std::result::Result<(), RustADBError> {
let mut len: Option<u64> = None; let mut len: Option<u64> = None;
loop { loop {
let payload = self.recv_and_reply_okay()?.into_payload(); let payload = self.recv_and_reply_okay(session)?.into_payload();
let mut rdr = Cursor::new(&payload); let mut rdr = Cursor::new(&payload);
while rdr.position() != payload.len() as u64 { while rdr.position() != payload.len() as u64 {
match len.take() { match len.take() {
@@ -173,8 +172,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push_file<R: std::io::Read>( pub(crate) fn push_file<R: std::io::Read>(
&mut self, &mut self,
local_id: u32, session: ADBSession,
remote_id: u32,
mut reader: R, mut reader: R,
) -> std::result::Result<(), RustADBError> { ) -> std::result::Result<(), RustADBError> {
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice(); let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
@@ -186,8 +184,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
&serialized_message, &serialized_message,
); );
@@ -204,8 +202,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let serialized_message = bincode_serialize_to_vec(&subcommand_data)?; let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
&serialized_message, &serialized_message,
); );
@@ -230,8 +228,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
&serialized_message, &serialized_message,
); );
@@ -244,24 +242,27 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
} }
} }
pub(crate) fn begin_synchronization(&mut self) -> Result<()> { pub(crate) fn begin_synchronization(&mut self) -> Result<ADBSession> {
self.open_session(b"sync:\0")?; self.open_session(b"sync:\0")
Ok(())
} }
pub(crate) fn stat_with_explicit_ids(&mut self, remote_path: &str) -> Result<AdbStatResponse> { pub(crate) fn stat_with_explicit_ids(
&mut self,
session: ADBSession,
remote_path: &str,
) -> Result<AdbStatResponse> {
let stat_buffer = MessageSubcommand::Stat.with_arg(u32::try_from(remote_path.len())?); let stat_buffer = MessageSubcommand::Stat.with_arg(u32::try_from(remote_path.len())?);
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
&bincode_serialize_to_vec(&stat_buffer)?, &bincode_serialize_to_vec(&stat_buffer)?,
); );
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
remote_path.as_bytes(), remote_path.as_bytes(),
))?; ))?;
let response = self.transport.read_message()?; let response = self.transport.read_message()?;
@@ -271,24 +272,25 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
bincode_deserialize_from_slice(&response.into_payload()[4..]) bincode_deserialize_from_slice(&response.into_payload()[4..])
} }
pub(crate) fn end_transaction(&mut self) -> Result<()> { pub(crate) fn end_transaction(&mut self, session: ADBSession) -> Result<()> {
let quit_buffer = MessageSubcommand::Quit.with_arg(0u32); let quit_buffer = MessageSubcommand::Quit.with_arg(0u32);
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
&bincode_serialize_to_vec(&quit_buffer)?, &bincode_serialize_to_vec(&quit_buffer)?,
))?; ))?;
let _discard_close = self.transport.read_message()?; let _discard_close = self.transport.read_message()?;
Ok(()) Ok(())
} }
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> { pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBSession> {
let mut rng = rand::rng(); let mut rng = rand::rng();
let local_id: u32 = rng.random();
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Open, MessageCommand::Open,
rng.random(), // Our 'local-id' local_id, // Our 'local-id'
0, 0,
data, data,
); );
@@ -296,21 +298,20 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let response = self.get_transport_mut().read_message()?; let response = self.get_transport_mut().read_message()?;
self.local_id = Some(response.header().arg1()); if response.header().command() != MessageCommand::Okay {
self.remote_id = Some(response.header().arg0()); return Err(RustADBError::ADBRequestFailed(format!(
"Open session failed: got {} in respone instead of OKAY",
response.header().command()
)));
}
Ok(response) if response.header().arg1() != local_id {
} return Err(RustADBError::ADBRequestFailed(format!(
"Open session failed: respones used {} for our local_id instead of {local_id}",
response.header().arg1()
)));
}
pub(crate) fn get_local_id(&self) -> Result<u32> { Ok(ADBSession::new(local_id, response.header().arg0()))
self.local_id.ok_or(RustADBError::ADBRequestFailed(
"connection not opened, no local_id".into(),
))
}
pub(crate) fn get_remote_id(&self) -> Result<u32> {
self.remote_id.ok_or(RustADBError::ADBRequestFailed(
"connection not opened, no remote_id".into(),
))
} }
} }

View File

@@ -42,4 +42,8 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> { fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.framebuffer_inner() self.framebuffer_inner()
} }
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
self.list(path)
}
} }

View File

@@ -1,5 +1,5 @@
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::Path;
use std::{io::Read, net::SocketAddr}; use std::{io::Read, net::SocketAddr};
use super::adb_message_device::ADBMessageDevice; use super::adb_message_device::ADBMessageDevice;
@@ -8,7 +8,7 @@ use super::{ADBRsaKey, ADBTransportMessage, get_default_adb_key_path};
use crate::device::adb_usb_device::read_adb_private_key; use crate::device::adb_usb_device::read_adb_private_key;
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport}; use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport};
/// Represent a device reached and available over USB. /// Represent a device reached and available over TCP.
#[derive(Debug)] #[derive(Debug)]
pub struct ADBTcpDevice { pub struct ADBTcpDevice {
private_key: ADBRsaKey, private_key: ADBRsaKey,
@@ -22,16 +22,16 @@ impl ADBTcpDevice {
} }
/// Instantiate a new [`ADBTcpDevice`] using a custom private key path /// Instantiate a new [`ADBTcpDevice`] using a custom private key path
pub fn new_with_custom_private_key( pub fn new_with_custom_private_key<P: AsRef<Path>>(
address: SocketAddr, address: SocketAddr,
private_key_path: PathBuf, private_key_path: P,
) -> Result<Self> { ) -> Result<Self> {
let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? { let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
private_key private_key
} else { } else {
log::warn!( log::warn!(
"No private key found at path {}. Using a temporary random one.", "No private key found at path {}. Using a temporary random one.",
private_key_path.display() private_key_path.as_ref().display()
); );
ADBRsaKey::new_random()? ADBRsaKey::new_random()?
}; };
@@ -136,6 +136,10 @@ impl ADBDeviceExt for ADBTcpDevice {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> { fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner() self.inner.framebuffer_inner()
} }
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
self.inner.list(path)
}
} }
impl Drop for ADBTcpDevice { impl Drop for ADBTcpDevice {

View File

@@ -110,12 +110,12 @@ impl ADBUSBDevice {
} }
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path /// Instantiate a new [`ADBUSBDevice`] using a custom private key path
pub fn new_with_custom_private_key( pub fn new_with_custom_private_key<P: AsRef<Path>>(
vendor_id: u16, vendor_id: u16,
product_id: u16, product_id: u16,
private_key_path: PathBuf, private_key_path: P,
) -> Result<Self> { ) -> Result<Self> {
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, &private_key_path) Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
} }
/// Instantiate a new [`ADBUSBDevice`] from a [`USBTransport`] and an optional private key path. /// Instantiate a new [`ADBUSBDevice`] from a [`USBTransport`] and an optional private key path.
@@ -131,16 +131,16 @@ impl ADBUSBDevice {
Self::new_from_transport_inner(transport, &private_key_path) Self::new_from_transport_inner(transport, &private_key_path)
} }
fn new_from_transport_inner( fn new_from_transport_inner<P: AsRef<Path>>(
transport: USBTransport, transport: USBTransport,
private_key_path: &PathBuf, private_key_path: P,
) -> Result<Self> { ) -> Result<Self> {
let private_key = if let Some(private_key) = read_adb_private_key(private_key_path)? { let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
private_key private_key
} else { } else {
log::warn!( log::warn!(
"No private key found at path {}. Using a temporary random one.", "No private key found at path {}. Using a temporary random one.",
private_key_path.display() private_key_path.as_ref().display()
); );
ADBRsaKey::new_random()? ADBRsaKey::new_random()?
}; };
@@ -247,6 +247,10 @@ impl ADBDeviceExt for ADBUSBDevice {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> { fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner() self.inner.framebuffer_inner()
} }
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
self.inner.list(path)
}
} }
impl Drop for ADBUSBDevice { impl Drop for ADBUSBDevice {

View File

@@ -11,9 +11,9 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> { pub(crate) fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
self.open_session(b"framebuffer:\0")?; let session = self.open_session(b"framebuffer:\0")?;
let response = self.recv_and_reply_okay()?; let response = self.recv_and_reply_okay(session)?;
let mut payload_cursor = Cursor::new(response.payload()); let mut payload_cursor = Cursor::new(response.payload());
@@ -36,7 +36,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
break; break;
} }
let response = self.recv_and_reply_okay()?; let response = self.recv_and_reply_okay(session)?;
framebuffer_data.extend_from_slice(&response.into_payload()); framebuffer_data.extend_from_slice(&response.into_payload());
@@ -69,7 +69,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
break; break;
} }
let response = self.recv_and_reply_okay()?; let response = self.recv_and_reply_okay(session)?;
framebuffer_data.extend_from_slice(&response.into_payload()); framebuffer_data.extend_from_slice(&response.into_payload());

View File

@@ -14,11 +14,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let file_size = apk_file.metadata()?.len(); let file_size = apk_file.metadata()?.len();
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?; let session =
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?;
let transport = self.get_transport().clone(); let transport = self.get_transport().clone();
let mut writer = MessageWriter::new(transport, self.get_local_id()?, self.get_remote_id()?); let mut writer = MessageWriter::new(transport, session.local_id(), session.remote_id());
std::io::copy(&mut apk_file, &mut writer)?; std::io::copy(&mut apk_file, &mut writer)?;

View File

@@ -0,0 +1,177 @@
use crate::{
ADBListItem, ADBListItemType, ADBMessageTransport, Result, RustADBError,
device::{
ADBTransportMessage, MessageCommand, MessageSubcommand,
adb_message_device::{ADBMessageDevice, bincode_serialize_to_vec},
},
};
use byteorder::ByteOrder;
use byteorder::LittleEndian;
use std::str;
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// List the entries in the given directory on the device.
/// note: path uses internal file paths, so Documents is at /storage/emulated/0/Documents
pub(crate) fn list<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
let session = self.begin_synchronization()?;
let output = self.handle_list(path, session.local_id(), session.remote_id());
self.end_transaction(session)?;
output
}
/// Request amount of bytes from transport, potentially across payloads
///
/// This automatically request a new payload by sending back "Okay" and waiting for the next payload
/// It reads the request bytes across the existing payload, and if there is not enough bytes left,
/// reads the rest from the next payload
///
/// Current index
/// ┼───────────────┼ Requested
/// ┌─────────────┐
/// ┌───────────────┼───────┐ │
/// └───────────────────────┘
/// Current └─────┘
/// payload Wanted in
/// Next payload
fn read_bytes_from_transport(
requested_bytes: &usize,
current_index: &mut usize,
transport: &mut T,
payload: &mut Vec<u8>,
local_id: &u32,
remote_id: &u32,
) -> Result<Vec<u8>> {
if *current_index + requested_bytes <= payload.len() {
// if there is enough bytes in this payload
// Copy from existing payload
let slice = &payload[*current_index..*current_index + requested_bytes];
*current_index += requested_bytes;
Ok(slice.to_vec())
} else {
// Read the rest of the existing payload, then continue with the next message
let mut slice = Vec::new();
let bytes_read_from_existing_payload = payload.len() - *current_index;
slice.extend_from_slice(
&payload[*current_index..*current_index + bytes_read_from_existing_payload],
);
// Request the next message
let send_message =
ADBTransportMessage::new(MessageCommand::Okay, *local_id, *remote_id, &[]);
transport.write_message(send_message)?;
// Read the new message
*payload = transport.read_message()?.into_payload();
let bytes_read_from_new_payload = requested_bytes - bytes_read_from_existing_payload;
slice.extend_from_slice(&payload[..bytes_read_from_new_payload]);
*current_index = bytes_read_from_new_payload;
Ok(slice)
}
}
fn handle_list<A: AsRef<str>>(
&mut self,
path: A,
local_id: u32,
remote_id: u32,
) -> Result<Vec<ADBListItem>> {
// TODO: use LIS2 to support files over 2.14 GB in size.
// SEE: https://github.com/cstyan/adbDocumentation?tab=readme-ov-file#adb-list
{
let mut len_buf = Vec::from([0_u8; 4]);
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
let subcommand_data = MessageSubcommand::List;
let mut serialized_message = bincode_serialize_to_vec(subcommand_data)
.map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut len_buf);
let mut path_bytes: Vec<u8> = Vec::from(path.as_ref().as_bytes());
serialized_message.append(&mut path_bytes);
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
&serialized_message,
);
self.send_and_expect_okay(message)?;
}
let mut list_items = Vec::new();
let transport = self.get_transport_mut();
let mut payload = transport.read_message()?.into_payload();
let mut current_index = 0;
loop {
// Loop though the response for all the entries
const STATUS_CODE_LENGTH_IN_BYTES: usize = 4;
let status_code = Self::read_bytes_from_transport(
&STATUS_CODE_LENGTH_IN_BYTES,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
)?;
match str::from_utf8(&status_code)? {
"DENT" => {
// Read the file mode, size, mod time and name length in one go, since all their sizes are predictable
const U32_SIZE_IN_BYTES: usize = 4;
const SIZE_OF_METADATA: usize = U32_SIZE_IN_BYTES * 4;
let metadata = Self::read_bytes_from_transport(
&SIZE_OF_METADATA,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
)?;
let mode = metadata[..U32_SIZE_IN_BYTES].to_vec();
let size = metadata[U32_SIZE_IN_BYTES..2 * U32_SIZE_IN_BYTES].to_vec();
let time = metadata[2 * U32_SIZE_IN_BYTES..3 * U32_SIZE_IN_BYTES].to_vec();
let name_len = metadata[3 * U32_SIZE_IN_BYTES..4 * U32_SIZE_IN_BYTES].to_vec();
let mode = LittleEndian::read_u32(&mode);
let size = LittleEndian::read_u32(&size);
let time = LittleEndian::read_u32(&time);
let name_len = LittleEndian::read_u32(&name_len) as usize;
// Read the file name, since it requires the length from the name_len
let name_buf = Self::read_bytes_from_transport(
&name_len,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
)?;
let name = String::from_utf8(name_buf)?;
// First 9 bits are the file permissions
let permissions = mode & 0b1_1111_1111;
// Bits 14 to 16 are the file type
let item_type = match (mode >> 13) & 0b111 {
0b010 => ADBListItemType::Directory,
0b100 => ADBListItemType::File,
0b101 => ADBListItemType::Symlink,
type_code => return Err(RustADBError::UnknownFileMode(type_code)),
};
let entry = ADBListItem {
item_type,
name,
time,
size,
permissions,
};
list_items.push(entry);
}
"DONE" => {
return Ok(list_items);
}
x => log::error!("Got an unknown response {}", x),
}
}
}
}

View File

@@ -1,5 +1,6 @@
mod framebuffer; mod framebuffer;
mod install; mod install;
mod list;
mod pull; mod pull;
mod push; mod push;
mod reboot; mod reboot;

View File

@@ -11,10 +11,10 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> { pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
self.begin_synchronization()?; let session = self.begin_synchronization()?;
let source = source.as_ref(); let source = source.as_ref();
let adb_stat_response = self.stat_with_explicit_ids(source)?; let adb_stat_response = self.stat_with_explicit_ids(session, source)?;
if adb_stat_response.file_perm == 0 { if adb_stat_response.file_perm == 0 {
return Err(RustADBError::UnknownResponseType( return Err(RustADBError::UnknownResponseType(
@@ -22,11 +22,13 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
)); ));
} }
let local_id = self.get_local_id()?;
let remote_id = self.get_remote_id()?;
self.get_transport_mut().write_message_with_timeout( self.get_transport_mut().write_message_with_timeout(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]), ADBTransportMessage::new(
MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
),
std::time::Duration::from_secs(4), std::time::Duration::from_secs(4),
)?; )?;
@@ -34,19 +36,19 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?; let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
&recv_buffer, &recv_buffer,
))?; ))?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
source.as_bytes(), source.as_bytes(),
))?; ))?;
self.recv_file(output)?; self.recv_file(session, output)?;
self.end_transaction()?; self.end_transaction(session)?;
Ok(()) Ok(())
} }
} }

View File

@@ -10,7 +10,7 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
self.begin_synchronization()?; let session = self.begin_synchronization()?;
let path_header = format!("{},0777", path.as_ref()); let path_header = format!("{},0777", path.as_ref());
@@ -20,14 +20,13 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, session.local_id(),
self.get_remote_id()?, session.remote_id(),
&send_buffer, &send_buffer,
))?; ))?;
self.push_file(self.get_local_id()?, self.get_remote_id()?, stream)?; self.push_file(session, stream)?;
self.end_transaction(session)?;
self.end_transaction()?;
Ok(()) Ok(())
} }

View File

@@ -1,4 +1,5 @@
use std::io::{ErrorKind, Read, Write}; use std::io::{ErrorKind, Read, Write};
use std::time::Duration;
use crate::Result; use crate::Result;
use crate::device::ShellMessageWriter; use crate::device::ShellMessageWriter;
@@ -10,24 +11,35 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Runs 'command' in a shell on the device, and write its output and error streams into output. /// Runs 'command' in a shell on the device, and write its output and error streams into output.
pub(crate) fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> { pub(crate) fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
let response = self.open_session(format!("shell:{}\0", command.join(" "),).as_bytes())?; let session = self.open_session(format!("shell:{}\0", command.join(" "),).as_bytes())?;
if response.header().command() != MessageCommand::Okay { let mut transport = self.get_transport().clone();
return Err(RustADBError::ADBRequestFailed(format!(
"wrong command {}",
response.header().command()
)));
}
loop { loop {
let response = self.get_transport_mut().read_message()?; let message = transport.read_message()?;
if response.header().command() != MessageCommand::Write { let command = message.header().command();
if command == MessageCommand::Clse {
break; break;
} }
output.write_all(&response.into_payload())?; self.get_transport_mut()
.write_message(ADBTransportMessage::new(
MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
))?;
output.write_all(&message.into_payload())?;
} }
// some devices will repeat the trailing CLSE command to ensure
// the client has acknowledged it. Read them quickly if present.
while let Ok(_discard_close_message) =
transport.read_message_with_timeout(Duration::from_millis(20))
{}
Ok(()) Ok(())
} }
@@ -38,21 +50,22 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
mut reader: &mut dyn Read, mut reader: &mut dyn Read,
mut writer: Box<dyn Write + Send>, mut writer: Box<dyn Write + Send>,
) -> Result<()> { ) -> Result<()> {
self.open_session(b"shell:\0")?; let session = self.open_session(b"shell:\0")?;
let mut transport = self.get_transport().clone(); let mut transport = self.get_transport().clone();
let local_id = self.get_local_id()?;
let remote_id = self.get_remote_id()?;
// Reading thread, reads response from adbd // Reading thread, reads response from adbd
std::thread::spawn(move || -> Result<()> { std::thread::spawn(move || -> Result<()> {
loop { loop {
let message = transport.read_message()?; let message = transport.read_message()?;
// Acknowledge for more data // Acknowledge for more data
let response = let response = ADBTransportMessage::new(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]); MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
);
transport.write_message(response)?; transport.write_message(response)?;
match message.header().command() { match message.header().command() {
@@ -67,7 +80,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
}); });
let transport = self.get_transport().clone(); let transport = self.get_transport().clone();
let mut shell_writer = ShellMessageWriter::new(transport, local_id, remote_id); let mut shell_writer =
ShellMessageWriter::new(transport, session.local_id(), session.remote_id());
// Read from given reader (that could be stdin e.g), and write content to device adbd // Read from given reader (that could be stdin e.g), and write content to device adbd
if let Err(e) = std::io::copy(&mut reader, &mut shell_writer) { if let Err(e) = std::io::copy(&mut reader, &mut shell_writer) {

View File

@@ -4,9 +4,9 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> { pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
self.begin_synchronization()?; let session = self.begin_synchronization()?;
let adb_stat_response = self.stat_with_explicit_ids(remote_path)?; let adb_stat_response = self.stat_with_explicit_ids(session, remote_path)?;
self.end_transaction()?; self.end_transaction(session)?;
Ok(adb_stat_response) Ok(adb_stat_response)
} }
} }

View File

@@ -0,0 +1,23 @@
/// Represent a session between an ADBDevice and remote `adbd`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ADBSession {
local_id: u32,
remote_id: u32,
}
impl ADBSession {
pub fn new(local_id: u32, remote_id: u32) -> Self {
Self {
local_id,
remote_id,
}
}
pub fn local_id(self) -> u32 {
self.local_id
}
pub fn remote_id(self) -> u32 {
self.remote_id
}
}

View File

@@ -1,5 +1,7 @@
mod adb_rsa_key; mod adb_rsa_key;
mod adb_session;
mod message_commands; mod message_commands;
pub use adb_rsa_key::ADBRsaKey; pub use adb_rsa_key::ADBRsaKey;
pub(crate) use adb_session::ADBSession;
pub use message_commands::{MessageCommand, MessageSubcommand}; pub use message_commands::{MessageCommand, MessageSubcommand};

View File

@@ -3,6 +3,6 @@ use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Send a SMS to this emulator with given content with given phone number /// Send a SMS to this emulator with given content with given phone number
pub fn rotate(&mut self) -> Result<()> { pub fn rotate(&mut self) -> Result<()> {
self.connect()?.send_command(ADBEmulatorCommand::Rotate) self.connect()?.send_command(&ADBEmulatorCommand::Rotate)
} }
} }

View File

@@ -3,7 +3,7 @@ use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Send a SMS to this emulator with given content with given phone number /// Send a SMS to this emulator with given content with given phone number
pub fn send_sms(&mut self, phone_number: &str, content: &str) -> Result<()> { pub fn send_sms(&mut self, phone_number: &str, content: &str) -> Result<()> {
self.connect()?.send_command(ADBEmulatorCommand::Sms( self.connect()?.send_command(&ADBEmulatorCommand::Sms(
phone_number.to_string(), phone_number.to_string(),
content.to_string(), content.to_string(),
)) ))

View File

@@ -123,6 +123,9 @@ pub enum RustADBError {
/// An unknown transport has been provided /// An unknown transport has been provided
#[error("unknown transport: {0}")] #[error("unknown transport: {0}")]
UnknownTransport(String), UnknownTransport(String),
/// An unknown file mode was encountered in list
#[error("Unknown file mode {0}")]
UnknownFileMode(u32),
} }
impl<T> From<std::sync::PoisonError<T>> for RustADBError { impl<T> From<std::sync::PoisonError<T>> for RustADBError {

View File

@@ -21,7 +21,7 @@ pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice; pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError}; pub use error::{Result, RustADBError};
pub use mdns::*; pub use mdns::*;
pub use models::{AdbStatResponse, RebootType}; pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use server::*; pub use server::*;
pub use server_device::ADBServerDevice; pub use server_device::ADBServerDevice;
pub use transports::*; pub use transports::*;

View File

@@ -26,7 +26,7 @@ pub(crate) enum AdbServerCommand {
Install(u64), Install(u64),
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport), WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
// Local commands // Local commands
ShellCommand(String), ShellCommand(String, Vec<String>),
Shell, Shell,
FrameBuffer, FrameBuffer,
Sync, Sync,
@@ -51,10 +51,14 @@ impl Display for AdbServerCommand {
AdbServerCommand::TrackDevices => write!(f, "host:track-devices"), AdbServerCommand::TrackDevices => write!(f, "host:track-devices"),
AdbServerCommand::TransportAny => write!(f, "host:transport-any"), AdbServerCommand::TransportAny => write!(f, "host:transport-any"),
AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"), AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"),
AdbServerCommand::ShellCommand(command) => match std::env::var("TERM") { AdbServerCommand::ShellCommand(command, args) => {
Ok(term) => write!(f, "shell,TERM={term},raw:{command}"), let args_s = args.join(",");
Err(_) => write!(f, "shell,raw:{command}"), write!(
}, f,
"shell{}{args_s},raw:{command}",
if args.is_empty() { "" } else { "," }
)
}
AdbServerCommand::Shell => match std::env::var("TERM") { AdbServerCommand::Shell => match std::env::var("TERM") {
Ok(term) => write!(f, "shell,TERM={term},raw:"), Ok(term) => write!(f, "shell,TERM={term},raw:"),
Err(_) => write!(f, "shell,raw:"), Err(_) => write!(f, "shell,raw:"),

View File

@@ -0,0 +1,25 @@
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
/// A list entry on the remote device
pub struct ADBListItem {
/// The name of the file, not the path
pub name: String,
/// The unix time stamp of when it was last modified
pub time: u32,
/// The unix mode of the file, used for permissions and special bits
pub permissions: u32,
/// The size of the file
pub size: u32,
/// The type of item this is, file, directory or symlink
pub item_type: ADBListItemType,
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
/// The different types of item that the list item can be
pub enum ADBListItemType {
/// The entry is a file
File,
/// The entry is a directory
Directory,
/// The entry is a symlink
Symlink,
}

View File

@@ -3,6 +3,7 @@ mod adb_server_command;
mod adb_stat_response; mod adb_stat_response;
mod framebuffer_info; mod framebuffer_info;
mod host_features; mod host_features;
mod list_info;
mod reboot_type; mod reboot_type;
mod sync_command; mod sync_command;
@@ -11,5 +12,6 @@ pub(crate) use adb_server_command::AdbServerCommand;
pub use adb_stat_response::AdbStatResponse; pub use adb_stat_response::AdbStatResponse;
pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2}; pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2};
pub use host_features::HostFeatures; pub use host_features::HostFeatures;
pub use list_info::{ADBListItem, ADBListItemType};
pub use reboot_type::RebootType; pub use reboot_type::RebootType;
pub use sync_command::SyncCommand; pub use sync_command::SyncCommand;

View File

@@ -16,6 +16,7 @@ pub struct AdbVersion {
impl AdbVersion { impl AdbVersion {
/// Instantiates a new [`AdbVersion`]. /// Instantiates a new [`AdbVersion`].
#[must_use]
pub fn new(minor: u32, revision: u32) -> Self { pub fn new(minor: u32, revision: u32) -> Self {
Self { Self {
major: 1, major: 1,

View File

@@ -1,4 +1,4 @@
use std::fmt::Display; use std::{fmt::Display, str::FromStr};
use crate::RustADBError; use crate::RustADBError;
@@ -24,10 +24,10 @@ impl Display for WaitForDeviceTransport {
} }
} }
impl TryFrom<&str> for WaitForDeviceTransport { impl FromStr for WaitForDeviceTransport {
type Error = RustADBError; type Err = RustADBError;
fn try_from(value: &str) -> Result<Self, Self::Error> { fn from_str(value: &str) -> Result<Self, Self::Err> {
match value { match value {
"usb" => Ok(Self::Usb), "usb" => Ok(Self::Usb),
"local" => Ok(Self::Local), "local" => Ok(Self::Local),

View File

@@ -22,8 +22,24 @@ impl ADBDeviceExt for ADBServerDevice {
self.set_serial_transport()?; self.set_serial_transport()?;
// Prepare shell command arguments
let mut args = Vec::new();
let command_string = command.join(" ");
// Add v2 mode if supported
if supported_features.contains(&HostFeatures::ShellV2) {
log::debug!("using shell_v2 feature");
args.push("v2".to_string());
}
// Include terminal information if available
if let Ok(term) = std::env::var("TERM") {
args.push(format!("TERM={term}"));
}
// Send the request
self.transport self.transport
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?; .send_adb_request(AdbServerCommand::ShellCommand(command_string, args))?;
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice(); let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
loop { loop {
@@ -119,4 +135,8 @@ impl ADBDeviceExt for ADBServerDevice {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> { fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.framebuffer_inner() self.framebuffer_inner()
} }
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
self.list(path)
}
} }

View File

@@ -1,8 +1,8 @@
use crate::{ use crate::{
ADBServerDevice, Result, ADBServerDevice, Result, RustADBError,
models::{AdbServerCommand, SyncCommand}, models::{ADBListItem, ADBListItemType, AdbServerCommand, SyncCommand},
}; };
use byteorder::{ByteOrder, LittleEndian}; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
str, str,
@@ -10,21 +10,22 @@ use std::{
impl ADBServerDevice { impl ADBServerDevice {
/// Lists files in path on the device. /// Lists files in path on the device.
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<()> { /// note: path uses internal file paths, so Documents is at /storage/emulated/0/Documents
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
self.set_serial_transport()?; self.set_serial_transport()?;
// Set device in SYNC mode // Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?; self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a list command // Send a list command
self.transport.send_sync_request(SyncCommand::List)?; self.transport.send_sync_request(&SyncCommand::List)?;
self.handle_list_command(path) self.handle_list_command(path)
} }
// This command does not seem to work correctly. The devices I test it on just resturn fn handle_list_command<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
// 'DONE' directly without listing anything. // TODO: use LIS2 to support files over 2.14 GB in size.
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> { // SEE: https://github.com/cstyan/adbDocumentation?tab=readme-ov-file#adb-list
let mut len_buf = [0_u8; 4]; let mut len_buf = [0_u8; 4];
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?); LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
@@ -36,6 +37,8 @@ impl ADBServerDevice {
.get_raw_connection()? .get_raw_connection()?
.write_all(path.as_ref().to_string().as_bytes())?; .write_all(path.as_ref().to_string().as_bytes())?;
let mut list_items = Vec::new();
// Reads returned status code from ADB server // Reads returned status code from ADB server
let mut response = [0_u8; 4]; let mut response = [0_u8; 4];
loop { loop {
@@ -44,25 +47,36 @@ impl ADBServerDevice {
.read_exact(&mut response)?; .read_exact(&mut response)?;
match str::from_utf8(response.as_ref())? { match str::from_utf8(response.as_ref())? {
"DENT" => { "DENT" => {
// TODO: Move this to a struct that extract this data, but as the device
// I test this on does not return anything, I can't test it.
let mut file_mod = [0_u8; 4];
let mut file_size = [0_u8; 4];
let mut mod_time = [0_u8; 4];
let mut name_len = [0_u8; 4];
let mut connection = self.transport.get_raw_connection()?; let mut connection = self.transport.get_raw_connection()?;
connection.read_exact(&mut file_mod)?;
connection.read_exact(&mut file_size)?;
connection.read_exact(&mut mod_time)?;
connection.read_exact(&mut name_len)?;
let name_len = LittleEndian::read_u32(&name_len); let mode = connection.read_u32::<LittleEndian>()?;
let size = connection.read_u32::<LittleEndian>()?;
let time = connection.read_u32::<LittleEndian>()?;
let name_len = connection.read_u32::<LittleEndian>()?;
let mut name_buf = vec![0_u8; name_len as usize]; let mut name_buf = vec![0_u8; name_len as usize];
connection.read_exact(&mut name_buf)?; connection.read_exact(&mut name_buf)?;
let name = String::from_utf8(name_buf)?;
// First 9 bits are the file permissions
let permissions = mode & 0b1_1111_1111;
// Bits 14 to 16 are the file type
let item_type = match (mode >> 13) & 0b111 {
0b010 => ADBListItemType::Directory,
0b100 => ADBListItemType::File,
0b101 => ADBListItemType::Symlink,
type_code => return Err(RustADBError::UnknownFileMode(type_code)),
};
let entry = ADBListItem {
item_type,
name,
time,
size,
permissions,
};
list_items.push(entry);
} }
"DONE" => { "DONE" => {
return Ok(()); return Ok(list_items);
} }
x => log::error!("Got an unknown response {x}"), x => log::error!("Got an unknown response {x}"),
} }

View File

@@ -72,7 +72,7 @@ impl ADBServerDevice {
self.transport.send_adb_request(AdbServerCommand::Sync)?; self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a recv command // Send a recv command
self.transport.send_sync_request(SyncCommand::Recv)?; self.transport.send_sync_request(&SyncCommand::Recv)?;
self.handle_recv_command(path, stream) self.handle_recv_command(path, stream)
} }

View File

@@ -50,7 +50,7 @@ impl ADBServerDevice {
self.transport.send_adb_request(AdbServerCommand::Sync)?; self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a send command // Send a send command
self.transport.send_sync_request(SyncCommand::Send)?; self.transport.send_sync_request(&SyncCommand::Send)?;
self.handle_send_command(stream, path) self.handle_send_command(stream, path)
} }

View File

@@ -44,7 +44,7 @@ impl ADBServerDevice {
self.transport.send_adb_request(AdbServerCommand::Sync)?; self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a "Stat" command // Send a "Stat" command
self.transport.send_sync_request(SyncCommand::Stat)?; self.transport.send_sync_request(&SyncCommand::Stat)?;
self.handle_stat_command(path) self.handle_stat_command(path)
} }

View File

@@ -16,6 +16,7 @@ pub struct TCPEmulatorTransport {
impl TCPEmulatorTransport { impl TCPEmulatorTransport {
/// Instantiates a new instance of [`TCPEmulatorTransport`] /// Instantiates a new instance of [`TCPEmulatorTransport`]
#[must_use]
pub fn new(socket_addr: SocketAddrV4) -> Self { pub fn new(socket_addr: SocketAddrV4) -> Self {
Self { Self {
socket_addr, socket_addr,
@@ -48,11 +49,11 @@ impl TCPEmulatorTransport {
/// Send an authenticate request to this emulator /// Send an authenticate request to this emulator
pub fn authenticate(&mut self) -> Result<()> { pub fn authenticate(&mut self) -> Result<()> {
let token = self.get_authentication_token()?; let token = self.get_authentication_token()?;
self.send_command(ADBEmulatorCommand::Authenticate(token)) self.send_command(&ADBEmulatorCommand::Authenticate(token))
} }
/// Send an [`ADBEmulatorCommand`] to this emulator /// Send an [`ADBEmulatorCommand`] to this emulator
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> { pub(crate) fn send_command(&mut self, command: &ADBEmulatorCommand) -> Result<()> {
let mut connection = self.get_raw_connection()?; let mut connection = self.get_raw_connection()?;
// Send command // Send command

View File

@@ -34,6 +34,7 @@ impl TCPServerTransport {
} }
/// Instantiate a new instance of [`TCPServerTransport`] using given address, or default if not specified. /// Instantiate a new instance of [`TCPServerTransport`] using given address, or default if not specified.
#[must_use]
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self { pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
match socket_addr { match socket_addr {
Some(s) => Self::new(s), Some(s) => Self::new(s),
@@ -42,6 +43,7 @@ impl TCPServerTransport {
} }
/// Get underlying [`SocketAddrV4`] /// Get underlying [`SocketAddrV4`]
#[must_use]
pub fn get_socketaddr(&self) -> SocketAddrV4 { pub fn get_socketaddr(&self) -> SocketAddrV4 {
self.socket_addr self.socket_addr
} }
@@ -90,7 +92,7 @@ impl TCPServerTransport {
} }
/// Send the given [`SyncCommand`] to ADB server, and checks that the request has been taken in consideration. /// Send the given [`SyncCommand`] to ADB server, and checks that the request has been taken in consideration.
pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> { pub(crate) fn send_sync_request(&mut self, command: &SyncCommand) -> Result<()> {
// First 4 bytes are the name of the command we want to send // First 4 bytes are the name of the command we want to send
// (e.g. "SEND", "RECV", "STAT", "LIST") // (e.g. "SEND", "RECV", "STAT", "LIST")
Ok(self Ok(self

View File

@@ -32,10 +32,11 @@ impl USBTransport {
/// Only the first device with given `vendor_id` and `product_id` is returned. /// Only the first device with given `vendor_id` and `product_id` is returned.
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> { pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
for device in rusb::devices()?.iter() { for device in rusb::devices()?.iter() {
if let Ok(descriptor) = device.device_descriptor() { if let Ok(descriptor) = device.device_descriptor()
if descriptor.vendor_id() == vendor_id && descriptor.product_id() == product_id { && descriptor.vendor_id() == vendor_id
return Ok(Self::new_from_device(device)); && descriptor.product_id() == product_id
} {
return Ok(Self::new_from_device(device));
} }
} }
@@ -47,6 +48,7 @@ impl USBTransport {
/// Instantiate a new [`USBTransport`] from a [`rusb::Device`]. /// Instantiate a new [`USBTransport`] from a [`rusb::Device`].
/// ///
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device. /// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
#[must_use]
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self { pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
Self { Self {
device: rusb_device, device: rusb_device,

View File

@@ -3,13 +3,13 @@ use std::{ffi::OsStr, path::Path};
use crate::{Result, RustADBError}; use crate::{Result, RustADBError};
pub fn check_extension_is_apk<P: AsRef<Path>>(path: P) -> Result<()> { pub fn check_extension_is_apk<P: AsRef<Path>>(path: P) -> Result<()> {
if let Some(extension) = path.as_ref().extension() { if let Some(extension) = path.as_ref().extension()
if ![OsStr::new("apk")].contains(&extension) { && ![OsStr::new("apk")].contains(&extension)
return Err(RustADBError::WrongFileExtension(format!( {
"{} is not an APK file", return Err(RustADBError::WrongFileExtension(format!(
extension.to_string_lossy() "{} is not an APK file",
))); extension.to_string_lossy()
} )));
} }
log::debug!("Given file is an APK"); log::debug!("Given file is an APK");

View File

@@ -22,6 +22,6 @@ name = "stub_gen"
[dependencies] [dependencies]
adb_client = { path = "../adb_client" } adb_client = { path = "../adb_client" }
anyhow = { version = "1.0.100" } anyhow = { version = "1.0.100" }
pyo3 = { version = "0.27.1", features = ["abi3-py310", "anyhow"] } pyo3 = { version = "0.27.2", features = ["abi3-py310", "anyhow"] }
pyo3-stub-gen = { version = "0.17.0" } pyo3-stub-gen = { version = "0.17.2" }
pyo3-stub-gen-derive = { version = "0.17.0" } pyo3-stub-gen-derive = { version = "0.17.2" }

View File

@@ -12,6 +12,7 @@ pub struct PyADBServerDevice(pub ADBServerDevice);
#[gen_stub_pymethods] #[gen_stub_pymethods]
#[pymethods] #[pymethods]
impl PyADBServerDevice { impl PyADBServerDevice {
#[must_use]
#[getter] #[getter]
/// Device identifier /// Device identifier
pub fn identifier(&self) -> Option<String> { pub fn identifier(&self) -> Option<String> {

View File

@@ -21,6 +21,7 @@ impl PyADBUSBDevice {
} }
/// Run shell commands on device and return the output (stdout + stderr merged) /// Run shell commands on device and return the output (stdout + stderr merged)
#[expect(clippy::needless_pass_by_value)]
pub fn shell_command(&mut self, commands: Vec<String>) -> Result<Vec<u8>> { pub fn shell_command(&mut self, commands: Vec<String>) -> Result<Vec<u8>> {
let mut output = Vec::new(); let mut output = Vec::new();
let commands: Vec<&str> = commands.iter().map(|x| &**x).collect(); let commands: Vec<&str> = commands.iter().map(|x| &**x).collect();
@@ -41,6 +42,7 @@ impl PyADBUSBDevice {
} }
/// Install a package installed on the device /// Install a package installed on the device
#[expect(clippy::needless_pass_by_value)]
pub fn install(&mut self, apk_path: PathBuf) -> Result<()> { pub fn install(&mut self, apk_path: PathBuf) -> Result<()> {
Ok(self.0.install(&apk_path)?) Ok(self.0.install(&apk_path)?)
} }

View File

@@ -12,12 +12,14 @@ pub struct PyDeviceShort(DeviceShort);
#[gen_stub_pymethods] #[gen_stub_pymethods]
#[pymethods] #[pymethods]
impl PyDeviceShort { impl PyDeviceShort {
#[must_use]
#[getter] #[getter]
/// Device identifier /// Device identifier
pub fn identifier(&self) -> String { pub fn identifier(&self) -> String {
self.0.identifier.clone() self.0.identifier.clone()
} }
#[must_use]
#[getter] #[getter]
/// Device state /// Device state
pub fn state(&self) -> String { pub fn state(&self) -> String {