16 Commits

Author SHA1 Message Date
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
124 changed files with 1140 additions and 1279 deletions

View File

@@ -35,4 +35,4 @@ jobs:
with:
files: |
target/wheels/pyadb_client*.whl
target/wheels/pyadb_client*.tar.gz
target/wheels/pyadb_client*.tar.gz

View File

@@ -26,4 +26,4 @@ jobs:
python-version: "3.10"
- name: Build project
run: cargo build --release --features rusb,mdns
run: cargo build --release --all-features

View File

@@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- run: rustup component add clippy
- name: Run clippy
run: cargo clippy --features rusb,mdns
run: cargo clippy --all-features -- -Dwarnings
fmt:
name: "fmt"
@@ -33,7 +33,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Run doc
run: cargo doc --features rusb,mdns --no-deps
run: cargo doc --all-features --no-deps
env:
RUSTDOCFLAGS: "-D warnings"
@@ -43,4 +43,4 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Run tests
run: cargo test --verbose --features rusb,mdns
run: cargo test --verbose --all-features

View File

@@ -36,7 +36,7 @@ jobs:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
- name: Build release
run: cargo build -p adb_cli --release
run: cargo build --all-features --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-linux
@@ -69,7 +69,7 @@ jobs:
override: true
- name: Build release
run: cargo build -p adb_cli --release
run: cargo build --all-features --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-macos
@@ -98,7 +98,7 @@ jobs:
python-version: "3.10"
- name: Build release
run: cargo build -p adb_cli --release
run: cargo build --all-features --release
- name: Rename binary
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe

2
.gitignore vendored
View File

@@ -3,4 +3,4 @@ target
/.vscode
venv
/.mypy_cache
pyadb_client/pyadb_client.pyi
pyadb_client/pyadb_client.pyi

View File

@@ -1,5 +1,5 @@
[workspace]
members = ["adb_cli", "adb_client", "examples/mdns", "pyadb_client"]
members = ["adb_cli", "adb_client", "pyadb_client"]
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

@@ -49,12 +49,6 @@ Provides a "real-world" usage example of this library.
Improved documentation available [here](./adb_cli/README.md).
## examples
Some examples are available in the `examples` directory:
- `examples/mdns`: mDNS device discovery example
## pyadb_client
Python wrapper using `adb_client` library to export classes usable directly from a Python environment.

View File

@@ -11,11 +11,10 @@ rust-version.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "^2.1.17", features = ["mdns", "rusb"] }
anyhow = { version = "1.0.100" }
clap = { version = "4.5.51", features = ["derive"] }
adb_client = { version = "^2.1.18" }
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::emulator::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)?;
match emulator_command.command {

View File

@@ -1,7 +1,4 @@
use adb_client::{
Result,
server::{ADBServer, DeviceShort, MDNSBackend, WaitForDeviceState},
};
use adb_client::{ADBServer, DeviceShort, MDNSBackend, Result, WaitForDeviceState};
use crate::models::{HostCommand, MdnsCommand, ServerCommand};

View File

@@ -1,14 +1,13 @@
use std::{fs::File, io::Write};
use adb_client::server_device::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

@@ -7,17 +7,14 @@ mod handlers;
mod models;
mod utils;
use adb_client::ADBDeviceExt;
use adb_client::mdns::MDNSDiscoveryService;
use adb_client::server::ADBServer;
use adb_client::server_device::ADBServerDevice;
use adb_client::tcp::ADBTcpDevice;
use adb_client::usb::ADBRusbDevice;
use adb_client::{
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
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};
@@ -27,87 +24,10 @@ use std::io::Write;
use std::path::Path;
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) => ADBRusbDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBRusbDevice::new(vid, pid)?,
},
(None, None) => match usb_command.path_to_private_key {
Some(pk) => ADBRusbDevice::autodetect_with_custom_private_key(pk)?,
None => ADBRusbDevice::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.
@@ -165,7 +85,106 @@ 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() -> 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
path: String,
},
/// List files on device
List {
/// Path to list files from
path: String,
},
}

View File

