25 Commits

Author SHA1 Message Date
cocool97
e2e1ae1202 Merge pull request #156 from cocool97/mdns-feature
feat(mdns): add feature flag + example
2025-12-26 12:24:00 +01:00
Corentin LIAUD
4f26ebfe29 fix: improve workflow 2025-12-26 12:19:44 +01:00
Corentin LIAUD
2a7c9bdc57 feat(mdns): add feature flag + example 2025-12-26 12:09:02 +01:00
Corentin LIAUD
d06b157255 chore: clippy improvements 2025-12-26 11:19:46 +01:00
Corentin LIAUD
947964163b fix(adb_client): image crate had no output format by default 2025-12-26 11:12:32 +01:00
Corentin LIAUD
5075e09d0e chore(adb_cli): improve error message in case of error 2025-12-26 11:12:08 +01:00
cocool97
f1d3f8d5f2 Merge pull request #155 from cocool97/sessions
feat: Track individual sessions (local and remote id) for each operation
2025-12-26 10:57:31 +01:00
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
62 changed files with 874 additions and 310 deletions

View File

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

View File

@@ -36,10 +36,10 @@ jobs:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-linux
run: cp target/release/adb_cli target/release/adb_cli-linux
- name: Build DEB package
run: cargo deb -p adb_cli
@@ -69,10 +69,10 @@ jobs:
override: true
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-macos
run: cp target/release/adb_cli target/release/adb_cli-macos
- name: Upload macOS binary
uses: softprops/action-gh-release@v2
@@ -98,7 +98,7 @@ jobs:
python-version: "3.10"
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe

View File

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

View File

@@ -42,6 +42,12 @@ Rust library implementing both ADB protocols (server and end-devices) and provid
Improved documentation available [here](./adb_client/README.md).
## examples
Some examples showing of to use this library are available in the `examples` directory:
- `examples/mdns`: mDNS device discovery
## adb_cli
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.

View File

@@ -11,11 +11,10 @@ rust-version.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "^2.1.17" }
anyhow = { version = "1.0.100" }
clap = { version = "4.5.51", features = ["derive"] }
adb_client = { version = "^2.1.19", features = ["mdns"] }
clap = { version = "4.5.53", features = ["derive"] }
env_logger = { version = "0.11.8" }
log = { version = "0.4.28" }
log = { version = "0.4.29" }
[target.'cfg(unix)'.dependencies]
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)
![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 crate::Result;
use crate::models::{ADBCliError, ADBCliResult};
pub struct ADBTermios {
fd: RawFd,
@@ -13,7 +13,7 @@ pub struct 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 old_termios = new_termios; // Saves previous state
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)?)
}
}

View File

@@ -1,8 +1,8 @@
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)?;
match emulator_command.command {

View File

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

View File

@@ -8,13 +8,13 @@ mod models;
mod utils;
use adb_client::{
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService,
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
mdns::MDNSDiscoveryService,
};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use adb_termios::ADBTermios;
use anyhow::Result;
use clap::Parser;
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
@@ -22,89 +22,13 @@ use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::ExitCode;
use utils::setup_logger;
fn main() -> Result<()> {
// This depends on `clap`
let opts = Opts::parse();
use crate::models::{ADBCliError, ADBCliResult};
// SAFETY:
// We are assuming the entire process is single-threaded
// 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 {
fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> ADBCliResult<()> {
match command {
DeviceCommands::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
@@ -162,7 +86,116 @@ fn main() -> Result<()> {
device.framebuffer(&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(())
}
fn main() -> ExitCode {
if let Err(err) = inner_main() {
log::error!("{err}");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
fn inner_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 fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
device.fullname,
device.ipv4_addresses(),
device.ipv6_addresses()
);
}
return Ok(service.shutdown()?);
}
};
run_command(device, commands)?;
Ok(())
}

View File

@@ -0,0 +1,84 @@
use std::fmt::Display;
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 Display 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"Error: {error}
An unexpected error occurred and may indicate a bug.
Please report this issue on the project repository (including steps to reproduce if possible): https://github.com/cocool97/adb_client/issues.",
)
}
}
}
}
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
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 clap::Parser;
@@ -6,7 +6,7 @@ use clap::Parser;
fn parse_wait_for_device_device_transport(
value: &str,
) -> Result<WaitForDeviceTransport, RustADBError> {
WaitForDeviceTransport::try_from(value)
WaitForDeviceTransport::from_str(value)
}
#[derive(Parser, Debug)]

