Compare commits
38 Commits
wasm-suppo
...
usb-backen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e74f9d3576 | ||
|
|
1d1e9b1b7f | ||
|
|
267d740321 | ||
|
|
c453c544e2 | ||
|
|
36097fdc07 | ||
|
|
4ab0b01e37 | ||
|
|
ee3d879744 | ||
|
|
31d5388ffa | ||
|
|
f108b5ed5f | ||
|
|
46c8c54751 | ||
|
|
f616373ae2 | ||
|
|
c83df4309f | ||
|
|
88526aa943 | ||
|
|
8cce59193c | ||
|
|
b916bafa5a | ||
|
|
2eed32649c | ||
|
|
ced11d4a81 | ||
|
|
db853ed67a | ||
|
|
38fead7101 | ||
|
|
8f2c3c8d89 | ||
|
|
e0b6bb0139 | ||
|
|
373a5265a0 | ||
|
|
060e43590d | ||
|
|
f51ba984ca | ||
|
|
66ebc8a030 | ||
|
|
d39e98695d | ||
|
|
34d5811420 | ||
|
|
86e28a6e25 | ||
|
|
9f113bdb93 | ||
|
|
8670d6db58 | ||
|
|
0732a0bbad | ||
|
|
b5673001ca | ||
|
|
81829c1523 | ||
|
|
b9d2b8374f | ||
|
|
5716784f5d | ||
|
|
b6ddc720d8 | ||
|
|
5438e53361 | ||
|
|
39a7f0a8cf |
2
.github/workflows/python-build.yml
vendored
2
.github/workflows/python-build.yml
vendored
@@ -35,4 +35,4 @@ jobs:
|
||||
with:
|
||||
files: |
|
||||
target/wheels/pyadb_client*.whl
|
||||
target/wheels/pyadb_client*.tar.gz
|
||||
target/wheels/pyadb_client*.tar.gz
|
||||
|
||||
12
.github/workflows/rust-build.yml
vendored
12
.github/workflows/rust-build.yml
vendored
@@ -18,6 +18,12 @@ jobs:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build project
|
||||
run: cargo build --release --all-features
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- name: Build project
|
||||
run: cargo build --release --features rusb,mdns
|
||||
|
||||
6
.github/workflows/rust-quality.yml
vendored
6
.github/workflows/rust-quality.yml
vendored
@@ -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 --features rusb,mdns
|
||||
|
||||
fmt:
|
||||
name: "fmt"
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run doc
|
||||
run: cargo doc --all-features --no-deps
|
||||
run: cargo doc --features rusb,mdns --no-deps
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
|
||||
@@ -43,4 +43,4 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features
|
||||
run: cargo test --verbose --features rusb,mdns
|
||||
|
||||
11
.github/workflows/rust-release.yml
vendored
11
.github/workflows/rust-release.yml
vendored
@@ -36,7 +36,7 @@ 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
|
||||
@@ -69,7 +69,7 @@ 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
|
||||
@@ -92,8 +92,13 @@ jobs:
|
||||
toolchain: stable
|
||||
override: true
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
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
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,4 +3,4 @@ target
|
||||
/.vscode
|
||||
venv
|
||||
/.mypy_cache
|
||||
pyadb_client/pyadb_client.pyi
|
||||
pyadb_client/pyadb_client.pyi
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["adb_cli", "adb_client", "pyadb_client"]
|
||||
members = ["adb_cli", "adb_client", "examples/mdns", "pyadb_client"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
@@ -9,7 +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.13"
|
||||
version = "2.1.18"
|
||||
rust-version = "1.85.1"
|
||||
|
||||
# To build locally when working on a new release
|
||||
[patch.crates-io]
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
<a href="https://crates.io/crates/adb_client">
|
||||
<img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/>
|
||||
</a>
|
||||
<a href="https://crates.io/crates/adb_client">
|
||||
<img alt="msrv" src="https://img.shields.io/crates/msrv/adb_client"/>
|
||||
</a>
|
||||
<a href="https://github.com/cocool97/adb_client/actions">
|
||||
<img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/>
|
||||
</a>
|
||||
@@ -46,6 +49,12 @@ 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.
|
||||
|
||||
@@ -7,14 +7,15 @@ license.workspace = true
|
||||
name = "adb_cli"
|
||||
readme = "README.md"
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
adb_client = { version = "^2.0.0" }
|
||||
anyhow = { version = "1.0.94" }
|
||||
clap = { version = "4.5.23", features = ["derive"] }
|
||||
env_logger = { version = "0.11.5" }
|
||||
log = { version = "0.4.26" }
|
||||
adb_client = { version = "^2.1.17", features = ["mdns", "rusb"] }
|
||||
anyhow = { version = "1.0.100" }
|
||||
clap = { version = "4.5.51", features = ["derive"] }
|
||||
env_logger = { version = "0.11.8" }
|
||||
log = { version = "0.4.28" }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
termios = { version = "0.3.3" }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
[](./LICENSE-MIT)
|
||||

|
||||

|
||||
|
||||
Rust binary providing an improved version of `adb` CLI.
|
||||
|
||||
@@ -10,7 +11,7 @@ Rust binary providing an improved version of `adb` CLI.
|
||||
This crate provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
|
||||
|
||||
```shell
|
||||
cargo install adb_cli
|
||||
cargo install adb_cli
|
||||
```
|
||||
|
||||
Usage is quite simple, and tends to look like `adb`:
|
||||
@@ -64,4 +65,4 @@ Options:
|
||||
-p, --product-id <PID> Hexadecimal product id of this USB device
|
||||
-k, --private-key <PATH_TO_PRIVATE_KEY> Path to a custom private key to use for authentication
|
||||
-h, --help Print help
|
||||
```
|
||||
```
|
||||
|
||||
@@ -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> {
|
||||
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
|
||||
let old_termios = new_termios; // Saves previous state
|
||||
new_termios.c_lflag = 0;
|
||||
@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
|
||||
fn drop(&mut self) {
|
||||
// Custom drop implementation, restores previous termios structure.
|
||||
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
|
||||
log::error!("Error while dropping ADBTermios: {e}")
|
||||
log::error!("Error while dropping ADBTermios: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use adb_client::ADBEmulatorDevice;
|
||||
use adb_client::emulator::ADBEmulatorDevice;
|
||||
|
||||
use crate::models::{EmuCommand, EmulatorCommand};
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use adb_client::{ADBServer, DeviceShort, MDNSBackend, Result, WaitForDeviceState};
|
||||
use adb_client::{
|
||||
Result,
|
||||
server::{ADBServer, DeviceShort, MDNSBackend, WaitForDeviceState},
|
||||
};
|
||||
|
||||
use crate::models::{HostCommand, MdnsCommand, ServerCommand};
|
||||
|
||||
@@ -8,7 +11,7 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
|
||||
match server_command.command {
|
||||
HostCommand::Version => {
|
||||
let version = adb_server.version()?;
|
||||
log::info!("Android Debug Bridge version {}", version);
|
||||
log::info!("Android Debug Bridge version {version}");
|
||||
log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
HostCommand::Kill => {
|
||||
@@ -18,18 +21,18 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
|
||||
if long {
|
||||
log::info!("List of devices attached (extended)");
|
||||
for device in adb_server.devices_long()? {
|
||||
log::info!("{}", device);
|
||||
log::info!("{device}");
|
||||
}
|
||||
} else {
|
||||
log::info!("List of devices attached");
|
||||
for device in adb_server.devices()? {
|
||||
log::info!("{}", device);
|
||||
log::info!("{device}");
|
||||
}
|
||||
}
|
||||
}
|
||||
HostCommand::TrackDevices => {
|
||||
let callback = |device: DeviceShort| {
|
||||
log::info!("{}", device);
|
||||
log::info!("{device}");
|
||||
Ok(())
|
||||
};
|
||||
log::info!("Live list of devices attached");
|
||||
@@ -53,19 +56,22 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
|
||||
let server_status = adb_server.server_status()?;
|
||||
match server_status.mdns_backend {
|
||||
MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
|
||||
MDNSBackend::Bonjour => match check {
|
||||
true => log::info!("mdns daemon version [Bonjour]"),
|
||||
false => log::info!("ERROR: mdns daemon unavailable"),
|
||||
},
|
||||
MDNSBackend::Bonjour => {
|
||||
if check {
|
||||
log::info!("mdns daemon version [Bonjour]");
|
||||
} else {
|
||||
log::info!("ERROR: mdns daemon unavailable");
|
||||
}
|
||||
}
|
||||
MDNSBackend::OpenScreen => {
|
||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]")
|
||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]");
|
||||
}
|
||||
}
|
||||
}
|
||||
MdnsCommand::Services => {
|
||||
log::info!("List of discovered mdns services");
|
||||
for service in adb_server.mdns_services()? {
|
||||
log::info!("{}", service);
|
||||
log::info!("{service}");
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::{fs::File, io::Write};
|
||||
|
||||
use adb_client::ADBServerDevice;
|
||||
use adb_client::server_device::ADBServerDevice;
|
||||
use anyhow::{Result, anyhow};
|
||||
|
||||
use crate::models::LocalDeviceCommand;
|
||||
@@ -14,7 +14,7 @@ pub fn handle_local_commands(
|
||||
let features = device
|
||||
.host_features()?
|
||||
.iter()
|
||||
.map(|v| v.to_string())
|
||||
.map(ToString::to_string)
|
||||
.reduce(|a, b| format!("{a},{b}"))
|
||||
.ok_or(anyhow!("cannot list features"))?;
|
||||
log::info!("Available host features: {features}");
|
||||
|
||||
@@ -7,9 +7,12 @@ mod handlers;
|
||||
mod models;
|
||||
mod utils;
|
||||
|
||||
use adb_client::{
|
||||
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService,
|
||||
};
|
||||
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;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
use adb_termios::ADBTermios;
|
||||
@@ -63,12 +66,12 @@ fn main() -> Result<()> {
|
||||
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)?,
|
||||
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) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
|
||||
None => ADBUSBDevice::autodetect()?,
|
||||
Some(pk) => ADBRusbDevice::autodetect_with_custom_private_key(pk)?,
|
||||
None => ADBRusbDevice::autodetect()?,
|
||||
},
|
||||
_ => {
|
||||
anyhow::bail!(
|
||||
@@ -79,7 +82,10 @@ fn main() -> Result<()> {
|
||||
(device.boxed(), usb_command.commands)
|
||||
}
|
||||
MainCommand::Tcp(tcp_command) => {
|
||||
let device = ADBTcpDevice::new(tcp_command.address)?;
|
||||
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 => {
|
||||
@@ -94,7 +100,7 @@ fn main() -> Result<()> {
|
||||
"Found device {} with addresses {:?}",
|
||||
device.fullname,
|
||||
device.addresses
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(service.shutdown()?);
|
||||
@@ -108,7 +114,7 @@ fn main() -> Result<()> {
|
||||
// Using a scope here would call drop() too early..
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
let mut adb_termios = ADBTermios::new(std::io::stdin())?;
|
||||
let mut adb_termios = ADBTermios::new(&std::io::stdin())?;
|
||||
adb_termios.set_adb_termios()?;
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
@@ -118,7 +124,7 @@ fn main() -> Result<()> {
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
} else {
|
||||
let commands: Vec<&str> = commands.iter().map(|v| v.as_str()).collect();
|
||||
let commands: Vec<&str> = commands.iter().map(String::as_str).collect();
|
||||
device.shell_command(&commands, &mut std::io::stdout())?;
|
||||
}
|
||||
}
|
||||
@@ -132,11 +138,11 @@ fn main() -> Result<()> {
|
||||
}
|
||||
DeviceCommands::Stat { path } => {
|
||||
let stat_response = device.stat(&path)?;
|
||||
println!("{}", stat_response);
|
||||
println!("{stat_response}");
|
||||
}
|
||||
DeviceCommands::Reboot { reboot_type } => {
|
||||
log::info!("Reboots device in mode {:?}", reboot_type);
|
||||
device.reboot(reboot_type.into())?
|
||||
log::info!("Reboots device in mode {reboot_type:?}");
|
||||
device.reboot(reboot_type.into())?;
|
||||
}
|
||||
DeviceCommands::Push { filename, path } => {
|
||||
let mut input = File::open(Path::new(&filename))?;
|
||||
@@ -152,7 +158,7 @@ fn main() -> Result<()> {
|
||||
device.install(&path)?;
|
||||
}
|
||||
DeviceCommands::Uninstall { package } => {
|
||||
log::info!("Uninstalling the package {}...", package);
|
||||
log::info!("Uninstalling the package {package}...");
|
||||
device.uninstall(&package)?;
|
||||
}
|
||||
DeviceCommands::Framebuffer { path } => {
|
||||
|
||||
@@ -19,7 +19,7 @@ pub enum DeviceCommands {
|
||||
/// The package whose activity is to be invoked
|
||||
#[clap(short = 'p', long = "package")]
|
||||
package: String,
|
||||
/// The activity to be invoked itself, Usually it is MainActivity
|
||||
/// The activity to be invoked itself, Usually it is `MainActivity`
|
||||
#[clap(short = 'a', long = "activity")]
|
||||
activity: String,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
use adb_client::{RustADBError, WaitForDeviceTransport};
|
||||
use adb_client::{RustADBError, server::WaitForDeviceTransport};
|
||||
use clap::Parser;
|
||||
|
||||
fn parse_wait_for_device_device_transport(
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
use clap::Parser;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::DeviceCommands;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct TcpCommand {
|
||||
pub address: SocketAddr,
|
||||
/// Path to a custom private key to use for authentication
|
||||
#[clap(short = 'k', long = "private-key")]
|
||||
pub path_to_private_key: Option<PathBuf>,
|
||||
#[clap(subcommand)]
|
||||
pub commands: DeviceCommands,
|
||||
}
|
||||
|
||||
@@ -5,10 +5,7 @@
|
||||
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 = match debug {
|
||||
true => "trace",
|
||||
false => "info",
|
||||
};
|
||||
let level = if debug { "trace" } else { "info" };
|
||||
|
||||
unsafe { std::env::set_var("RUST_LOG", level) };
|
||||
}
|
||||
|
||||
@@ -7,40 +7,63 @@ license.workspace = true
|
||||
name = "adb_client"
|
||||
readme = "README.md"
|
||||
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 = "1.3.3" }
|
||||
bincode = { version = "2.0.1", features = ["serde"] }
|
||||
byteorder = { version = "1.5.0" }
|
||||
chrono = { version = "0.4.40", default-features = false, features = ["std"] }
|
||||
homedir = { version = "0.3.4" }
|
||||
image = { version = "0.25.5", default-features = false }
|
||||
log = { version = "0.4.26" }
|
||||
mdns-sd = { version = "0.13.9", default-features = false, features = [
|
||||
"logging",
|
||||
] }
|
||||
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" }
|
||||
num-traits = { version = "0.2.19" }
|
||||
quick-protobuf = { version = "0.8.1" }
|
||||
rand = { version = "0.9.0" }
|
||||
rcgen = { version = "0.13.1", default-features = false, features = [
|
||||
"aws_lc_rs",
|
||||
rand = { version = "0.8.5" }
|
||||
rcgen = { version = "0.13.2", default-features = false, features = [
|
||||
"pem",
|
||||
"ring"
|
||||
] }
|
||||
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] }
|
||||
rsa = { version = "0.9.7" }
|
||||
rusb = { version = "0.9.4", features = ["vendored"] }
|
||||
rustls = { version = "0.23.27" }
|
||||
rustls-pki-types = { version = "1.11.0" }
|
||||
serde = { version = "1.0.216", features = ["derive"] }
|
||||
serde_repr = { version = "0.1.19" }
|
||||
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"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_repr = { version = "0.1.20" }
|
||||
sha1 = { version = "0.10.6", features = ["oid"] }
|
||||
thiserror = { version = "2.0.7" }
|
||||
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.93" }
|
||||
criterion = { version = "0.5.1" } # Used for benchmarks
|
||||
anyhow = { version = "1.0.100" }
|
||||
criterion = { version = "0.7.0" } # Used for benchmarks
|
||||
|
||||
[[bench]]
|
||||
harness = false
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
[](./LICENSE-MIT)
|
||||
[](https://docs.rs/adb_client)
|
||||
[](https://crates.io/crates/adb_client)
|
||||

|
||||
|
||||
Rust library implementing ADB protocol.
|
||||
|
||||
@@ -15,6 +16,26 @@ 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
|
||||
@@ -23,89 +44,8 @@ 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>|
|
||||
|
||||
## 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()));
|
||||
```
|
||||
| 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> |
|
||||
|
||||
@@ -6,14 +6,17 @@ use image::{ImageBuffer, ImageFormat, Rgba};
|
||||
use crate::models::AdbStatResponse;
|
||||
use crate::{RebootType, Result};
|
||||
|
||||
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
|
||||
/// Trait representing all features available on an ADB device, currently used by:
|
||||
/// - [`crate::server_device::ADBServerDevice`]
|
||||
/// - [`crate::usb::ADBRusbDevice`]
|
||||
/// - [`crate::tcp::ADBTcpDevice`]
|
||||
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<()>;
|
||||
|
||||
/// Starts an interactive shell session on the device.
|
||||
/// Input data is read from reader and write to writer.
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()>;
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()>;
|
||||
|
||||
/// Display the stat information for a remote file
|
||||
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
pub const BUFFER_SIZE: usize = 65536;
|
||||
@@ -1,292 +0,0 @@
|
||||
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 std::time::Duration;
|
||||
|
||||
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::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
|
||||
use crate::{Result, RustADBError, USBTransport};
|
||||
|
||||
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
|
||||
Ok(read_to_string(private_key_path.as_ref()).map(|pk| {
|
||||
match ADBRsaKey::new_from_pkcs8(&pk) {
|
||||
Ok(pk) => Some(pk),
|
||||
Err(e) => {
|
||||
log::error!("Error while create RSA private key: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
})?)
|
||||
}
|
||||
|
||||
/// Search for adb devices with known interface class and subclass values
|
||||
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 {:04x}:{:04x} and {:04x}:{:04x}",
|
||||
vid1, pid1, vid2, pid2
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
homedir::my_home()
|
||||
.ok()
|
||||
.flatten()
|
||||
.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(
|
||||
vendor_id: u16,
|
||||
product_id: u16,
|
||||
private_key_path: PathBuf,
|
||||
) -> 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(
|
||||
transport: USBTransport,
|
||||
private_key_path: PathBuf,
|
||||
) -> Result<Self> {
|
||||
let private_key = match read_adb_private_key(private_key_path)? {
|
||||
Some(pk) => pk,
|
||||
None => 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,
|
||||
0x01000000,
|
||||
1048576,
|
||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||
);
|
||||
|
||||
self.get_transport_mut().write_message(message)?;
|
||||
|
||||
let message = self.get_transport_mut().read_message()?;
|
||||
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]
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ADBUSBDevice {
|
||||
fn drop(&mut self) {
|
||||
// Best effort here
|
||||
let _ = self.get_transport_mut().disconnect();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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};
|
||||
pub use message_writer::MessageWriter;
|
||||
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
|
||||
pub use shell_message_writer::ShellMessageWriter;
|
||||
@@ -1,5 +0,0 @@
|
||||
mod adb_rsa_key;
|
||||
mod message_commands;
|
||||
|
||||
pub use adb_rsa_key::ADBRsaKey;
|
||||
pub use message_commands::{MessageCommand, MessageSubcommand};
|
||||
@@ -3,7 +3,10 @@ use std::{
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
|
||||
use crate::{
|
||||
ADBTransport, Result, RustADBError, emulator::tcp_emulator_transport::TCPEmulatorTransport,
|
||||
server_device::ADBServerDevice,
|
||||
};
|
||||
use regex::Regex;
|
||||
|
||||
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
@@ -15,23 +18,22 @@ static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
pub struct ADBEmulatorDevice {
|
||||
/// Unique device identifier.
|
||||
pub identifier: String,
|
||||
/// Internal [TCPEmulatorTransport]
|
||||
/// Internal [`TCPEmulatorTransport`]
|
||||
transport: TCPEmulatorTransport,
|
||||
}
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Instantiates a new [ADBEmulatorDevice]
|
||||
/// Instantiates a new [`ADBEmulatorDevice`]
|
||||
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
|
||||
let ip_address = match ip_address {
|
||||
Some(ip_address) => ip_address,
|
||||
None => Ipv4Addr::new(127, 0, 0, 1),
|
||||
None => Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
|
||||
let groups = EMULATOR_REGEX
|
||||
.captures(&identifier)
|
||||
.ok_or(RustADBError::DeviceNotFound(format!(
|
||||
"Device {} is likely not an emulator",
|
||||
identifier
|
||||
"Device {identifier} is likely not an emulator"
|
||||
)))?;
|
||||
|
||||
let port = groups
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
|
||||
};
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Send a SMS to this emulator with given content with given phone number
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
|
||||
};
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Send a SMS to this emulator with given content with given phone number
|
||||
@@ -1,5 +1,7 @@
|
||||
mod adb_emulator_device;
|
||||
mod commands;
|
||||
mod models;
|
||||
mod tcp_emulator_transport;
|
||||
|
||||
pub use adb_emulator_device::ADBEmulatorDevice;
|
||||
pub(crate) use models::ADBEmulatorCommand;
|
||||
use models::ADBEmulatorCommand;
|
||||
@@ -24,8 +24,7 @@ impl ADBEmulatorCommand {
|
||||
pub(crate) fn skip_response_lines(&self) -> u8 {
|
||||
match self {
|
||||
ADBEmulatorCommand::Authenticate(_) => 1,
|
||||
ADBEmulatorCommand::Sms(_, _) => 0,
|
||||
ADBEmulatorCommand::Rotate => 0,
|
||||
ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@ use std::{
|
||||
net::{SocketAddrV4, TcpStream},
|
||||
};
|
||||
|
||||
use homedir::my_home;
|
||||
|
||||
use super::ADBTransport;
|
||||
use crate::{Result, RustADBError, emulator_device::ADBEmulatorCommand};
|
||||
use crate::{
|
||||
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
|
||||
};
|
||||
|
||||
/// Emulator transport running on top on TCP.
|
||||
#[derive(Debug)]
|
||||
@@ -17,7 +16,7 @@ pub struct TCPEmulatorTransport {
|
||||
}
|
||||
|
||||
impl TCPEmulatorTransport {
|
||||
/// Instantiates a new instance of [TCPEmulatorTransport]
|
||||
/// Instantiates a new instance of [`TCPEmulatorTransport`]
|
||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
socket_addr,
|
||||
@@ -34,11 +33,10 @@ impl TCPEmulatorTransport {
|
||||
)))
|
||||
}
|
||||
|
||||
/// Return authentication token stored in $HOME/.emulator_console_auth_token
|
||||
/// Return authentication token stored in `$HOME/.emulator_console_auth_token`
|
||||
pub fn get_authentication_token(&mut self) -> Result<String> {
|
||||
let home = match my_home()? {
|
||||
Some(home) => home,
|
||||
None => return Err(RustADBError::NoHomeDirectory),
|
||||
let Some(home) = std::env::home_dir() else {
|
||||
return Err(RustADBError::NoHomeDirectory);
|
||||
};
|
||||
|
||||
let mut f = File::open(home.join(".emulator_console_auth_token"))?;
|
||||
@@ -54,7 +52,7 @@ impl TCPEmulatorTransport {
|
||||
self.send_command(ADBEmulatorCommand::Authenticate(token))
|
||||
}
|
||||
|
||||
/// Send an [ADBEmulatorCommand] to this emulator
|
||||
/// Send an [`ADBEmulatorCommand`] to this emulator
|
||||
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> {
|
||||
let mut connection = self.get_raw_connection()?;
|
||||
|
||||
@@ -80,10 +78,11 @@ impl TCPEmulatorTransport {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line)?;
|
||||
|
||||
match line.starts_with("OK") {
|
||||
true => Ok(()),
|
||||
false => Err(RustADBError::ADBRequestFailed(line)),
|
||||
if line.starts_with("OK") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(RustADBError::ADBRequestFailed(line))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,9 @@ pub enum RustADBError {
|
||||
/// Indicates that an error occurred when converting a value.
|
||||
#[error("Conversion error")]
|
||||
ConversionError,
|
||||
/// Indicates an error with the integer conversion.
|
||||
#[error(transparent)]
|
||||
IntegerConversionError(#[from] std::num::TryFromIntError),
|
||||
/// Remote ADB server does not support shell feature.
|
||||
#[error("Remote ADB server does not support shell feature")]
|
||||
ADBShellNotSupported,
|
||||
@@ -61,12 +64,14 @@ pub enum RustADBError {
|
||||
#[error("Unimplemented framebuffer image version: {0}")]
|
||||
UnimplementedFramebufferImageVersion(u32),
|
||||
/// An error occurred while getting user's home directory
|
||||
#[error(transparent)]
|
||||
HomeError(#[from] homedir::GetHomeError),
|
||||
#[error("Cannot get user home directory")]
|
||||
HomeError,
|
||||
/// Cannot get home directory
|
||||
#[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
|
||||
@@ -85,6 +90,8 @@ 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
|
||||
@@ -94,6 +101,8 @@ 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
|
||||
@@ -112,11 +121,13 @@ 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),
|
||||
|
||||
@@ -3,25 +3,34 @@
|
||||
#![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 constants;
|
||||
mod device;
|
||||
mod emulator_device;
|
||||
mod adb_transport;
|
||||
/// Emulator-related definitions
|
||||
pub mod emulator;
|
||||
mod error;
|
||||
mod mdns;
|
||||
mod message_devices;
|
||||
mod models;
|
||||
mod server;
|
||||
mod server_device;
|
||||
mod transports;
|
||||
|
||||
/// Server-related definitions
|
||||
pub mod server;
|
||||
|
||||
/// Device reachable by the server related definitions
|
||||
pub mod server_device;
|
||||
mod utils;
|
||||
|
||||
/// MDNS-related definitions
|
||||
#[cfg(feature = "mdns")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
|
||||
pub mod mdns;
|
||||
|
||||
pub use adb_device_ext::ADBDeviceExt;
|
||||
pub use device::{ADBTcpDevice, ADBUSBDevice};
|
||||
pub use emulator_device::ADBEmulatorDevice;
|
||||
use adb_transport::ADBTransport;
|
||||
pub use error::{Result, RustADBError};
|
||||
pub use mdns::*;
|
||||
pub use models::{AdbStatResponse, RebootType};
|
||||
pub use server::*;
|
||||
pub use server_device::ADBServerDevice;
|
||||
pub use transports::*;
|
||||
pub use message_devices::*;
|
||||
pub use models::{AdbStatResponse, HostFeatures, RebootType};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::{collections::HashSet, net::IpAddr};
|
||||
|
||||
use mdns_sd::{ResolvedService, ScopedIp};
|
||||
|
||||
/// Represent a device found from mdns search
|
||||
#[derive(Debug)]
|
||||
pub struct MDNSDevice {
|
||||
@@ -9,11 +11,11 @@ pub struct MDNSDevice {
|
||||
pub addresses: HashSet<IpAddr>,
|
||||
}
|
||||
|
||||
impl From<mdns_sd::ServiceInfo> for MDNSDevice {
|
||||
fn from(value: mdns_sd::ServiceInfo) -> Self {
|
||||
impl From<Box<ResolvedService>> for MDNSDevice {
|
||||
fn from(value: Box<ResolvedService>) -> Self {
|
||||
Self {
|
||||
fullname: value.get_fullname().to_string(),
|
||||
addresses: value.get_addresses().to_owned(),
|
||||
fullname: value.fullname,
|
||||
addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use mdns_sd::{ServiceDaemon, ServiceEvent};
|
||||
use std::{sync::mpsc::Sender, thread::JoinHandle};
|
||||
|
||||
use crate::{MDNSDevice, Result, RustADBError};
|
||||
use crate::{Result, RustADBError, mdns::MDNSDevice};
|
||||
|
||||
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
|
||||
|
||||
@@ -42,12 +42,14 @@ impl MDNSDiscoveryService {
|
||||
| ServiceEvent::ServiceFound(_, _)
|
||||
| ServiceEvent::SearchStopped(_) => {
|
||||
// Ignoring these events. We are only interesting in found devices
|
||||
continue;
|
||||
}
|
||||
ServiceEvent::ServiceResolved(service_info) => {
|
||||
if let Err(e) = sender.send(MDNSDevice::from(service_info)) {
|
||||
return Err(e.into());
|
||||
}
|
||||
return sender
|
||||
.send(MDNSDevice::from(service_info))
|
||||
.map_err(|_| RustADBError::SendError);
|
||||
}
|
||||
e => {
|
||||
log::warn!("received unknown event type {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
use byteorder::{LittleEndian, ReadBytesExt};
|
||||
use rand::Rng;
|
||||
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 bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
|
||||
use byteorder::ReadBytesExt;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::io::{Cursor, Read, Seek};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::{ADBMessageTransport, AdbStatResponse, Result, RustADBError, constants::BUFFER_SIZE};
|
||||
const BUFFER_SIZE: usize = 65535;
|
||||
|
||||
use super::{ADBTransportMessage, MessageCommand, models::MessageSubcommand};
|
||||
const BINCODE_CONFIG: Configuration<LittleEndian, Fixint, NoLimit> = bincode::config::legacy();
|
||||
|
||||
pub(crate) fn bincode_serialize_to_vec<E: Serialize>(val: E) -> Result<Vec<u8>> {
|
||||
bincode::serde::encode_to_vec(val, BINCODE_CONFIG).map_err(|_e| RustADBError::ConversionError)
|
||||
}
|
||||
|
||||
pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -> Result<D> {
|
||||
let (response, _) = bincode::serde::decode_from_slice(data, BINCODE_CONFIG)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
|
||||
/// Structure is totally agnostic over which transport is truly used.
|
||||
@@ -33,6 +53,66 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
&mut self.transport
|
||||
}
|
||||
|
||||
pub(crate) fn auth_handshake(
|
||||
&mut self,
|
||||
message: ADBTransportMessage,
|
||||
private_key: &ADBRsaKey,
|
||||
) -> Result<()> {
|
||||
match message.header().command() {
|
||||
MessageCommand::Auth => {
|
||||
log::debug!("Authentication required");
|
||||
}
|
||||
_ => return Ok(()),
|
||||
}
|
||||
|
||||
// At this point, we should have received 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 = 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 = 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(())
|
||||
}
|
||||
|
||||
/// Receive a message and acknowledge it by replying with an `OKAY` command
|
||||
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> {
|
||||
let message = self.transport.read_message()?;
|
||||
@@ -70,7 +150,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
match len.take() {
|
||||
Some(0) | None => {
|
||||
rdr.seek_relative(4)?;
|
||||
len.replace(rdr.read_u32::<LittleEndian>()? as u64);
|
||||
len.replace(u64::from(rdr.read_u32::<byteorder::LittleEndian>()?));
|
||||
}
|
||||
Some(length) => {
|
||||
let remaining_bytes = payload.len() as u64 - rdr.position();
|
||||
@@ -86,7 +166,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
}
|
||||
}
|
||||
if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
|
||||
.read_u32::<LittleEndian>()?
|
||||
.read_u32::<byteorder::LittleEndian>()?
|
||||
== MessageSubcommand::Done as u32
|
||||
{
|
||||
break;
|
||||
@@ -101,12 +181,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
remote_id: u32,
|
||||
mut reader: R,
|
||||
) -> std::result::Result<(), RustADBError> {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
let amount_read = reader.read(&mut buffer)?;
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(amount_read as u32);
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(amount_read)?);
|
||||
|
||||
let mut serialized_message =
|
||||
bincode::serialize(&subcommand_data).map_err(|_e| RustADBError::ConversionError)?;
|
||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
serialized_message.append(&mut buffer[..amount_read].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
@@ -119,16 +198,14 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
self.send_and_expect_okay(message)?;
|
||||
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => {
|
||||
// Currently file mtime is not forwarded
|
||||
let subcommand_data = MessageSubcommand::Done.with_arg(0);
|
||||
|
||||
let serialized_message = bincode::serialize(&subcommand_data)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
|
||||
let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
local_id,
|
||||
@@ -144,17 +221,15 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
MessageCommand::Write => return Ok(()),
|
||||
c => {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Wrong command received {}",
|
||||
c
|
||||
"Wrong command received {c}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(size) => {
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(size as u32);
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(size)?);
|
||||
|
||||
let mut serialized_message = bincode::serialize(&subcommand_data)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
serialized_message.append(&mut buffer[..size].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
@@ -179,12 +254,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
}
|
||||
|
||||
pub(crate) fn stat_with_explicit_ids(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
||||
let stat_buffer = MessageSubcommand::Stat.with_arg(remote_path.len() as u32);
|
||||
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()?,
|
||||
&bincode::serialize(&stat_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||
&bincode_serialize_to_vec(&stat_buffer)?,
|
||||
);
|
||||
self.send_and_expect_okay(message)?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
@@ -196,8 +271,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
let response = self.transport.read_message()?;
|
||||
// Skip first 4 bytes as this is the literal "STAT".
|
||||
// Interesting part starts right after
|
||||
bincode::deserialize(&response.into_payload()[4..])
|
||||
.map_err(|_e| RustADBError::ConversionError)
|
||||
|
||||
bincode_deserialize_from_slice(&response.into_payload()[4..])
|
||||
}
|
||||
|
||||
pub(crate) fn end_transaction(&mut self) -> Result<()> {
|
||||
@@ -206,18 +281,16 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&bincode::serialize(&quit_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||
&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> {
|
||||
let mut rng = rand::rng();
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Open,
|
||||
rng.random(), // Our 'local-id'
|
||||
rand::random::<u32>(), // Our 'local-id'
|
||||
0,
|
||||
data,
|
||||
);
|
||||
@@ -1,17 +1,21 @@
|
||||
use crate::{ADBDeviceExt, ADBMessageTransport, RebootType, Result, models::AdbStatResponse};
|
||||
use crate::{
|
||||
ADBDeviceExt, RebootType, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
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)
|
||||
}
|
||||
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()> {
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
||||
self.shell(reader, writer)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::ADBTransport;
|
||||
use crate::{Result, device::ADBTransportMessage};
|
||||
use crate::{
|
||||
Result, adb_transport::ADBTransport,
|
||||
message_devices::adb_transport_message::ADBTransportMessage,
|
||||
};
|
||||
|
||||
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(u64::MAX);
|
||||
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
@@ -6,6 +6,7 @@ use num_traits::cast::ToPrimitive;
|
||||
use rsa::pkcs8::DecodePrivateKey;
|
||||
use rsa::traits::PublicKeyParts;
|
||||
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
|
||||
use std::fmt::Write;
|
||||
|
||||
const ADB_PRIVATE_KEY_SIZE: usize = 2048;
|
||||
const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64;
|
||||
@@ -92,15 +93,16 @@ impl ADBRsaKey {
|
||||
.to_u32()
|
||||
.ok_or(RustADBError::ConversionError)?;
|
||||
|
||||
Ok(self.encode_public_key(adb_rsa_pubkey.into_bytes()))
|
||||
Self::encode_public_key(adb_rsa_pubkey.into_bytes())
|
||||
}
|
||||
|
||||
fn encode_public_key(&self, pub_key: Vec<u8>) -> String {
|
||||
fn encode_public_key(pub_key: Vec<u8>) -> Result<String> {
|
||||
let mut encoded = STANDARD.encode(pub_key);
|
||||
encoded.push(' ');
|
||||
encoded.push_str(&format!("adb_client@{}", env!("CARGO_PKG_VERSION")));
|
||||
write!(encoded, "adb_client@{}", env!("CARGO_PKG_VERSION"))
|
||||
.map_err(|_| RustADBError::ConversionError)?;
|
||||
|
||||
encoded
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
||||
@@ -1,12 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Result, RustADBError};
|
||||
|
||||
use super::models::MessageCommand;
|
||||
|
||||
pub const AUTH_TOKEN: u32 = 1;
|
||||
pub const AUTH_SIGNATURE: u32 = 2;
|
||||
pub const AUTH_RSAPUBLICKEY: u32 = 3;
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
message_devices::{adb_message_device, message_commands::MessageCommand},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ADBTransportMessage {
|
||||
@@ -58,16 +55,16 @@ impl ADBTransportMessageHeader {
|
||||
}
|
||||
|
||||
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
|
||||
data.iter().map(|&x| x as u32).sum()
|
||||
data.iter().map(|&x| u32::from(x)).sum()
|
||||
}
|
||||
|
||||
fn compute_magic(command: MessageCommand) -> u32 {
|
||||
let command_u32 = command as u32;
|
||||
command_u32 ^ 0xFFFFFFFF
|
||||
command_u32 ^ 0xFFFF_FFFF
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> Result<Vec<u8>> {
|
||||
bincode::serialize(&self).map_err(|_e| RustADBError::ConversionError)
|
||||
adb_message_device::bincode_serialize_to_vec(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +114,6 @@ impl TryFrom<[u8; 24]> for ADBTransportMessageHeader {
|
||||
type Error = RustADBError;
|
||||
|
||||
fn try_from(value: [u8; 24]) -> Result<Self> {
|
||||
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError)
|
||||
adb_message_device::bincode_deserialize_from_slice(&value)
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,11 @@ use byteorder::{LittleEndian, ReadBytesExt};
|
||||
use image::{ImageBuffer, Rgba};
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result, RustADBError,
|
||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
models::{FrameBufferInfoV1, FrameBufferInfoV2},
|
||||
};
|
||||
|
||||
@@ -32,7 +35,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||
|
||||
loop {
|
||||
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -65,7 +68,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||
|
||||
loop {
|
||||
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use std::{fs::File, path::Path};
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result,
|
||||
device::{MessageWriter, adb_message_device::ADBMessageDevice},
|
||||
Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
commands::utils::MessageWriter,
|
||||
},
|
||||
utils::check_extension_is_apk,
|
||||
};
|
||||
|
||||
@@ -14,7 +17,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
|
||||
let file_size = apk_file.metadata()?.len();
|
||||
|
||||
self.open_session(format!("exec:cmd package 'install' -S {}\0", file_size).as_bytes())?;
|
||||
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?;
|
||||
|
||||
let transport = self.get_transport().clone();
|
||||
|
||||
@@ -6,3 +6,4 @@ mod reboot;
|
||||
mod shell;
|
||||
mod stat;
|
||||
mod uninstall;
|
||||
mod utils;
|
||||
@@ -1,10 +1,12 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, MessageCommand, adb_message_device::ADBMessageDevice,
|
||||
models::MessageSubcommand,
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::{self, ADBMessageDevice},
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage,
|
||||
message_commands::{MessageCommand, MessageSubcommand},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -29,9 +31,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
std::time::Duration::from_secs(4),
|
||||
)?;
|
||||
|
||||
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32);
|
||||
let recv_buffer =
|
||||
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
|
||||
let recv_buffer = MessageSubcommand::Recv.with_arg(u32::try_from(source.len())?);
|
||||
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()?,
|
||||
@@ -1,10 +1,12 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, MessageCommand, MessageSubcommand,
|
||||
adb_message_device::ADBMessageDevice,
|
||||
Result,
|
||||
message_devices::{
|
||||
adb_message_device::{self, ADBMessageDevice},
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage,
|
||||
message_commands::{MessageCommand, MessageSubcommand},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14,9 +16,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
|
||||
let path_header = format!("{},0777", path.as_ref());
|
||||
|
||||
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32);
|
||||
let mut send_buffer =
|
||||
bincode::serialize(&send_buffer).map_err(|_e| RustADBError::ConversionError)?;
|
||||
let send_buffer = MessageSubcommand::Send.with_arg(u32::try_from(path_header.len())?);
|
||||
let mut send_buffer = adb_message_device::bincode_serialize_to_vec(&send_buffer)?;
|
||||
send_buffer.append(&mut path_header.as_bytes().to_vec());
|
||||
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
@@ -1,11 +1,14 @@
|
||||
use crate::{
|
||||
ADBMessageTransport, RebootType, Result,
|
||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
||||
RebootType, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
|
||||
self.open_session(format!("reboot:{}\0", reboot_type).as_bytes())?;
|
||||
self.open_session(format!("reboot:{reboot_type}\0").as_bytes())?;
|
||||
|
||||
self.get_transport_mut()
|
||||
.read_message()
|
||||
@@ -1,10 +1,12 @@
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
|
||||
use crate::Result;
|
||||
use crate::device::ShellMessageWriter;
|
||||
use crate::{
|
||||
ADBMessageTransport, RustADBError,
|
||||
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage, commands::utils::ShellMessageWriter,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
@@ -36,7 +38,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn shell(
|
||||
&mut self,
|
||||
mut reader: &mut dyn Read,
|
||||
mut writer: Box<(dyn Write + Send)>,
|
||||
mut writer: Box<dyn Write + Send>,
|
||||
) -> Result<()> {
|
||||
self.open_session(b"shell:\0")?;
|
||||
|
||||
@@ -60,7 +62,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
writer.write_all(&message.into_payload())?;
|
||||
writer.flush()?;
|
||||
}
|
||||
MessageCommand::Okay => continue,
|
||||
MessageCommand::Okay => {}
|
||||
_ => return Err(RustADBError::ADBShellNotSupported),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
use crate::{
|
||||
ADBMessageTransport, AdbStatResponse, Result, device::adb_message_device::ADBMessageDevice,
|
||||
AdbStatResponse, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
@@ -1,14 +1,19 @@
|
||||
use crate::{ADBMessageTransport, Result, device::adb_message_device::ADBMessageDevice};
|
||||
use crate::{
|
||||
Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {
|
||||
self.open_session(format!("exec:cmd package 'uninstall' {}\0", package_name).as_bytes())?;
|
||||
self.open_session(format!("exec:cmd package 'uninstall' {package_name}\0").as_bytes())?;
|
||||
|
||||
let final_status = self.get_transport_mut().read_message()?;
|
||||
|
||||
match final_status.into_payload().as_slice() {
|
||||
b"Success\n" => {
|
||||
log::info!("Package {} successfully uninstalled", package_name);
|
||||
log::info!("Package {package_name} successfully uninstalled");
|
||||
Ok(())
|
||||
}
|
||||
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::io::{Error, ErrorKind, Result, Write};
|
||||
|
||||
use crate::ADBMessageTransport;
|
||||
|
||||
use super::{ADBTransportMessage, MessageCommand};
|
||||
use crate::message_devices::{
|
||||
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
|
||||
message_commands::MessageCommand,
|
||||
};
|
||||
|
||||
/// [`Write`] trait implementation to hide underlying ADB protocol write logic.
|
||||
///
|
||||
@@ -35,10 +36,10 @@ impl<T: ADBMessageTransport> Write for MessageWriter<T> {
|
||||
Ok(response) => {
|
||||
response
|
||||
.assert_command(MessageCommand::Okay)
|
||||
.map_err(|e| Error::new(ErrorKind::Other, e))?;
|
||||
.map_err(Error::other)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
Err(e) => Err(Error::new(ErrorKind::Other, e)),
|
||||
Err(e) => Err(Error::other(e)),
|
||||
}
|
||||
}
|
||||
|
||||
4
adb_client/src/message_devices/commands/utils/mod.rs
Normal file
4
adb_client/src/message_devices/commands/utils/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
mod message_writer;
|
||||
mod shell_message_writer;
|
||||
pub use message_writer::MessageWriter;
|
||||
pub use shell_message_writer::ShellMessageWriter;
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::ADBMessageTransport;
|
||||
|
||||
use super::{ADBTransportMessage, models::MessageCommand};
|
||||
use crate::message_devices::{
|
||||
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
|
||||
message_commands::MessageCommand,
|
||||
};
|
||||
|
||||
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
|
||||
pub struct ShellMessageWriter<T: ADBMessageTransport> {
|
||||
@@ -6,32 +6,32 @@ use std::fmt::Display;
|
||||
#[repr(u32)]
|
||||
pub enum MessageCommand {
|
||||
/// Connect to a device
|
||||
Cnxn = 0x4E584E43,
|
||||
Cnxn = 0x4E58_4E43,
|
||||
/// Close connection to a device
|
||||
Clse = 0x45534C43,
|
||||
Clse = 0x4553_4C43,
|
||||
/// Device ask for authentication
|
||||
Auth = 0x48545541,
|
||||
Auth = 0x4854_5541,
|
||||
/// Open a data connection
|
||||
Open = 0x4E45504F,
|
||||
Open = 0x4E45_504F,
|
||||
/// Write data to connection
|
||||
Write = 0x45545257,
|
||||
Write = 0x4554_5257,
|
||||
/// Server understood the message
|
||||
Okay = 0x59414B4F,
|
||||
Okay = 0x5941_4B4F,
|
||||
/// Start a connection using TLS
|
||||
Stls = 0x534C5453,
|
||||
Stls = 0x534C_5453,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize_repr, Deserialize_repr)]
|
||||
#[repr(u32)]
|
||||
pub enum MessageSubcommand {
|
||||
Stat = 0x54415453,
|
||||
Send = 0x444E4553,
|
||||
Recv = 0x56434552,
|
||||
Quit = 0x54495551,
|
||||
Fail = 0x4C494146,
|
||||
Done = 0x454E4F44,
|
||||
Data = 0x41544144,
|
||||
List = 0x5453494C,
|
||||
Stat = 0x5441_5453,
|
||||
Send = 0x444E_4553,
|
||||
Recv = 0x5643_4552,
|
||||
Quit = 0x5449_5551,
|
||||
Fail = 0x4C49_4146,
|
||||
Done = 0x454E_4F44,
|
||||
Data = 0x4154_4144,
|
||||
List = 0x5453_494C,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
17
adb_client/src/message_devices/mod.rs
Normal file
17
adb_client/src/message_devices/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
/// 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;
|
||||
13
adb_client/src/message_devices/tcp/README.md
Normal file
13
adb_client/src/message_devices/tcp/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# 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()));
|
||||
```
|
||||
@@ -1,22 +1,47 @@
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::{io::Read, net::SocketAddr};
|
||||
|
||||
use super::ADBTransportMessage;
|
||||
use super::adb_message_device::ADBMessageDevice;
|
||||
use super::models::MessageCommand;
|
||||
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport};
|
||||
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};
|
||||
|
||||
/// Represent a device reached and available over USB.
|
||||
#[derive(Debug)]
|
||||
pub struct ADBTcpDevice {
|
||||
private_key: ADBRsaKey,
|
||||
inner: ADBMessageDevice<TcpTransport>,
|
||||
}
|
||||
|
||||
impl ADBTcpDevice {
|
||||
/// Instantiate a new [`ADBTcpDevice`]
|
||||
pub fn new(address: SocketAddr) -> Result<Self> {
|
||||
Self::new_with_custom_private_key(address, get_default_adb_key_path()?)
|
||||
}
|
||||
|
||||
/// Instantiate a new [`ADBTcpDevice`] using a custom private key path
|
||||
pub fn new_with_custom_private_key(
|
||||
address: SocketAddr,
|
||||
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 device = Self {
|
||||
private_key,
|
||||
inner: ADBMessageDevice::new(TcpTransport::new(address)?),
|
||||
};
|
||||
|
||||
@@ -31,8 +56,8 @@ impl ADBTcpDevice {
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Cnxn,
|
||||
0x01000000,
|
||||
1048576,
|
||||
0x0100_0000,
|
||||
1_048_576,
|
||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||
);
|
||||
|
||||
@@ -40,26 +65,28 @@ impl ADBTcpDevice {
|
||||
|
||||
let message = self.get_transport_mut().read_message()?;
|
||||
|
||||
// Check if client is requesting a secure connection and upgrade it if necessary
|
||||
// Check if a client is requesting a secure connection and upgrade it if necessary
|
||||
match message.header().command() {
|
||||
MessageCommand::Stls => {
|
||||
self.get_transport_mut()
|
||||
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
|
||||
self.get_transport_mut().upgrade_connection()?;
|
||||
log::debug!("Connection successfully upgraded from TCP to TLS");
|
||||
Ok(())
|
||||
}
|
||||
MessageCommand::Cnxn => {
|
||||
log::debug!("Unencrypted connection established");
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
return Err(crate::RustADBError::WrongResponseReceived(
|
||||
"Expected CNXN or STLS command".to_string(),
|
||||
message.header().command().to_string(),
|
||||
));
|
||||
MessageCommand::Auth => {
|
||||
log::debug!("Authentication required");
|
||||
self.inner.auth_handshake(message, &self.private_key)
|
||||
}
|
||||
_ => Err(crate::RustADBError::WrongResponseReceived(
|
||||
"Expected CNXN, STLS or AUTH command".to_string(),
|
||||
message.header().command().to_string(),
|
||||
)),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -75,7 +102,7 @@ impl ADBDeviceExt for ADBTcpDevice {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()> {
|
||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
||||
self.inner.shell(reader, writer)
|
||||
}
|
||||
|
||||
6
adb_client/src/message_devices/tcp/mod.rs
Normal file
6
adb_client/src/message_devices/tcp/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#![doc = include_str!("./README.md")]
|
||||
|
||||
mod adb_tcp_device;
|
||||
mod tcp_transport;
|
||||
|
||||
pub use adb_tcp_device::ADBTcpDevice;
|
||||
@@ -5,18 +5,20 @@ use rustls::{
|
||||
pki_types::{CertificateDer, PrivatePkcs8KeyDer, pem::PemObject},
|
||||
};
|
||||
|
||||
use super::{ADBMessageTransport, ADBTransport};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, ADBTransportMessageHeader, MessageCommand, get_default_adb_key_path,
|
||||
adb_transport::ADBTransport,
|
||||
message_devices::{
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
utils::get_default_adb_key_path,
|
||||
};
|
||||
use std::{
|
||||
fs::read_to_string,
|
||||
io::{Read, Write},
|
||||
net::{Shutdown, SocketAddr, TcpStream},
|
||||
ops::{Deref, DerefMut},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
@@ -77,7 +79,7 @@ impl Write for CurrentConnection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport running on USB
|
||||
/// Transport running on TCP
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TcpTransport {
|
||||
address: SocketAddr,
|
||||
@@ -109,7 +111,7 @@ impl TcpTransport {
|
||||
})
|
||||
}
|
||||
|
||||
fn get_current_connection(&mut self) -> Result<Arc<Mutex<CurrentConnection>>> {
|
||||
fn get_current_connection(&self) -> Result<Arc<Mutex<CurrentConnection>>> {
|
||||
self.current_connection
|
||||
.as_ref()
|
||||
.ok_or(RustADBError::IOError(std::io::Error::new(
|
||||
@@ -120,18 +122,15 @@ impl TcpTransport {
|
||||
}
|
||||
|
||||
pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
|
||||
let current_connection = match self.current_connection.clone() {
|
||||
Some(current_connection) => current_connection,
|
||||
None => {
|
||||
return Err(RustADBError::UpgradeError(
|
||||
"cannot upgrade a non-existing connection...".into(),
|
||||
));
|
||||
}
|
||||
let Some(current_connection) = self.current_connection.clone() else {
|
||||
return Err(RustADBError::UpgradeError(
|
||||
"cannot upgrade a non-existing connection...".into(),
|
||||
));
|
||||
};
|
||||
|
||||
{
|
||||
let mut current_conn_locked = current_connection.lock()?;
|
||||
match current_conn_locked.deref() {
|
||||
match &*current_conn_locked {
|
||||
CurrentConnection::Tcp(tcp_stream) => {
|
||||
// TODO: Check if we cannot be more precise
|
||||
|
||||
@@ -175,8 +174,7 @@ impl TcpTransport {
|
||||
Ok(())
|
||||
}
|
||||
c => Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Wrong command received {}",
|
||||
c
|
||||
"Wrong command received {c}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
@@ -193,7 +191,7 @@ impl ADBTransport for TcpTransport {
|
||||
log::debug!("disconnecting...");
|
||||
if let Some(current_connection) = &self.current_connection {
|
||||
let mut lock = current_connection.lock()?;
|
||||
match lock.deref_mut() {
|
||||
match &mut *lock {
|
||||
CurrentConnection::Tcp(tcp_stream) => {
|
||||
let _ = tcp_stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
@@ -212,7 +210,7 @@ impl ADBMessageTransport for TcpTransport {
|
||||
fn read_message_with_timeout(
|
||||
&mut self,
|
||||
read_timeout: std::time::Duration,
|
||||
) -> Result<crate::device::ADBTransportMessage> {
|
||||
) -> Result<ADBTransportMessage> {
|
||||
let raw_connection_lock = self.get_current_connection()?;
|
||||
let mut raw_connection = raw_connection_lock.lock()?;
|
||||
|
||||
26
adb_client/src/message_devices/usb/README.md
Normal file
26
adb_client/src/message_devices/usb/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# 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");
|
||||
```
|
||||
100
adb_client/src/message_devices/usb/adb_rusb_device.rs
Normal file
100
adb_client/src/message_devices/usb/adb_rusb_device.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
187
adb_client/src/message_devices/usb/adb_usb_device.rs
Normal file
187
adb_client/src/message_devices/usb/adb_usb_device.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
69
adb_client/src/message_devices/usb/adb_webusb_device.rs
Normal file
69
adb_client/src/message_devices/usb/adb_webusb_device.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
7
adb_client/src/message_devices/usb/backends/mod.rs
Normal file
7
adb_client/src/message_devices/usb/backends/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
#[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;
|
||||
@@ -5,10 +5,15 @@ use rusb::{
|
||||
constants::LIBUSB_CLASS_VENDOR_SPEC,
|
||||
};
|
||||
|
||||
use super::{ADBMessageTransport, ADBTransport};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
device::{ADBTransportMessage, ADBTransportMessageHeader, MessageCommand},
|
||||
adb_transport::ADBTransport,
|
||||
message_devices::{
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
usb::constants::class_codes::ADB_SUBCLASS,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -18,17 +23,17 @@ struct Endpoint {
|
||||
max_packet_size: usize,
|
||||
}
|
||||
|
||||
/// Transport running on USB
|
||||
/// Transport running on USB using `rusb` as a backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct USBTransport {
|
||||
pub struct RusbTransport {
|
||||
device: Device<GlobalContext>,
|
||||
handle: Option<Arc<DeviceHandle<GlobalContext>>>,
|
||||
read_endpoint: Option<Endpoint>,
|
||||
write_endpoint: Option<Endpoint>,
|
||||
}
|
||||
|
||||
impl USBTransport {
|
||||
/// Instantiate a new [`USBTransport`].
|
||||
impl RusbTransport {
|
||||
/// Instantiate a new [`RusbTransport`].
|
||||
/// 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() {
|
||||
@@ -40,12 +45,11 @@ impl USBTransport {
|
||||
}
|
||||
|
||||
Err(RustADBError::DeviceNotFound(format!(
|
||||
"cannot find USB device with vendor_id={} and product_id={}",
|
||||
vendor_id, product_id
|
||||
"cannot find USB device with vendor_id={vendor_id} and product_id={product_id}",
|
||||
)))
|
||||
}
|
||||
|
||||
/// Instantiate a new [`USBTransport`] from a [`rusb::Device`].
|
||||
/// Instantiate a new [`RusbTransport`] from a [`rusb::Device`].
|
||||
///
|
||||
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
|
||||
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
|
||||
@@ -91,14 +95,13 @@ impl USBTransport {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_endpoints(&self, handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
||||
fn find_endpoints(handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
||||
let mut read_endpoint: Option<Endpoint> = None;
|
||||
let mut write_endpoint: Option<Endpoint> = None;
|
||||
|
||||
for n in 0..handle.device().device_descriptor()?.num_configurations() {
|
||||
let config_desc = match handle.device().config_descriptor(n) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
let Ok(config_desc) = handle.device().config_descriptor(n) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for interface in config_desc.interfaces() {
|
||||
@@ -106,7 +109,7 @@ impl USBTransport {
|
||||
for endpoint_desc in interface_desc.endpoint_descriptors() {
|
||||
if endpoint_desc.transfer_type() == TransferType::Bulk
|
||||
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC
|
||||
&& interface_desc.sub_class_code() == 0x42
|
||||
&& interface_desc.sub_class_code() == ADB_SUBCLASS
|
||||
&& interface_desc.protocol_code() == 0x01
|
||||
{
|
||||
let endpoint = Endpoint {
|
||||
@@ -118,16 +121,14 @@ impl USBTransport {
|
||||
Direction::In => {
|
||||
if let Some(write_endpoint) = write_endpoint {
|
||||
return Ok((endpoint, write_endpoint));
|
||||
} else {
|
||||
read_endpoint = Some(endpoint);
|
||||
}
|
||||
read_endpoint = Some(endpoint);
|
||||
}
|
||||
Direction::Out => {
|
||||
if let Some(read_endpoint) = read_endpoint {
|
||||
return Ok((read_endpoint, endpoint));
|
||||
} else {
|
||||
write_endpoint = Some(endpoint);
|
||||
}
|
||||
write_endpoint = Some(endpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,12 +152,7 @@ impl USBTransport {
|
||||
let write_amount = handle.write_bulk(endpoint.address, &data[offset..end], timeout)?;
|
||||
offset += write_amount;
|
||||
|
||||
log::trace!(
|
||||
"wrote chunk of size {} - {}/{}",
|
||||
write_amount,
|
||||
offset,
|
||||
data_len
|
||||
)
|
||||
log::trace!("wrote chunk of size {write_amount} - {offset}/{data_len}",);
|
||||
}
|
||||
|
||||
if offset % max_packet_size == 0 {
|
||||
@@ -168,18 +164,18 @@ impl USBTransport {
|
||||
}
|
||||
}
|
||||
|
||||
impl ADBTransport for USBTransport {
|
||||
impl ADBTransport for RusbTransport {
|
||||
fn connect(&mut self) -> crate::Result<()> {
|
||||
let device = self.device.open()?;
|
||||
|
||||
let (read_endpoint, write_endpoint) = self.find_endpoints(&device)?;
|
||||
let (read_endpoint, write_endpoint) = Self::find_endpoints(&device)?;
|
||||
|
||||
Self::configure_endpoint(&device, &read_endpoint)?;
|
||||
log::debug!("got read endpoint: {:?}", read_endpoint);
|
||||
log::debug!("got read endpoint: {read_endpoint:?}");
|
||||
self.read_endpoint = Some(read_endpoint);
|
||||
|
||||
Self::configure_endpoint(&device, &write_endpoint)?;
|
||||
log::debug!("got write endpoint: {:?}", write_endpoint);
|
||||
log::debug!("got write endpoint: {write_endpoint:?}");
|
||||
self.write_endpoint = Some(write_endpoint);
|
||||
|
||||
self.handle = Some(Arc::new(device));
|
||||
@@ -197,7 +193,7 @@ impl ADBTransport for USBTransport {
|
||||
let endpoint = self.read_endpoint.as_ref().or(self.write_endpoint.as_ref());
|
||||
if let Some(endpoint) = &endpoint {
|
||||
match handle.release_interface(endpoint.iface) {
|
||||
Ok(_) => log::debug!("succesfully released interface"),
|
||||
Ok(()) => log::debug!("succesfully released interface"),
|
||||
Err(e) => log::error!("error while release interface: {e}"),
|
||||
}
|
||||
}
|
||||
@@ -207,7 +203,7 @@ impl ADBTransport for USBTransport {
|
||||
}
|
||||
}
|
||||
|
||||
impl ADBMessageTransport for USBTransport {
|
||||
impl ADBMessageTransport for RusbTransport {
|
||||
fn write_message_with_timeout(
|
||||
&mut self,
|
||||
message: ADBTransportMessage,
|
||||
@@ -0,0 +1,48 @@
|
||||
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!()
|
||||
}
|
||||
}
|
||||
78
adb_client/src/message_devices/usb/mod.rs
Normal file
78
adb_client/src/message_devices/usb/mod.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
#![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};
|
||||
98
adb_client/src/message_devices/usb/utils.rs
Normal file
98
adb_client/src/message_devices/usb/utils.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! 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
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
/// Available host features.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum HostFeatures {
|
||||
/// Shell version 2.
|
||||
ShellV2,
|
||||
/// Command.
|
||||
Cmd,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
mod adb_request_status;
|
||||
mod adb_server_command;
|
||||
mod adb_stat_response;
|
||||
mod framebuffer_info;
|
||||
mod host_features;
|
||||
mod reboot_type;
|
||||
mod sync_command;
|
||||
|
||||
pub use adb_request_status::AdbRequestStatus;
|
||||
pub(crate) use adb_server_command::AdbServerCommand;
|
||||
pub(crate) use adb_request_status::AdbRequestStatus;
|
||||
pub use adb_stat_response::AdbStatResponse;
|
||||
pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2};
|
||||
pub use host_features::HostFeatures;
|
||||
pub use reboot_type::RebootType;
|
||||
pub use sync_command::SyncCommand;
|
||||
pub(crate) use sync_command::SyncCommand;
|
||||
|
||||
15
adb_client/src/server/README.md
Normal file
15
adb_client/src/server/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# 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();
|
||||
```
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::ADBTransport;
|
||||
use crate::Result;
|
||||
use crate::RustADBError;
|
||||
use crate::TCPServerTransport;
|
||||
use crate::server::tcp_server_transport::TCPServerTransport;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddrV4;
|
||||
use std::process::Command;
|
||||
@@ -9,7 +9,7 @@ use std::process::Command;
|
||||
/// Represents an ADB Server
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ADBServer {
|
||||
/// Internal [TcpStream], lazily initialized
|
||||
/// Internal [`TcpStream`], lazily initialized
|
||||
pub(crate) transport: Option<TCPServerTransport>,
|
||||
/// Address to connect to
|
||||
pub(crate) socket_addr: Option<SocketAddrV4>,
|
||||
@@ -21,7 +21,7 @@ pub struct ADBServer {
|
||||
}
|
||||
|
||||
impl ADBServer {
|
||||
/// Instantiates a new [ADBServer]
|
||||
/// Instantiates a new [`ADBServer`]
|
||||
pub fn new(address: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
transport: None,
|
||||
@@ -31,7 +31,7 @@ impl ADBServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a new [ADBServer] with a custom adb path
|
||||
/// Instantiates a new [`ADBServer`] with a custom adb path
|
||||
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
|
||||
Self {
|
||||
transport: None,
|
||||
@@ -46,7 +46,7 @@ impl ADBServer {
|
||||
// ADB Server is local, we start it if not already running
|
||||
let mut command = Command::new(adb_path.as_deref().unwrap_or("adb"));
|
||||
command.arg("start-server");
|
||||
for (env_k, env_v) in envs.iter() {
|
||||
for (env_k, env_v) in envs {
|
||||
command.env(env_k, env_v);
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ impl ADBServer {
|
||||
match child {
|
||||
Ok(mut child) => {
|
||||
if let Err(e) = child.wait() {
|
||||
log::error!("error while starting adb server: {e}")
|
||||
log::error!("error while starting adb server: {e}");
|
||||
}
|
||||
}
|
||||
Err(e) => log::error!("error while starting adb server: {e}"),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::{WaitForDeviceState, WaitForDeviceTransport};
|
||||
use crate::{
|
||||
RebootType,
|
||||
server::{WaitForDeviceState, WaitForDeviceTransport},
|
||||
};
|
||||
|
||||
use super::RebootType;
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
pub(crate) enum AdbServerCommand {
|
||||
@@ -63,8 +65,8 @@ impl Display for AdbServerCommand {
|
||||
AdbServerCommand::Reboot(reboot_type) => {
|
||||
write!(f, "reboot:{reboot_type}")
|
||||
}
|
||||
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{}", addr),
|
||||
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{}", addr),
|
||||
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{addr}"),
|
||||
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{addr}"),
|
||||
AdbServerCommand::Pair(addr, code) => {
|
||||
write!(f, "host:pair:{code}:{addr}")
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::{
|
||||
ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, DeviceShort, Result, RustADBError,
|
||||
models::AdbServerCommand,
|
||||
Result, RustADBError,
|
||||
emulator::ADBEmulatorDevice,
|
||||
server::{ADBServer, AdbServerCommand, DeviceLong, DeviceShort},
|
||||
server_device::ADBServerDevice,
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
@@ -69,12 +71,12 @@ impl ADBServer {
|
||||
.filter(|d| d.identifier.as_str() == name)
|
||||
.collect::<Vec<DeviceShort>>()
|
||||
.len();
|
||||
if nb_devices != 1 {
|
||||
if nb_devices == 1 {
|
||||
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
||||
} else {
|
||||
Err(RustADBError::DeviceNotFound(format!(
|
||||
"could not find device {name}"
|
||||
)))
|
||||
} else {
|
||||
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Asks the ADB server to quit immediately.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::io::BufRead;
|
||||
|
||||
use crate::{
|
||||
ADBServer, MDNSServices, Result, models::AdbServerCommand, server::models::MDNSBackend,
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, MDNSServices, models::MDNSBackend},
|
||||
};
|
||||
|
||||
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";
|
||||
@@ -32,7 +33,7 @@ impl ADBServer {
|
||||
Ok(service) => {
|
||||
vec_services.push(MDNSServices::try_from(service.as_bytes())?);
|
||||
}
|
||||
Err(e) => log::error!("{}", e),
|
||||
Err(e) => log::error!("{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::models::AdbServerCommand;
|
||||
use crate::{ADBServer, Result, RustADBError};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Reconnect the device
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand, server::models::ServerStatus};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, models::ServerStatus},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Check ADB server status
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, AdbVersion, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, AdbVersion},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Gets server's internal version number.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::{
|
||||
ADBServer, Result, WaitForDeviceState, WaitForDeviceTransport, models::AdbServerCommand,
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, WaitForDeviceState, WaitForDeviceTransport},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
#![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;
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct AdbVersion {
|
||||
}
|
||||
|
||||
impl AdbVersion {
|
||||
/// Instantiates a new [AdbVersion].
|
||||
/// Instantiates a new [`AdbVersion`].
|
||||
pub fn new(minor: u32, revision: u32) -> Self {
|
||||
Self {
|
||||
major: 1,
|
||||
|
||||
@@ -2,7 +2,8 @@ use std::str::FromStr;
|
||||
use std::sync::LazyLock;
|
||||
use std::{fmt::Display, str};
|
||||
|
||||
use crate::{DeviceState, RustADBError};
|
||||
use crate::RustADBError;
|
||||
use crate::server::DeviceState;
|
||||
use regex::bytes::Regex;
|
||||
|
||||
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
@@ -86,15 +87,13 @@ impl TryFrom<&[u8]> for DeviceLong {
|
||||
None => "Unk".to_string(),
|
||||
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
||||
},
|
||||
transport_id: u32::from_str_radix(
|
||||
str::from_utf8(
|
||||
groups
|
||||
.name("transport_id")
|
||||
.ok_or(RustADBError::RegexParsingError)?
|
||||
.as_bytes(),
|
||||
)?,
|
||||
16,
|
||||
)?,
|
||||
transport_id: (str::from_utf8(
|
||||
groups
|
||||
.name("transport_id")
|
||||
.ok_or(RustADBError::RegexParsingError)?
|
||||
.as_bytes(),
|
||||
)?)
|
||||
.parse::<u32>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use regex::bytes::Regex;
|
||||
use std::{fmt::Display, str::FromStr, sync::LazyLock};
|
||||
|
||||
use crate::{DeviceState, RustADBError};
|
||||
use crate::{RustADBError, server::DeviceState};
|
||||
|
||||
static DEVICES_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));
|
||||
|
||||
@@ -48,11 +48,11 @@ impl Display for UsbBackend {
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub enum MDNSBackend {
|
||||
#[default]
|
||||
/// Unknown
|
||||
/// `Unknown`
|
||||
Unknown = 0,
|
||||
/// Bonjour
|
||||
/// `Bonjour`
|
||||
Bonjour = 1,
|
||||
/// OpenScreen
|
||||
/// `OpenScreen`
|
||||
OpenScreen = 2,
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::fmt::Display;
|
||||
|
||||
use crate::RustADBError;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// List of available transports to wait for.
|
||||
pub enum WaitForDeviceTransport {
|
||||
/// USB transport
|
||||
@@ -10,15 +10,10 @@ pub enum WaitForDeviceTransport {
|
||||
/// Local transport
|
||||
Local,
|
||||
/// Any transport (default value)
|
||||
#[default]
|
||||
Any,
|
||||
}
|
||||
|
||||
impl Default for WaitForDeviceTransport {
|
||||
fn default() -> Self {
|
||||
Self::Any
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for WaitForDeviceTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
|
||||
@@ -4,11 +4,12 @@ use std::str::FromStr;
|
||||
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
|
||||
use crate::ADBTransport;
|
||||
use crate::models::{AdbRequestStatus, SyncCommand};
|
||||
use crate::{ADBTransport, models::AdbServerCommand};
|
||||
use crate::server::AdbServerCommand;
|
||||
use crate::{Result, RustADBError};
|
||||
|
||||
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
|
||||
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::LOCALHOST;
|
||||
const DEFAULT_SERVER_PORT: u16 = 5037;
|
||||
|
||||
/// Server transport running on top on TCP
|
||||
@@ -25,7 +26,7 @@ impl Default for TCPServerTransport {
|
||||
}
|
||||
|
||||
impl TCPServerTransport {
|
||||
/// Instantiates a new instance of [TCPServerTransport]
|
||||
/// Instantiates a new instance of [`TCPServerTransport`]
|
||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
socket_addr,
|
||||
@@ -33,7 +34,7 @@ impl TCPServerTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiate a new instance of [TCPServerTransport] using given address, or default if not specified.
|
||||
/// Instantiate a new instance of [`TCPServerTransport`] using given address, or default if not specified.
|
||||
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
|
||||
match socket_addr {
|
||||
Some(s) => Self::new(s),
|
||||
@@ -41,7 +42,7 @@ impl TCPServerTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get underlying [SocketAddrV4]
|
||||
/// Get underlying [`SocketAddrV4`]
|
||||
pub fn get_socketaddr(&self) -> SocketAddrV4 {
|
||||
self.socket_addr
|
||||
}
|
||||
@@ -89,7 +90,7 @@ impl TCPServerTransport {
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Send the given [SyncCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||
/// Send the given [`SyncCommand`] to ADB server, and checks that the request has been taken in consideration.
|
||||
pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> {
|
||||
// First 4 bytes are the name of the command we want to send
|
||||
// (e.g. "SEND", "RECV", "STAT", "LIST")
|
||||
@@ -98,22 +99,22 @@ impl TCPServerTransport {
|
||||
.write_all(command.to_string().as_bytes())?)
|
||||
}
|
||||
|
||||
/// Gets the body length from a LittleEndian value
|
||||
pub(crate) fn get_body_length(&mut self) -> Result<u32> {
|
||||
/// Gets the body length from a `LittleEndian` value
|
||||
pub(crate) fn get_body_length(&self) -> Result<u32> {
|
||||
let length_buffer = self.read_body_length()?;
|
||||
Ok(LittleEndian::read_u32(&length_buffer))
|
||||
}
|
||||
|
||||
/// Read 4 bytes representing body length
|
||||
fn read_body_length(&mut self) -> Result<[u8; 4]> {
|
||||
fn read_body_length(&self) -> Result<[u8; 4]> {
|
||||
let mut length_buffer = [0; 4];
|
||||
self.get_raw_connection()?.read_exact(&mut length_buffer)?;
|
||||
|
||||
Ok(length_buffer)
|
||||
}
|
||||
|
||||
/// Send the given [AdbCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||
/// If an error occurred, a [RustADBError] is returned with the response error string.
|
||||
/// Send the given [`AdbCommand`] to ADB server, and checks that the request has been taken in consideration.
|
||||
/// If an error occurred, a [`RustADBError`] is returned with the response error string.
|
||||
pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> {
|
||||
let adb_command_string = command.to_string();
|
||||
let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string);
|
||||
25
adb_client/src/server_device/README.md
Normal file
25
adb_client/src/server_device/README.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# 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");
|
||||
```
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBTransport, Result, TCPServerTransport, models::AdbServerCommand};
|
||||
use crate::{
|
||||
ADBTransport, Result,
|
||||
server::{AdbServerCommand, TCPServerTransport},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
/// Represents a device connected to the ADB server.
|
||||
@@ -6,12 +9,12 @@ use std::net::SocketAddrV4;
|
||||
pub struct ADBServerDevice {
|
||||
/// Unique device identifier.
|
||||
pub identifier: Option<String>,
|
||||
/// Internal [TCPServerTransport]
|
||||
/// Internal [`TCPServerTransport`]
|
||||
pub(crate) transport: TCPServerTransport,
|
||||
}
|
||||
|
||||
impl ADBServerDevice {
|
||||
/// Instantiates a new [ADBServerDevice], knowing its ADB identifier (as returned by `adb devices` command).
|
||||
/// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
|
||||
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
|
||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||
|
||||
@@ -21,7 +24,7 @@ impl ADBServerDevice {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a new [ADBServerDevice], assuming only one is currently connected.
|
||||
/// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
|
||||
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
|
||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||
|
||||
|
||||
@@ -5,12 +5,14 @@ use std::{
|
||||
|
||||
use crate::{
|
||||
ADBDeviceExt, Result, RustADBError,
|
||||
constants::BUFFER_SIZE,
|
||||
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
|
||||
models::{AdbStatResponse, HostFeatures},
|
||||
server::AdbServerCommand,
|
||||
};
|
||||
|
||||
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()?;
|
||||
@@ -25,15 +27,14 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
self.transport
|
||||
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
|
||||
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
match self.transport.get_raw_connection()?.read(&mut buffer) {
|
||||
Ok(size) => {
|
||||
if size == 0 {
|
||||
return Ok(());
|
||||
} else {
|
||||
output.write_all(&buffer[..size])?;
|
||||
}
|
||||
output.write_all(&buffer[..size])?;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(RustADBError::IOError(e));
|
||||
@@ -49,7 +50,7 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
fn shell(
|
||||
&mut self,
|
||||
mut reader: &mut dyn Read,
|
||||
mut writer: Box<(dyn Write + Send)>,
|
||||
mut writer: Box<dyn Write + Send>,
|
||||
) -> Result<()> {
|
||||
let supported_features = self.host_features()?;
|
||||
if !supported_features.contains(&HostFeatures::ShellV2)
|
||||
@@ -67,8 +68,9 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
|
||||
// Reading thread, reads response from adb-server
|
||||
std::thread::spawn(move || -> Result<()> {
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
match read_stream.read(&mut buffer) {
|
||||
Ok(0) => {
|
||||
read_stream.shutdown(std::net::Shutdown::Both)?;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{ADBServerDevice, Result, models::AdbServerCommand};
|
||||
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
|
||||
|
||||
impl ADBServerDevice {
|
||||
/// Forward socket connection
|
||||
|
||||
@@ -4,8 +4,10 @@ use byteorder::{LittleEndian, ReadBytesExt};
|
||||
use image::{ImageBuffer, Rgba};
|
||||
|
||||
use crate::{
|
||||
ADBServerDevice, Result, RustADBError,
|
||||
models::{AdbServerCommand, FrameBufferInfoV1, FrameBufferInfoV2},
|
||||
Result, RustADBError,
|
||||
models::{FrameBufferInfoV1, FrameBufferInfoV2},
|
||||
server::AdbServerCommand,
|
||||
server_device::ADBServerDevice,
|
||||
};
|
||||
|
||||
impl ADBServerDevice {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::{
|
||||
ADBServerDevice, Result,
|
||||
models::{AdbServerCommand, HostFeatures},
|
||||
Result, models::HostFeatures, server::AdbServerCommand, server_device::ADBServerDevice,
|
||||
};
|
||||
|
||||
impl ADBServerDevice {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{fs::File, io::Read, path::Path};
|
||||
|
||||
use crate::{
|
||||
Result, models::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk,
|
||||
Result, server::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk,
|
||||
};
|
||||
|
||||
impl ADBServerDevice {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::{
|
||||
ADBServerDevice, Result,
|
||||
models::{AdbServerCommand, SyncCommand},
|
||||
Result, models::SyncCommand, server::AdbServerCommand, server_device::ADBServerDevice,
|
||||
};
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
use std::{
|
||||
@@ -26,7 +25,7 @@ impl ADBServerDevice {
|
||||
// 'DONE' directly without listing anything.
|
||||
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> {
|
||||
let mut len_buf = [0_u8; 4];
|
||||
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
|
||||
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
|
||||
|
||||
// 4 bytes of command name is already sent by send_sync_request
|
||||
self.transport.get_raw_connection()?.write_all(&len_buf)?;
|
||||
@@ -64,7 +63,7 @@ impl ADBServerDevice {
|
||||
"DONE" => {
|
||||
return Ok(());
|
||||
}
|
||||
x => log::error!("Got an unknown response {}", x),
|
||||
x => log::error!("Got an unknown response {x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user