@@ -1,12 +1,12 @@
use std::net::SocketAddrV4;
use std::{net::SocketAddrV4, str::FromStr};
use adb_client::{RustADBError, server::WaitForDeviceTransport};
use adb_client::{RustADBError, WaitForDeviceTransport};
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,57 +10,31 @@ 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"]
rusb = ["dep:rsa", "dep:rusb"]
webusb = ["dep:webusb-web", "dep:rsa"]
[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" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
image = { version = "0.25.9", default-features = false }
log = { version = "0.4.29" }
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
] }
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.8.5" }
rcgen = { version = "0.13.2", default-features = false, features = [
"pem",
"ring"
] }
rand = { version = "0.9.2" }
rcgen = { version = "0.14.6" }
regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
rustls = { version = "0.23.33", default-features = false, features = ["logging", "ring", "std", "tls12"] }
rustls-pki-types = { version = "1.12.0", features = ["web"] }
rsa = { version = "0.9.9" }
rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.35" }
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 dependencies
mdns-sd = { version = "0.17.0", default-features = false, features = [
"logging",
], optional = true }
#########
#########
# USB-only dependencies
rsa = { version = "0.9.7", optional = true }
rusb = { version = "0.9.4", features = ["vendored"], optional = true }
#########
#########
# webusb dependencies
webusb-web = { version = "0.4.1", optional = true }
getrandom = { version = "0.2.16", features = ["js"], optional = true }
ring = { version = "0.17.14", features = ["wasm32_unknown_unknown_js"], 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,26 +16,6 @@ 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 |
| `rusb` | Enables interactions with USB devices. | No |
To deactivate some 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 = "*" }
```
## Examples
Usage examples can be found in the `examples/` directory of this repository.
Some example are also provided in the various `README.md` files of modules.
## Benchmarks
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
@@ -44,8 +24,89 @@ 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
### Get available ADB devices
```rust no_run
use adb_client::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```
### Using ADB server as bridge
#### Launch a command on device
```rust no_run
use adb_client::{ADBServer, ADBDeviceExt};
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### Push a file to the device
```rust no_run
use adb_client::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```
### Interact directly with end devices
#### (USB) Launch a command on device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### (USB) Push a file to the device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
use std::fs::File;
use std::path::Path;
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, &"/data/local/tmp");
```
#### (TCP) Get a shell from device
```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use adb_client::{ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
```

View File

@@ -4,12 +4,9 @@ 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 an ADB device, currently used by:
/// - [`crate::server_device::ADBServerDevice`]
/// - [`crate::usb::ADBRusbDevice`]
/// - [`crate::tcp::ADBTcpDevice`]
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
pub trait ADBDeviceExt {
/// Runs command in a shell on the device, and write its output and error streams into output.
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
@@ -27,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<()>;

View File

@@ -0,0 +1 @@
pub const BUFFER_SIZE: usize = 65536;

View File

@@ -1,18 +1,14 @@
use crate::message_devices::adb_message_transport::ADBMessageTransport;
use crate::message_devices::adb_rsa_key::ADBRsaKey;
use crate::message_devices::adb_transport_message::ADBTransportMessage;
use crate::message_devices::message_commands::{MessageCommand, MessageSubcommand};
use crate::message_devices::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE};
use crate::{AUTH_TOKEN, AdbStatResponse, Result, RustADBError};
use super::{ADBRsaKey, ADBTransportMessage, MessageCommand, models::MessageSubcommand};
use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::{ADBMessageTransport, AdbStatResponse, Result, RustADBError, constants::BUFFER_SIZE};
use bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
use byteorder::ReadBytesExt;
use rand::Rng;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{Cursor, Read, Seek};
use std::time::Duration;
const BUFFER_SIZE: usize = 65535;
const BINCODE_CONFIG: Configuration<LittleEndian, Fixint, NoLimit> = bincode::config::legacy();
pub(crate) fn bincode_serialize_to_vec<E: Serialize>(val: E) -> Result<Vec<u8>> {
@@ -288,9 +284,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
}
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
let mut rng = rand::rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rand::random::<u32>(), // Our 'local-id'
rng.random(), // Our 'local-id'
0,
data,
);

View File

@@ -1,15 +1,11 @@
use crate::{
ADBDeviceExt, RebootType, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
},
models::AdbStatResponse,
};
use crate::{ADBDeviceExt, ADBMessageTransport, RebootType, Result, models::AdbStatResponse};
use std::{
io::{Read, Write},
path::Path,
};
use super::ADBMessageDevice;
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.shell_command(command, output)
@@ -46,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,18 +1,14 @@
use std::io::Write;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::{io::Read, net::SocketAddr};
use crate::message_devices::adb_message_device::ADBMessageDevice;
use crate::message_devices::adb_message_transport::ADBMessageTransport;
use crate::message_devices::adb_rsa_key::ADBRsaKey;
use crate::message_devices::adb_transport_message::ADBTransportMessage;
use crate::message_devices::message_commands::MessageCommand;
use crate::tcp::tcp_transport::TcpTransport;
use crate::usb::read_adb_private_key;
use crate::utils::get_default_adb_key_path;
use crate::{ADBDeviceExt, ADBTransport, Result};
use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand;
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,
@@ -26,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()?
};
@@ -140,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

@@ -1,9 +1,12 @@
use serde::{Deserialize, Serialize};
use crate::{
Result, RustADBError,
message_devices::{adb_message_device, message_commands::MessageCommand},
};
use crate::{Result, RustADBError, device::adb_message_device};
use super::models::MessageCommand;
pub const AUTH_TOKEN: u32 = 1;
pub const AUTH_SIGNATURE: u32 = 2;
pub const AUTH_RSAPUBLICKEY: u32 = 3;
#[derive(Debug)]
pub struct ADBTransportMessage {

View File

@@ -0,0 +1,261 @@
use rusb::Device;
use rusb::DeviceDescriptor;
use rusb::UsbContext;
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use std::fs::read_to_string;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand;
use super::{ADBRsaKey, ADBTransportMessage};
use crate::ADBDeviceExt;
use crate::ADBMessageTransport;
use crate::ADBTransport;
use crate::{Result, RustADBError, USBTransport};
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
// Try to read the private key file from given path
// If the file is not found, return None
// If there is another error while reading the file, return this error
// Else, return the private key content
let pk = match read_to_string(private_key_path.as_ref()) {
Ok(pk) => pk,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
match ADBRsaKey::new_from_pkcs8(&pk) {
Ok(pk) => Ok(Some(pk)),
Err(e) => Err(e),
}
}
/// Search for adb devices with known interface class and subclass values
pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
let mut found_devices = vec![];
for device in rusb::devices()?.iter() {
let Ok(des) = device.device_descriptor() else {
continue;
};
if is_adb_device(&device, &des) {
log::debug!(
"Autodetect device {:04x}:{:04x}",
des.vendor_id(),
des.product_id()
);
found_devices.push((des.vendor_id(), des.product_id()));
}
}
match (found_devices.first(), found_devices.get(1)) {
(None, _) => Ok(None),
(Some(identifiers), None) => Ok(Some(*identifiers)),
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
))),
}
}
/// Check whether a device with given descriptor is an ADB device
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
const ADB_SUBCLASS: u8 = 0x42;
const ADB_PROTOCOL: u8 = 0x1;
// Some devices require choosing the file transfer mode
// for usb debugging to take effect.
const BULK_CLASS: u8 = 0xdc;
const BULK_ADB_SUBCLASS: u8 = 2;
for n in 0..des.num_configurations() {
let Ok(config_des) = device.config_descriptor(n) else {
continue;
};
for interface in config_des.interfaces() {
for interface_des in interface.descriptors() {
let proto = interface_des.protocol_code();
let class = interface_des.class_code();
let subcl = interface_des.sub_class_code();
if proto == ADB_PROTOCOL
&& ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
{
return true;
}
}
}
}
false
}
pub fn get_default_adb_key_path() -> Result<PathBuf> {
std::env::home_dir()
.map(|home| home.join(".android").join("adbkey"))
.ok_or(RustADBError::NoHomeDirectory)
}
/// Represent a device reached and available over USB.
#[derive(Debug)]
pub struct ADBUSBDevice {
private_key: ADBRsaKey,
inner: ADBMessageDevice<USBTransport>,
}
impl ADBUSBDevice {
/// Instantiate a new [`ADBUSBDevice`]
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
}
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path
pub fn new_with_custom_private_key<P: AsRef<Path>>(
vendor_id: u16,
product_id: u16,
private_key_path: P,
) -> Result<Self> {
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.
pub fn new_from_transport(
transport: USBTransport,
private_key_path: Option<PathBuf>,
) -> Result<Self> {
let private_key_path = match private_key_path {
Some(private_key_path) => private_key_path,
None => get_default_adb_key_path()?,
};
Self::new_from_transport_inner(transport, &private_key_path)
}
fn new_from_transport_inner<P: AsRef<Path>>(
transport: USBTransport,
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.as_ref().display()
);
ADBRsaKey::new_random()?
};
let mut s = Self {
private_key,
inner: ADBMessageDevice::new(transport),
};
s.connect()?;
Ok(s)
}
/// autodetect connected ADB devices and establish a connection with the first device found
pub fn autodetect() -> Result<Self> {
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
}
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
match search_adb_devices()? {
Some((vendor_id, product_id)) => {
ADBUSBDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
}
_ => Err(RustADBError::DeviceNotFound(
"cannot find USB devices matching the signature of an ADB device".into(),
)),
}
}
/// Send initial connect
pub fn connect(&mut self) -> Result<()> {
self.get_transport_mut().connect()?;
let message = ADBTransportMessage::new(
MessageCommand::Cnxn,
0x0100_0000,
1_048_576,
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
// If the device returned CNXN instead of AUTH it does not require authentication,
// so we can skip the auth steps.
if message.header().command() == MessageCommand::Cnxn {
return Ok(());
}
message.assert_command(MessageCommand::Auth)?;
self.inner.auth_handshake(message, &self.private_key)
}
#[inline]
fn get_transport_mut(&mut self) -> &mut USBTransport {
self.inner.get_transport_mut()
}
}
impl ADBDeviceExt for ADBUSBDevice {
#[inline]
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.inner.shell_command(command, output)
}
#[inline]
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
#[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output)
}
#[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path)
}
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
#[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path)
}
#[inline]
fn uninstall(&mut self, package: &str) -> Result<()> {
self.inner.uninstall(package)
}
#[inline]
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 {
fn drop(&mut self) {
// Best effort here
let _ = self.get_transport_mut().disconnect();
}
}

View File

@@ -4,11 +4,8 @@ use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, Rgba};
use crate::{
Result, RustADBError,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
message_commands::MessageCommand,
},
ADBMessageTransport, Result, RustADBError,
device::{MessageCommand, adb_message_device::ADBMessageDevice},
models::{FrameBufferInfoV1, FrameBufferInfoV2},
};

View File

@@ -1,11 +1,8 @@
use std::{fs::File, path::Path};
use crate::{
Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
commands::utils::MessageWriter,
},
ADBMessageTransport, Result,
device::{MessageWriter, adb_message_device::ADBMessageDevice},
utils::check_extension_is_apk,
};

View File

@@ -0,0 +1,174 @@
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>> {
self.begin_synchronization()?;
let output = self.handle_list(path);
self.end_transaction()?;
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) -> 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 local_id = self.get_local_id()?;
let remote_id = self.get_remote_id()?;
{
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,9 +1,9 @@
mod framebuffer;
mod install;
mod list;
mod pull;
mod push;
mod reboot;
mod shell;
mod stat;
mod uninstall;
mod utils;

View File

@@ -1,12 +1,11 @@
use std::io::Write;
use crate::{
Result, RustADBError,
message_devices::{
ADBMessageTransport, Result, RustADBError,
device::{
ADBTransportMessage, MessageCommand,
adb_message_device::{self, ADBMessageDevice},
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
models::MessageSubcommand,
},
};

View File

@@ -1,12 +1,10 @@
use std::io::Read;
use crate::{
Result,
message_devices::{
ADBMessageTransport, Result,
device::{
ADBTransportMessage, MessageCommand, MessageSubcommand,
adb_message_device::{self, ADBMessageDevice},
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
},
};

View File

@@ -1,9 +1,6 @@
use crate::{
RebootType, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
message_commands::MessageCommand,
},
ADBMessageTransport, RebootType, Result,
device::{MessageCommand, adb_message_device::ADBMessageDevice},
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {

View File

@@ -1,12 +1,11 @@
use std::io::{ErrorKind, Read, Write};
use std::time::Duration;
use crate::Result;
use crate::device::ShellMessageWriter;
use crate::{
Result, RustADBError,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage, commands::utils::ShellMessageWriter,
message_commands::MessageCommand,
},
ADBMessageTransport, RustADBError,
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -14,6 +13,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
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 mut transport = self.get_transport().clone();
let local_id = self.get_local_id()?;
let remote_id = self.get_remote_id()?;
if response.header().command() != MessageCommand::Okay {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong command {}",
@@ -22,12 +26,30 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
}
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,
local_id,
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))
{
continue;
}
Ok(())

View File

@@ -1,8 +1,5 @@
use crate::{
AdbStatResponse, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
},
ADBMessageTransport, AdbStatResponse, Result, device::adb_message_device::ADBMessageDevice,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {

View File

@@ -1,9 +1,4 @@
use crate::{
Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
},
};
use crate::{ADBMessageTransport, Result, device::adb_message_device::ADBMessageDevice};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {

View File

@@ -1,9 +1,8 @@
use std::io::{Error, ErrorKind, Result, Write};
use crate::message_devices::{
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
message_commands::MessageCommand,
};
use crate::ADBMessageTransport;
use super::{ADBTransportMessage, MessageCommand};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic.
///

View File

@@ -0,0 +1,19 @@
mod adb_message_device;
mod adb_message_device_commands;
mod adb_tcp_device;
mod adb_transport_message;
mod adb_usb_device;
mod commands;
mod message_writer;
mod models;
mod shell_message_writer;
use adb_message_device::ADBMessageDevice;
pub use adb_tcp_device::ADBTcpDevice;
pub use adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader};
pub use adb_usb_device::{
ADBUSBDevice, get_default_adb_key_path, is_adb_device, search_adb_devices,
};
pub use message_writer::MessageWriter;
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
pub use shell_message_writer::ShellMessageWriter;

View File

@@ -0,0 +1,5 @@
mod adb_rsa_key;
mod message_commands;
pub use adb_rsa_key::ADBRsaKey;
pub use message_commands::{MessageCommand, MessageSubcommand};

View File

@@ -1,9 +1,8 @@
use std::io::Write;
use crate::message_devices::{
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
message_commands::MessageCommand,
};
use crate::ADBMessageTransport;
use super::{ADBTransportMessage, models::MessageCommand};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
pub struct ShellMessageWriter<T: ADBMessageTransport> {

View File

@@ -3,10 +3,7 @@ use std::{
sync::LazyLock,
};
use crate::{
ADBTransport, Result, RustADBError, emulator::tcp_emulator_transport::TCPEmulatorTransport,
server_device::ADBServerDevice,
};
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
use regex::Regex;
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {

View File

@@ -1,11 +1,8 @@
use crate::{
Result,
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
};
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

@@ -1,12 +1,9 @@
use crate::{
Result,
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
};
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

@@ -1,7 +1,5 @@
mod adb_emulator_device;
mod commands;
mod models;
mod tcp_emulator_transport;
pub use adb_emulator_device::ADBEmulatorDevice;
use models::ADBEmulatorCommand;
pub(crate) use models::ADBEmulatorCommand;

View File

@@ -70,8 +70,6 @@ pub enum RustADBError {
#[error("Cannot get home directory")]
NoHomeDirectory,
/// Generic USB error
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
#[error("USB Error: {0}")]
UsbError(#[from] rusb::Error),
/// USB device not found
@@ -90,8 +88,6 @@ pub enum RustADBError {
#[error(transparent)]
Base64EncodeError(#[from] base64::EncodeSliceError),
/// An error occurred with RSA engine
#[cfg(any(feature = "rusb", feature = "webusb"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
#[error(transparent)]
RSAError(#[from] rsa::errors::Error),
/// Cannot convert given data from slice
@@ -101,8 +97,6 @@ pub enum RustADBError {
#[error("wrong file extension: {0}")]
WrongFileExtension(String),
/// An error occurred with PKCS8 data
#[cfg(any(feature = "rusb", feature = "webusb"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
#[error("error with pkcs8: {0}")]
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
/// Error during certificate generation
@@ -121,16 +115,17 @@ 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("error sending data to channel")]
SendError,
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
/// 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,34 +3,25 @@
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
// Feature `doc_cfg` is currently only available on nightly.
// 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 adb_transport;
/// Emulator-related definitions
pub mod emulator;
mod constants;
mod device;
mod emulator_device;
mod error;
mod message_devices;
mod mdns;
mod models;
/// Server-related definitions
pub mod server;
/// Device reachable by the server related definitions
pub mod server_device;
mod server;
mod server_device;
mod transports;
mod utils;
/// MDNS-related definitions
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub mod mdns;
pub use adb_device_ext::ADBDeviceExt;
use adb_transport::ADBTransport;
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError};
pub use message_devices::*;
pub use models::{AdbStatResponse, HostFeatures, RebootType};
pub use mdns::*;
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use server::*;
pub use server_device::ADBServerDevice;
pub use transports::*;

View File

@@ -1,7 +1,7 @@
use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle};
use crate::{Result, RustADBError, mdns::MDNSDevice};
use crate::{MDNSDevice, Result, RustADBError};
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
@@ -44,9 +44,9 @@ impl MDNSDiscoveryService {
// Ignoring these events. We are only interesting in found devices
}
ServiceEvent::ServiceResolved(service_info) => {
return sender
.send(MDNSDevice::from(service_info))
.map_err(|_| RustADBError::SendError);
if let Err(e) = sender.send(MDNSDevice::from(service_info)) {
return Err(e.into());
}
}
e => {
log::warn!("received unknown event type {e:?}");

View File

@@ -1,4 +0,0 @@
mod message_writer;
mod shell_message_writer;
pub use message_writer::MessageWriter;
pub use shell_message_writer::ShellMessageWriter;

View File

@@ -1,17 +0,0 @@
/// USB-related definitions
pub mod usb;
/// Device reachable over TCP related definition
pub mod tcp;
pub(crate) const AUTH_TOKEN: u32 = 1;
pub(crate) const AUTH_SIGNATURE: u32 = 2;
pub(crate) const AUTH_RSAPUBLICKEY: u32 = 3;
mod adb_message_device;
mod adb_message_device_commands;
mod adb_message_transport;
mod adb_rsa_key;
mod adb_transport_message;
mod commands;
mod message_commands;

View File

@@ -1,13 +0,0 @@
# Examples
## Get a shell from device
```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use adb_client::{tcp::ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
```

View File

@@ -1,6 +0,0 @@
#![doc = include_str!("./README.md")]
mod adb_tcp_device;
mod tcp_transport;
pub use adb_tcp_device::ADBTcpDevice;

View File

@@ -1,26 +0,0 @@
# Examples
## Launch a command on device
```rust no_run
use adb_client::{usb::ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
## Push a file to the device
```rust no_run
use adb_client::{usb::ADBUSBDevice, ADBDeviceExt};
use std::fs::File;
use std::path::Path;
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
let mut input = File::open("/tmp/file.txt").expect("Cannot open file");
device.push(&mut input, &"/data/local/tmp");
```

View File

@@ -1,100 +0,0 @@
use std::{
io::{Read, Write},
path::{Path, PathBuf},
};
use crate::{
ADBDeviceExt, Result, RustADBError,
usb::{RusbTransport, adb_usb_device::ADBUSBDevice, search_adb_devices},
utils::get_default_adb_key_path,
};
/// Implement Android USB device reachable over wired USB
#[derive(Debug)]
pub struct ADBRusbDevice {
inner: ADBUSBDevice<RusbTransport>,
}
impl ADBRusbDevice {
/// Instantiate a new [`ADBRusbDevice`]
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
}
/// Instantiate a new [`ADBRusbDevice`] using a custom private key path
pub fn new_with_custom_private_key(
vendor_id: u16,
product_id: u16,
private_key_path: PathBuf,
) -> Result<Self> {
let transport = RusbTransport::new(vendor_id, product_id)?;
Ok(Self {
inner: ADBUSBDevice::new_from_transport(transport, Some(private_key_path))?,
})
}
/// autodetect connected ADB devices and establish a connection with the first device found
pub fn autodetect() -> Result<Self> {
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
}
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
match search_adb_devices()? {
Some((vendor_id, product_id)) => {
ADBRusbDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
}
_ => Err(RustADBError::DeviceNotFound(
"cannot find USB devices matching the signature of an ADB device".into(),
)),
}
}
}
impl ADBDeviceExt for ADBRusbDevice {
#[inline]
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.inner.shell_command(command, output)
}
#[inline]
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
#[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output)
}
#[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path)
}
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
#[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path)
}
#[inline]
fn uninstall(&mut self, package: &str) -> Result<()> {
self.inner.uninstall(package)
}
#[inline]
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner()
}
}