View File

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

View File

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

View File

@@ -1,14 +1,9 @@
/// # Safety
///
/// 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" };
use env_logger::{Builder, Env};
unsafe { std::env::set_var("RUST_LOG", level) };
}
env_logger::init();
/// Sets up appropriate logger level:
/// - if `RUST_LOG` environment variable is set, use its value
/// - else, use `debug` CLI option
pub fn setup_logger(debug: bool) {
Builder::from_env(Env::default().default_filter_or(if debug { "debug" } else { "info" }))
.init();
}

View File

@@ -10,31 +10,43 @@ repository.workspace = true
rust-version.workspace = true
version.workspace = true
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[features]
default = []
mdns = ["dep:mdns-sd"]
[dependencies]
base64 = { version = "0.22.1" }
bincode = { version = "2.0.1", features = ["serde"] }
byteorder = { version = "1.5.0" }
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
image = { version = "0.25.8", default-features = false }
log = { version = "0.4.28" }
mdns-sd = { version = "0.17.0", default-features = false, features = [
"logging",
] }
num-bigint = { version = "0.8.5", package = "num-bigint-dig" }
image = { version = "0.25.9", default-features = false, features = ["png"] }
log = { version = "0.4.29" }
num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
rand = { version = "0.9.2" }
rcgen = { version = "0.14.5" }
rcgen = { version = "0.14.6" }
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"] }
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_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.17" }
#########
# `mdns` feature-specific dependencies
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
], optional = true }
#########
[dev-dependencies]
anyhow = { version = "1.0.100" }
criterion = { version = "0.7.0" } # Used for benchmarks

View File

@@ -1,4 +1,4 @@
# adb_client
# `adb_client`
[![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)
@@ -16,6 +16,19 @@ Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
adb_client = "*"
```
## Crate features
| Feature | Description | Default? |
| :-----: | :---------------------------------------------: | :------: |
| `mdns` | Enables mDNS device discovery on local network. | No |
To deactivate some default features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
```toml
[dependencies]
adb_client = { version = "*", default-features = false, features = ["mdns"] }
```
## Benchmarks
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
@@ -24,11 +37,11 @@ Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel
`ADBServerDevice` performs all operations by using adb server as a bridge.
|File size|Sample size|`ADBServerDevice`|`adb`|Difference|
|:-------:|:---------:|:----------:|:---:|:-----:|
|10 MB|100|350,79 ms|356,30 ms|<div style="color:green">-1,57 %</div>|
|500 MB|50|15,60 s|15,64 s|<div style="color:green">-0,25 %</div>|
|1 GB|20|31,09 s|31,12 s|<div style="color:green">-0,10 %</div>|
| File size | Sample size | `ADBServerDevice` | `adb` | Difference |
| :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
| 10 MB | 100 | 350,79 ms | 356,30 ms | <div style="color:green">-1,57 %</div> |
| 500 MB | 50 | 15,60 s | 15,64 s | <div style="color:green">-0,25 %</div> |
| 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |
## Examples

View File

@@ -4,7 +4,7 @@ use std::path::Path;
use image::{ImageBuffer, ImageFormat, Rgba};
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`]
pub trait ADBDeviceExt {
@@ -24,6 +24,9 @@ pub trait ADBDeviceExt {
/// Push `stream` to `path` on the device.
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
fn reboot(&mut self, reboot_type: RebootType) -> Result<()>;
@@ -47,7 +50,9 @@ pub trait ADBDeviceExt {
/// Inner method requesting framebuffer from an Android device
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>>;
/// Dump framebuffer of this device into given path
/// Dump framebuffer of this device into given path.
///
/// Output data format is currently only `PNG`.
fn framebuffer(&mut self, path: &dyn AsRef<Path>) -> Result<()> {
// Big help from AOSP source code (<https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp>)
let img = self.framebuffer_inner()?;

View File

@@ -1,5 +1,6 @@
use super::{ADBRsaKey, ADBTransportMessage, MessageCommand, models::MessageSubcommand};
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 bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
use byteorder::ReadBytesExt;
@@ -27,18 +28,12 @@ pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -
#[derive(Debug)]
pub struct ADBMessageDevice<T: ADBMessageTransport> {
transport: T,
local_id: Option<u32>,
remote_id: Option<u32>,
}
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Instantiate a new [`ADBMessageTransport`]
pub fn new(transport: T) -> Self {
Self {
transport,
local_id: None,
remote_id: None,
}
Self { transport }
}
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
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()?;
self.transport.write_message(ADBTransportMessage::new(
MessageCommand::Okay,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
&[],
))?;
Ok(message)
@@ -136,11 +134,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn recv_file<W: std::io::Write>(
&mut self,
session: ADBSession,
mut output: W,
) -> std::result::Result<(), RustADBError> {
let mut len: Option<u64> = None;
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);
while rdr.position() != payload.len() as u64 {
match len.take() {
@@ -173,8 +172,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push_file<R: std::io::Read>(
&mut self,
local_id: u32,
remote_id: u32,
session: ADBSession,
mut reader: R,
) -> std::result::Result<(), RustADBError> {
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
@@ -186,8 +184,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
session.local_id(),
session.remote_id(),
&serialized_message,
);
@@ -204,8 +202,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
session.local_id(),
session.remote_id(),
&serialized_message,
);
@@ -230,8 +228,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
session.local_id(),
session.remote_id(),
&serialized_message,
);
@@ -244,24 +242,27 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
}
}
pub(crate) fn begin_synchronization(&mut self) -> Result<()> {
self.open_session(b"sync:\0")?;
Ok(())
pub(crate) fn begin_synchronization(&mut self) -> Result<ADBSession> {
self.open_session(b"sync:\0")
}
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 message = ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
&bincode_serialize_to_vec(&stat_buffer)?,
);
self.send_and_expect_okay(message)?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
remote_path.as_bytes(),
))?;
let response = self.transport.read_message()?;
@@ -271,24 +272,25 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
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);
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
&bincode_serialize_to_vec(&quit_buffer)?,
))?;
let _discard_close = self.transport.read_message()?;
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 local_id: u32 = rng.random();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.random(), // Our 'local-id'
local_id, // Our 'local-id'
0,
data,
);
@@ -296,21 +298,20 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let response = self.get_transport_mut().read_message()?;
self.local_id = Some(response.header().arg1());
self.remote_id = Some(response.header().arg0());
if response.header().command() != MessageCommand::Okay {
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> {
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(),
))
Ok(ADBSession::new(local_id, response.header().arg0()))
}
}

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