View File

@@ -1,187 +0,0 @@
use std::io::Read;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::ADBDeviceExt;
use crate::AUTH_TOKEN;
use crate::Result;
use crate::RustADBError;
use crate::message_devices::AUTH_RSAPUBLICKEY;
use crate::message_devices::AUTH_SIGNATURE;
use crate::message_devices::adb_message_device::ADBMessageDevice;
use crate::message_devices::adb_message_transport::ADBMessageTransport;
use crate::message_devices::adb_rsa_key::ADBRsaKey;
use crate::message_devices::adb_transport_message::ADBTransportMessage;
use crate::message_devices::message_commands::MessageCommand;
use crate::usb::read_adb_private_key;
use crate::utils::get_default_adb_key_path;
/// Private struct implementing Android USB device logic, depending on a `ADBMessageTransport`.
#[derive(Debug)]
pub(crate) struct ADBUSBDevice<T: ADBMessageTransport> {
private_key: ADBRsaKey,
inner: ADBMessageDevice<T>,
}
impl<T: ADBMessageTransport> ADBUSBDevice<T> {
/// Instantiate a new [`ADBUSBDevice`] from a [`RusbTransport`] and an optional private key path.
pub fn new_from_transport(transport: T, private_key_path: Option<PathBuf>) -> Result<Self> {
let private_key_path = match private_key_path {
Some(private_key_path) => private_key_path,
None => get_default_adb_key_path()?,
};
Self::new_from_transport_inner(transport, &private_key_path)
}
fn new_from_transport_inner(transport: T, private_key_path: &PathBuf) -> 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()
);
ADBRsaKey::new_random()?
};
let mut s = Self {
private_key,
inner: ADBMessageDevice::new(transport),
};
s.connect()?;
Ok(s)
}
/// Send initial connect
pub fn connect(&mut self) -> Result<()> {
self.get_transport_mut().connect()?;
let message = ADBTransportMessage::new(
MessageCommand::Cnxn,
0x0100_0000,
1_048_576,
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
// If the device returned CNXN instead of AUTH it does not require authentication,
// so we can skip the auth steps.
if message.header().command() == MessageCommand::Cnxn {
return Ok(());
}
message.assert_command(MessageCommand::Auth)?;
// At this point, we should have receive an AUTH message with arg0 == 1
let auth_message = match message.header().arg0() {
AUTH_TOKEN => message,
v => {
return Err(RustADBError::ADBRequestFailed(format!(
"Received AUTH message with type != 1 ({v})"
)));
}
};
let sign = self.private_key.sign(auth_message.into_payload())?;
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, &sign);
self.get_transport_mut().write_message(message)?;
let received_response = self.get_transport_mut().read_message()?;
if received_response.header().command() == MessageCommand::Cnxn {
log::info!(
"Authentication OK, device info {}",
String::from_utf8(received_response.into_payload())?
);
return Ok(());
}
let mut pubkey = self.private_key.android_pubkey_encode()?.into_bytes();
pubkey.push(b'\0');
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_RSAPUBLICKEY, 0, &pubkey);
self.get_transport_mut().write_message(message)?;
let response = self
.get_transport_mut()
.read_message_with_timeout(Duration::from_secs(10))
.and_then(|message| {
message.assert_command(MessageCommand::Cnxn)?;
Ok(message)
})?;
log::info!(
"Authentication OK, device info {}",
String::from_utf8(response.into_payload())?
);
Ok(())
}
#[inline]
pub(crate) fn get_transport_mut(&mut self) -> &mut T {
self.inner.get_transport_mut()
}
}
impl<T: ADBMessageTransport> ADBDeviceExt for ADBUSBDevice<T> {
#[inline]
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.inner.shell_command(command, output)
}
#[inline]
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
#[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output)
}
#[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path)
}
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
#[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path)
}
#[inline]
fn uninstall(&mut self, package: &str) -> Result<()> {
self.inner.uninstall(package)
}
#[inline]
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner()
}
}
impl<T: ADBMessageTransport> Drop for ADBUSBDevice<T> {
fn drop(&mut self) {
// Best effort here
let _ = self.get_transport_mut().disconnect();
}
}

View File

@@ -1,69 +0,0 @@
use std::{
io::{Read, Write},
path::Path,
};
use crate::{
ADBDeviceExt, Result,
usb::{WebUsbTransport, adb_usb_device::ADBUSBDevice},
};
/// Implement Android USB device reachable over wired USB
#[derive(Debug)]
pub struct ADBWebUsbDevice {
inner: ADBUSBDevice<WebUsbTransport>,
}
impl ADBWebUsbDevice {
/// Instantiate a new [`ADBRusb`]
pub fn new(_vendor_id: u16, _product_id: u16) -> Result<Self> {
todo!()
}
}
impl ADBDeviceExt for ADBWebUsbDevice {
#[inline]
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.inner.shell_command(command, output)
}
#[inline]
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
#[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output)
}
#[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path)
}
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
#[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path)
}
#[inline]
fn uninstall(&mut self, package: &str) -> Result<()> {
self.inner.uninstall(package)
}
#[inline]
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.inner.framebuffer_inner()
}
}

View File

@@ -1,7 +0,0 @@
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
pub mod rusb_transport;
#[cfg(feature = "webusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
pub mod webusb_transport;

View File

@@ -1,48 +0,0 @@
use std::time::Duration;
use crate::{
Result,
adb_transport::ADBTransport,
message_devices::{
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
},
};
/// Transport running on USB using `webusb` as a backend.
#[derive(Clone, Debug)]
pub struct WebUsbTransport {}
impl WebUsbTransport {
/// Instantiate a new [`WebUsbTransport`].
/// Only the first device with given vendor_id and product_id is returned.
pub fn new() -> Self {
WebUsbTransport {}
}
}
impl ADBTransport for WebUsbTransport {
fn connect(&mut self) -> crate::Result<()> {
todo!()
}
fn disconnect(&mut self) -> crate::Result<()> {
todo!()
}
}
impl ADBMessageTransport for WebUsbTransport {
fn read_message_with_timeout(
&mut self,
_read_timeout: Duration,
) -> Result<ADBTransportMessage> {
todo!()
}
fn write_message_with_timeout(
&mut self,
message: ADBTransportMessage,
write_timeout: std::time::Duration,
) -> Result<()> {
todo!()
}
}