View File

@@ -110,12 +110,12 @@ impl ADBUSBDevice {
}
/// 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,
product_id: u16,
private_key_path: PathBuf,
private_key_path: P,
) -> 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.
@@ -131,16 +131,16 @@ impl ADBUSBDevice {
Self::new_from_transport_inner(transport, &private_key_path)
}
fn new_from_transport_inner(
fn new_from_transport_inner<P: AsRef<Path>>(
transport: USBTransport,
private_key_path: &PathBuf,
private_key_path: P,
) -> 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
} else {
log::warn!(
"No private key found at path {}. Using a temporary random one.",
private_key_path.display()
private_key_path.as_ref().display()
);
ADBRsaKey::new_random()?
};
@@ -247,6 +247,10 @@ impl ADBDeviceExt for ADBUSBDevice {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner()
}
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
self.inner.list(path)
}
}
impl Drop for ADBUSBDevice {

View File

@@ -11,9 +11,9 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
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());
@@ -36,7 +36,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
break;
}
let response = self.recv_and_reply_okay()?;
let response = self.recv_and_reply_okay(session)?;
framebuffer_data.extend_from_slice(&response.into_payload());
@@ -69,7 +69,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
break;
}
let response = self.recv_and_reply_okay()?;
let response = self.recv_and_reply_okay(session)?;
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();
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 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)?;

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, u32::try_from(path.as_ref().len())?);
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 install;
mod list;
mod pull;
mod push;
mod reboot;

View File

@@ -11,10 +11,10 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
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 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 {
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(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]),
ADBTransportMessage::new(
MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
),
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)?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
&recv_buffer,
))?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
source.as_bytes(),
))?;
self.recv_file(output)?;
self.end_transaction()?;
self.recv_file(session, output)?;
self.end_transaction(session)?;
Ok(())
}
}

View File

@@ -10,7 +10,7 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
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());
@@ -20,14 +20,13 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
self.get_local_id()?,
self.get_remote_id()?,
session.local_id(),
session.remote_id(),
&send_buffer,
))?;
self.push_file(self.get_local_id()?, self.get_remote_id()?, stream)?;
self.end_transaction()?;
self.push_file(session, stream)?;
self.end_transaction(session)?;
Ok(())
}