View File

@@ -1,78 +0,0 @@
#![doc = include_str!("./README.md")]
/// Common USB constants for Android Debug Bridge
pub mod constants {
/// Standard Android vendor ID
pub const ANDROID_VENDOR_ID: u16 = 0x18d1;
/// Common ADB product IDs
pub mod product_ids {
/// ADB interface
pub const ADB: u16 = 0x4ee7;
/// ADB + MTP
pub const ADB_MTP: u16 = 0x4ee2;
/// ADB + RNDIS
pub const ADB_RNDIS: u16 = 0x4ee4;
/// Fastboot interface
pub const FASTBOOT: u16 = 0x4ee0;
}
/// USB class codes for ADB detection
pub mod class_codes {
/// ADB subclass code
pub const ADB_SUBCLASS: u8 = 0x42;
/// ADB protocol code
pub const ADB_PROTOCOL: u8 = 0x1;
/// Bulk transfer class
pub const BULK_CLASS: u8 = 0xdc;
/// Bulk ADB subclass
pub const BULK_ADB_SUBCLASS: u8 = 2;
}
}
// ###################################################
// rusb specific modules
#[cfg(feature = "rusb")]
mod adb_rusb_device;
// Device implementations
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
pub use adb_rusb_device::ADBRusbDevice;
// Transport implementations
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
pub use backends::rusb_transport::RusbTransport;
// ###################################################
// ###################################################
// webusb specific modules
#[cfg(feature = "webusb")]
mod adb_webusb_device;
// Device implementations
#[cfg(feature = "webusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
pub use adb_webusb_device::ADBWebUsbDevice;
// Transport implementations
#[cfg(feature = "webusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
pub use backends::webusb_transport::WebUsbTransport;
// ###################################################
mod backends;
mod utils;
#[cfg(any(feature = "rusb", feature = "webusb"))]
mod adb_usb_device;
// Utility functions
#[cfg(any(feature = "rusb", feature = "webusb"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
pub use utils::read_adb_private_key;
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
pub use utils::{is_adb_device, search_adb_devices};

View File

@@ -1,98 +0,0 @@
//! USB utilities that are independent of specific transport implementations
use crate::message_devices::adb_rsa_key::ADBRsaKey;
use crate::{Result, RustADBError};
use std::fs::read_to_string;
use std::path::Path;
#[cfg(feature = "rusb")]
use rusb::{Device, DeviceDescriptor, UsbContext};
#[cfg(feature = "rusb")]
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use crate::usb::constants::class_codes::{
ADB_PROTOCOL, ADB_SUBCLASS, BULK_ADB_SUBCLASS, BULK_CLASS,
};
/// Read an ADB private key from a file path
///
/// Returns `Ok(None)` if the file doesn't exist, `Ok(Some(key))` if the key was successfully loaded,
/// or an error if there was a problem reading the file.
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
// Try to read the private key file from given path
// If the file is not found, return None
// If there is another error while reading the file, return this error
// Else, return the private key content
let pk = match read_to_string(private_key_path.as_ref()) {
Ok(pk) => pk,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
match ADBRsaKey::new_from_pkcs8(&pk) {
Ok(pk) => Ok(Some(pk)),
Err(e) => Err(e),
}
}
/// Search for ADB devices connected via USB
///
/// Returns the vendor_id and product_id of the first ADB device found,
/// or `None` if no devices are found.
#[cfg(feature = "rusb")]
pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
let mut found_devices = vec![];
for device in rusb::devices()?.iter() {
let Ok(des) = device.device_descriptor() else {
continue;
};
if is_adb_device(&device, &des) {
log::debug!(
"Autodetect device {:04x}:{:04x}",
des.vendor_id(),
des.product_id()
);
found_devices.push((des.vendor_id(), des.product_id()));
}
}
match (found_devices.first(), found_devices.get(1)) {
(None, _) => Ok(None),
(Some(identifiers), None) => Ok(Some(*identifiers)),
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
))),
}
}
/// Check if a USB device is an ADB device
///
/// This function inspects the device descriptor and configuration to determine
/// if it's an Android Debug Bridge device.
#[cfg(feature = "rusb")]
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
// Some devices require choosing the file transfer mode
// for usb debugging to take effect.
for n in 0..des.num_configurations() {
let Ok(config_des) = device.config_descriptor(n) else {
continue;
};
for interface in config_des.interfaces() {
for interface_des in interface.descriptors() {
let proto = interface_des.protocol_code();
let class = interface_des.class_code();
let subcl = interface_des.sub_class_code();
if proto == ADB_PROTOCOL
&& ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
{
return true;
}
}
}
}
false
}