View File

@@ -1,4 +1,5 @@
use std::io::{ErrorKind, Read, Write};
use std::time::Duration;
use crate::Result;
use crate::device::ShellMessageWriter;
@@ -10,24 +11,35 @@ use crate::{
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// 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<()> {
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 {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong command {}",
response.header().command()
)));
}
let mut transport = self.get_transport().clone();
loop {
let response = self.get_transport_mut().read_message()?;
if response.header().command() != MessageCommand::Write {
let message = transport.read_message()?;
let command = message.header().command();
if command == MessageCommand::Clse {
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(())
}
@@ -38,21 +50,22 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
mut reader: &mut dyn Read,
mut writer: Box<dyn Write + Send>,
) -> Result<()> {
self.open_session(b"shell:\0")?;
let session = self.open_session(b"shell:\0")?;
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
std::thread::spawn(move || -> Result<()> {
loop {
let message = transport.read_message()?;
// Acknowledge for more data
let response =
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]);
let response = ADBTransportMessage::new(
MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
);
transport.write_message(response)?;
match message.header().command() {
@@ -67,7 +80,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
});
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
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> {
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
self.begin_synchronization()?;
let adb_stat_response = self.stat_with_explicit_ids(remote_path)?;
self.end_transaction()?;
let session = self.begin_synchronization()?;
let adb_stat_response = self.stat_with_explicit_ids(session, remote_path)?;
self.end_transaction(session)?;
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_session;
mod message_commands;
pub use adb_rsa_key::ADBRsaKey;
pub(crate) use adb_session::ADBSession;
pub use message_commands::{MessageCommand, MessageSubcommand};

View File

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

View File

@@ -115,14 +115,19 @@ pub enum RustADBError {
#[error("upgrade error: {0}")]
UpgradeError(String),
/// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)]
MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
#[error("error sending data to channel")]
SendError,
/// An unknown transport has been provided
#[error("unknown transport: {0}")]
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 {

View File

@@ -3,13 +3,23 @@
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
// Feature `doc_cfg` is currently only available on nightly builds.
// It is activated when cfg `docsrs` is enabled.
// Documentation can be build locally using:
// `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features`
#![cfg_attr(docsrs, feature(doc_cfg))]
mod adb_device_ext;
mod constants;
mod device;
mod emulator_device;
mod error;
mod mdns;
/// MDNS-related definitions
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub mod mdns;
mod models;
mod server;
mod server_device;
@@ -20,8 +30,7 @@ pub use adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError};
pub use mdns::*;
pub use models::{AdbStatResponse, RebootType};
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use server::*;
pub use server_device::ADBServerDevice;
pub use transports::*;

View File

@@ -1,4 +1,8 @@
use std::{collections::HashSet, net::IpAddr};
use std::{
collections::HashSet,
fmt::Display,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
use mdns_sd::{ResolvedService, ScopedIp};
@@ -8,7 +12,41 @@ pub struct MDNSDevice {
/// Full device address when resolved
pub fullname: String,
/// Device IP addresses
pub addresses: HashSet<IpAddr>,
addresses: HashSet<IpAddr>,
}
impl MDNSDevice {
/// Return all adresses linked to this device
#[must_use]
pub fn addresses(&self) -> HashSet<IpAddr> {
self.addresses.clone()
}
/// Return all IPv4 addresses linked to this device
#[must_use]
pub fn ipv4_addresses(&self) -> HashSet<Ipv4Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(addr) => Some(addr),
IpAddr::V6(_) => None,
})
.copied()
.collect()
}
/// Return all IPv6 addresses linked to this device
#[must_use]
pub fn ipv6_addresses(&self) -> HashSet<Ipv6Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(_) => None,
IpAddr::V6(addr) => Some(addr),
})
.copied()
.collect()
}
}
impl From<Box<ResolvedService>> for MDNSDevice {
@@ -19,3 +57,13 @@ impl From<Box<ResolvedService>> for MDNSDevice {
}
}
}
impl Display for MDNSDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Device fullname: {}", self.fullname)?;
writeln!(f, "IPv4 Addresses: {:?}", self.ipv4_addresses())?;
write!(f, "IPv6 Addresses: {:?}", self.ipv6_addresses())?;
Ok(())
}
}

View File

@@ -1,7 +1,8 @@
use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle};
use crate::{MDNSDevice, Result, RustADBError};
use super::MDNSDevice;
use crate::{Result, RustADBError};
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
@@ -29,7 +30,7 @@ impl MDNSDiscoveryService {
})
}
/// Start discovery by spawning a new thread responsible of getting events.
/// Start discovery by spawning a new background thread responsible of getting events.
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
@@ -44,9 +45,9 @@ impl MDNSDiscoveryService {
// Ignoring these events. We are only interesting in found devices
}
ServiceEvent::ServiceResolved(service_info) => {
if let Err(e) = sender.send(MDNSDevice::from(service_info)) {
return Err(e.into());
}
sender
.send(MDNSDevice::from(service_info))
.map_err(|_| RustADBError::SendError)?;
}
e => {
log::warn!("received unknown event type {e:?}");

View File

@@ -26,7 +26,7 @@ pub(crate) enum AdbServerCommand {
Install(u64),
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
// Local commands
ShellCommand(String),
ShellCommand(String, Vec<String>),
Shell,
FrameBuffer,
Sync,
@@ -51,10 +51,14 @@ impl Display for AdbServerCommand {
AdbServerCommand::TrackDevices => write!(f, "host:track-devices"),
AdbServerCommand::TransportAny => write!(f, "host:transport-any"),
AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"),
AdbServerCommand::ShellCommand(command) => match std::env::var("TERM") {
Ok(term) => write!(f, "shell,TERM={term},raw:{command}"),
Err(_) => write!(f, "shell,raw:{command}"),
},
AdbServerCommand::ShellCommand(command, args) => {
let args_s = args.join(",");
write!(
f,
"shell{}{args_s},raw:{command}",
if args.is_empty() { "" } else { "," }
)
}
AdbServerCommand::Shell => match std::env::var("TERM") {
Ok(term) => write!(f, "shell,TERM={term},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 framebuffer_info;
mod host_features;
mod list_info;
mod reboot_type;
mod sync_command;
@@ -11,5 +12,6 @@ pub(crate) use adb_server_command::AdbServerCommand;
pub use adb_stat_response::AdbStatResponse;
pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2};
pub use host_features::HostFeatures;
pub use list_info::{ADBListItem, ADBListItemType};
pub use reboot_type::RebootType;
pub use sync_command::SyncCommand;

View File

@@ -22,6 +22,7 @@ pub struct ADBServer {
impl ADBServer {
/// Instantiates a new [`ADBServer`]
#[must_use]
pub fn new(address: SocketAddrV4) -> Self {
Self {
transport: None,
@@ -32,6 +33,7 @@ impl ADBServer {
}
/// Instantiates a new [`ADBServer`] with a custom adb path
#[must_use]
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
Self {
transport: None,

View File

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

View File

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

View File

@@ -12,6 +12,7 @@ pub struct ADBServerDevice {
impl ADBServerDevice {
/// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
#[must_use]
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr);
@@ -22,6 +23,7 @@ impl ADBServerDevice {
}
/// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
#[must_use]
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr);

View File

@@ -22,8 +22,24 @@ impl ADBDeviceExt for ADBServerDevice {
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
.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();
loop {
@@ -119,4 +135,8 @@ impl ADBDeviceExt for ADBServerDevice {
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
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::{
ADBServerDevice, Result,
models::{AdbServerCommand, SyncCommand},
ADBServerDevice, Result, RustADBError,
models::{ADBListItem, ADBListItemType, AdbServerCommand, SyncCommand},
};
use byteorder::{ByteOrder, LittleEndian};
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
use std::{
io::{Read, Write},
str,
@@ -10,21 +10,22 @@ use std::{
impl ADBServerDevice {
/// 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()?;
// Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a list command
self.transport.send_sync_request(SyncCommand::List)?;
self.transport.send_sync_request(&SyncCommand::List)?;
self.handle_list_command(path)
}
// This command does not seem to work correctly. The devices I test it on just resturn
// 'DONE' directly without listing anything.
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> {
fn handle_list_command<A: AsRef<str>>(&mut self, path: A) -> 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 = [0_u8; 4];
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
@@ -36,6 +37,8 @@ impl ADBServerDevice {
.get_raw_connection()?
.write_all(path.as_ref().to_string().as_bytes())?;
let mut list_items = Vec::new();
// Reads returned status code from ADB server
let mut response = [0_u8; 4];
loop {
@@ -44,25 +47,36 @@ impl ADBServerDevice {
.read_exact(&mut response)?;
match str::from_utf8(response.as_ref())? {
"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()?;
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];
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" => {
return Ok(());
return Ok(list_items);
}
x => log::error!("Got an unknown response {x}"),
}

View File

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

View File

@@ -4,7 +4,7 @@ use crate::{
};
use std::{
convert::TryInto,
io::{BufReader, BufWriter, Read, Write},
io::{self, BufReader, BufWriter, Read, Write},
str::{self, FromStr},
time::SystemTime,
};
@@ -22,7 +22,7 @@ impl<W: Write> ADBSendCommandWriter<W> {
impl<W: Write> Write for ADBSendCommandWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let chunk_len = buf.len() as u32;
let chunk_len = u32::try_from(buf.len()).map_err(io::Error::other)?;
// 8 = "DATA".len() + sizeof(u32)
let mut buffer = Vec::with_capacity(8 + buf.len());
@@ -50,7 +50,7 @@ impl ADBServerDevice {
self.transport.send_adb_request(AdbServerCommand::Sync)?;
// Send a send command
self.transport.send_sync_request(SyncCommand::Send)?;
self.transport.send_sync_request(&SyncCommand::Send)?;
self.handle_send_command(stream, path)
}

View File

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

View File

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

View File

@@ -26,6 +26,7 @@ impl Default for TCPServerTransport {
impl TCPServerTransport {
/// Instantiates a new instance of [`TCPServerTransport`]
#[must_use]
pub fn new(socket_addr: SocketAddrV4) -> Self {
Self {
socket_addr,
@@ -34,6 +35,7 @@ impl TCPServerTransport {
}
/// 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 {
match socket_addr {
Some(s) => Self::new(s),
@@ -42,6 +44,7 @@ impl TCPServerTransport {
}
/// Get underlying [`SocketAddrV4`]
#[must_use]
pub fn get_socketaddr(&self) -> SocketAddrV4 {
self.socket_addr
}
@@ -90,7 +93,7 @@ impl TCPServerTransport {
}
/// 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
// (e.g. "SEND", "RECV", "STAT", "LIST")
Ok(self

View File

@@ -32,10 +32,11 @@ impl USBTransport {
/// Only the first device with given `vendor_id` and `product_id` is returned.
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
for device in rusb::devices()?.iter() {
if let Ok(descriptor) = device.device_descriptor() {
if descriptor.vendor_id() == vendor_id && descriptor.product_id() == product_id {
return Ok(Self::new_from_device(device));
}
if let Ok(descriptor) = device.device_descriptor()
&& descriptor.vendor_id() == vendor_id
&& 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`].
///
/// 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 {
Self {
device: rusb_device,

View File

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

19
examples/mdns/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "mdns"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
keywords.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
rust-version.workspace = true
[[bin]]
name = "mdns"
path = "main.rs"
[dependencies]
adb_client = { path = "../../adb_client", default-features = false, features = [
"mdns",
] }

19
examples/mdns/main.rs Normal file
View File

@@ -0,0 +1,19 @@
use std::sync::mpsc;
use adb_client::mdns::{MDNSDevice, MDNSDiscoveryService};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting mDNS device discovery...");
// Create a channel to receive discovered devices information
let (sender, receiver) = mpsc::channel::<MDNSDevice>();
// Create and start the discovery service
let mut discovery = MDNSDiscoveryService::new()?;
discovery.start(sender)?;
loop {
let device = receiver.recv()?;
println!("{device}");
}
}

View File

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

View File

@@ -1,4 +1,4 @@
# pyadb_client
# `pyadb_client`
<p align="center">
<p align="center">Python library to communicate with ADB devices. Built on top of Rust adb_client library.</p>

View File

@@ -12,6 +12,7 @@ pub struct PyADBServerDevice(pub ADBServerDevice);
#[gen_stub_pymethods]
#[pymethods]
impl PyADBServerDevice {
#[must_use]
#[getter]
/// Device identifier
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)
#[expect(clippy::needless_pass_by_value)]
pub fn shell_command(&mut self, commands: Vec<String>) -> Result<Vec<u8>> {
let mut output = Vec::new();
let commands: Vec<&str> = commands.iter().map(|x| &**x).collect();
@@ -41,6 +42,7 @@ impl PyADBUSBDevice {
}
/// Install a package installed on the device
#[expect(clippy::needless_pass_by_value)]
pub fn install(&mut self, apk_path: PathBuf) -> Result<()> {
Ok(self.0.install(&apk_path)?)
}

View File

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