View File

@@ -1,10 +1,8 @@
use std::fmt::Display;
use crate::{
RebootType,
server::{WaitForDeviceState, WaitForDeviceTransport},
};
use crate::{WaitForDeviceState, WaitForDeviceTransport};
use super::RebootType;
use std::net::SocketAddrV4;
pub(crate) enum AdbServerCommand {
@@ -28,7 +26,7 @@ pub(crate) enum AdbServerCommand {
Install(u64),
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
// Local commands
ShellCommand(String),
ShellCommand(String, Vec<String>),
Shell,
FrameBuffer,
Sync,
@@ -53,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

@@ -1,11 +1,8 @@
use std::fmt::Display;
/// Available host features.
#[derive(Debug, PartialEq)]
pub enum HostFeatures {
/// Shell version 2.
ShellV2,
/// Command.
Cmd,
}

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

@@ -1,13 +1,17 @@
mod adb_request_status;
mod adb_server_command;
mod adb_stat_response;
mod framebuffer_info;
mod host_features;
mod list_info;
mod reboot_type;
mod sync_command;
pub(crate) use adb_request_status::AdbRequestStatus;
pub use adb_request_status::AdbRequestStatus;
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(crate) use sync_command::SyncCommand;
pub use sync_command::SyncCommand;

View File

@@ -1,15 +0,0 @@
# Examples
## Get available ADB devices
```rust no_run
use adb_client::server::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```

View File

@@ -1,7 +1,7 @@
use crate::ADBTransport;
use crate::Result;
use crate::RustADBError;
use crate::server::tcp_server_transport::TCPServerTransport;
use crate::TCPServerTransport;
use std::collections::HashMap;
use std::net::SocketAddrV4;
use std::process::Command;

View File

@@ -1,7 +1,4 @@
use crate::{
Result, RustADBError,
server::{ADBServer, AdbServerCommand},
};
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
use std::net::SocketAddrV4;
impl ADBServer {

View File

@@ -1,10 +1,8 @@
use std::io::Read;
use crate::{
Result, RustADBError,
emulator::ADBEmulatorDevice,
server::{ADBServer, AdbServerCommand, DeviceLong, DeviceShort},
server_device::ADBServerDevice,
ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, DeviceShort, Result, RustADBError,
models::AdbServerCommand,
};
impl ADBServer {

View File

@@ -1,7 +1,4 @@
use crate::{
Result, RustADBError,
server::{ADBServer, AdbServerCommand},
};
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
use std::net::SocketAddrV4;
impl ADBServer {

View File

@@ -1,7 +1,4 @@
use crate::{
Result,
server::{ADBServer, AdbServerCommand},
};
use crate::{ADBServer, Result, models::AdbServerCommand};
impl ADBServer {
/// Asks the ADB server to quit immediately.

View File

@@ -1,8 +1,7 @@
use std::io::BufRead;
use crate::{
Result,
server::{ADBServer, AdbServerCommand, MDNSServices, models::MDNSBackend},
ADBServer, MDNSServices, Result, models::AdbServerCommand, server::models::MDNSBackend,
};
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";

View File

@@ -1,7 +1,5 @@
use crate::{
Result, RustADBError,
server::{ADBServer, AdbServerCommand},
};
use crate::models::AdbServerCommand;
use crate::{ADBServer, Result, RustADBError};
use std::net::SocketAddrV4;
impl ADBServer {

View File

@@ -1,7 +1,4 @@
use crate::{
Result,
server::{ADBServer, AdbServerCommand},
};
use crate::{ADBServer, Result, models::AdbServerCommand};
impl ADBServer {
/// Reconnect the device

View File

@@ -1,7 +1,4 @@
use crate::{
Result,
server::{ADBServer, AdbServerCommand, models::ServerStatus},
};
use crate::{ADBServer, Result, models::AdbServerCommand, server::models::ServerStatus};
impl ADBServer {
/// Check ADB server status

View File

@@ -1,7 +1,4 @@
use crate::{
Result,
server::{ADBServer, AdbServerCommand, AdbVersion},
};
use crate::{ADBServer, AdbVersion, Result, models::AdbServerCommand};
impl ADBServer {
/// Gets server's internal version number.

View File

@@ -1,6 +1,5 @@
use crate::{
Result,
server::{ADBServer, AdbServerCommand, WaitForDeviceState, WaitForDeviceTransport},
ADBServer, Result, WaitForDeviceState, WaitForDeviceTransport, models::AdbServerCommand,
};
impl ADBServer {

View File

@@ -1,12 +1,6 @@
#![doc = include_str!("./README.md")]
mod adb_server;
mod adb_server_command;
mod commands;
mod models;
mod tcp_server_transport;
pub use adb_server::ADBServer;
pub(crate) use adb_server_command::AdbServerCommand;
pub use models::*;
pub use tcp_server_transport::TCPServerTransport;

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

@@ -2,8 +2,7 @@ use std::str::FromStr;
use std::sync::LazyLock;
use std::{fmt::Display, str};
use crate::RustADBError;
use crate::server::DeviceState;
use crate::{DeviceState, RustADBError};
use regex::bytes::Regex;
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {

View File

@@ -1,7 +1,7 @@
use regex::bytes::Regex;
use std::{fmt::Display, str::FromStr, sync::LazyLock};
use crate::{RustADBError, server::DeviceState};
use crate::{DeviceState, RustADBError};
static DEVICES_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));

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

@@ -1,25 +0,0 @@
# Examples
## Launch a command on device
```rust no_run
use adb_client::{server::ADBServer, ADBDeviceExt};
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
## Push a file to the device
```rust no_run
use adb_client::server::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open("/tmp/file.txt").expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```

View File

@@ -1,7 +1,4 @@
use crate::{
ADBTransport, Result,
server::{AdbServerCommand, TCPServerTransport},
};
use crate::{ADBTransport, Result, TCPServerTransport, models::AdbServerCommand};
use std::net::SocketAddrV4;
/// Represents a device connected to the ADB server.

View File

@@ -5,14 +5,12 @@ use std::{
use crate::{
ADBDeviceExt, Result, RustADBError,
models::{AdbStatResponse, HostFeatures},
server::AdbServerCommand,
constants::BUFFER_SIZE,
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
};
use super::ADBServerDevice;
const BUFFER_SIZE: usize = 65535;
impl ADBDeviceExt for ADBServerDevice {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
let supported_features = self.host_features()?;
@@ -24,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 {
@@ -121,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,4 +1,4 @@
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
use crate::{ADBServerDevice, Result, models::AdbServerCommand};
impl ADBServerDevice {
/// Forward socket connection

View File

@@ -4,10 +4,8 @@ use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, Rgba};
use crate::{
Result, RustADBError,
models::{FrameBufferInfoV1, FrameBufferInfoV2},
server::AdbServerCommand,
server_device::ADBServerDevice,
ADBServerDevice, Result, RustADBError,
models::{AdbServerCommand, FrameBufferInfoV1, FrameBufferInfoV2},
};
impl ADBServerDevice {

View File

@@ -1,5 +1,6 @@
use crate::{
Result, models::HostFeatures, server::AdbServerCommand, server_device::ADBServerDevice,
ADBServerDevice, Result,
models::{AdbServerCommand, HostFeatures},
};
impl ADBServerDevice {

View File

@@ -1,7 +1,7 @@
use std::{fs::File, io::Read, path::Path};
use crate::{
Result, server::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk,
Result, models::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk,
};
impl ADBServerDevice {

View File

@@ -1,7 +1,8 @@
use crate::{
Result, models::SyncCommand, server::AdbServerCommand, server_device::ADBServerDevice,
ADBServerDevice, Result, RustADBError,
models::{ADBListItem, ADBListItemType, AdbServerCommand, SyncCommand},
};
use byteorder::{ByteOrder, LittleEndian};
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
use std::{
io::{Read, Write},
str,
@@ -9,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())?);
@@ -35,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 {
@@ -43,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

@@ -1,6 +1,6 @@
use std::io::{self, Write};
use crate::{ADBDeviceExt, Result, server_device::ADBServerDevice};
use crate::{ADBDeviceExt, ADBServerDevice, Result};
struct LogFilter<W: Write> {
writer: W,

View File

@@ -1,4 +1,7 @@
use crate::{Result, models::RebootType, server::AdbServerCommand, server_device::ADBServerDevice};
use crate::{
ADBServerDevice, Result,
models::{AdbServerCommand, RebootType},
};
impl ADBServerDevice {
/// Reboots the device

View File

@@ -1,4 +1,4 @@
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
use crate::{ADBServerDevice, Result, models::AdbServerCommand};
impl ADBServerDevice {
/// Reconnect device

View File

@@ -1,5 +1,6 @@
use crate::{
Result, models::SyncCommand, server::AdbServerCommand, server_device::ADBServerDevice,
ADBServerDevice, Result, constants,
models::{AdbServerCommand, SyncCommand},
};
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{BufReader, BufWriter, Read, Write};
@@ -62,8 +63,6 @@ impl<R: Read> Read for ADBRecvCommandReader<R> {
}
}
const BUFFER_SIZE: usize = 65535;
impl ADBServerDevice {
/// Receives path to stream from the device.
pub fn pull(&mut self, path: &dyn AsRef<str>, stream: &mut dyn Write) -> Result<()> {
@@ -73,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)
}
@@ -93,8 +92,8 @@ impl ADBServerDevice {
let reader = ADBRecvCommandReader::new(raw_connection);
std::io::copy(
&mut BufReader::with_capacity(BUFFER_SIZE, reader),
&mut BufWriter::with_capacity(BUFFER_SIZE, output),
&mut BufReader::with_capacity(constants::BUFFER_SIZE, reader),
&mut BufWriter::with_capacity(constants::BUFFER_SIZE, output),
)?;
// Connection should've been left in SYNC mode by now

Some files were not shown because too many files have changed in this diff Show More