57 Commits

Author SHA1 Message Date
Corentin LIAUD
e74f9d3576 fix: ci 2025-11-10 12:16:36 +01:00
Corentin LIAUD
1d1e9b1b7f Merge branch 'main' into usb-backends 2025-11-10 12:07:00 +01:00
Corentin LIAUD
267d740321 feat: support wasm build for adb_client 2025-11-10 11:39:28 +01:00
Corentin LIAUD
c453c544e2 wip: keep moving things to usb specific feat. 2025-11-09 12:16:52 +01:00
Corentin LIAUD
36097fdc07 fix: windows release build 2025-11-07 14:41:09 +01:00
Corentin LIAUD
4ab0b01e37 chore: v2.1.18 2025-11-07 14:33:19 +01:00
Corentin LIAUD
ee3d879744 chore: v2.1.18 2025-11-07 14:20:17 +01:00
Corentin LIAUD
31d5388ffa feat(pyadb_client): bump min python version to 3.10 2025-11-07 14:18:37 +01:00
Corentin LIAUD
f108b5ed5f chore(bincode): bump 2025-11-06 08:55:41 +01:00
Corentin LIAUD
46c8c54751 chore(deps): updates 2025-11-06 08:15:11 +01:00
Koji AGAWA
f616373ae2 refactor(adb_client): Simplify command handling in adb_tcp_device.rs by reducing explicit return statements 2025-11-06 08:00:43 +01:00
Koji AGAWA
c83df4309f refactor(adb_client): Extract common AUTH handshake logic to a reusable method in adb_message_device.rs 2025-11-06 08:00:43 +01:00
Koji AGAWA
88526aa943 feat(adb_client): Add support for AUTH in the TCP device 2025-11-06 08:00:43 +01:00
Koji AGAWA
8cce59193c deps(adb_client): use ring rather than aws_lc_rs in rcgen 2025-11-06 07:47:59 +01:00
Corentin LIAUD
b916bafa5a feat: rework usb backend 2025-10-19 15:04:27 +02:00
Corentin LIAUD
2eed32649c feat: improve README.md 2025-10-19 15:00:45 +02:00
Corentin LIAUD
ced11d4a81 feat: improve modules ordering 2025-10-19 15:00:42 +02:00
Corentin LIAUD
db853ed67a breaking(feature): add usb feature 2025-10-19 15:00:29 +02:00
Corentin LIAUD
38fead7101 doc: add section in README.md 2025-10-19 14:59:47 +02:00
Corentin LIAUD
8f2c3c8d89 breaking(features): add mdns feature + example 2025-10-19 14:59:44 +02:00
Corentin LIAUD
e0b6bb0139 chore: cargo clippy -- -W clippy::pedantic 2025-10-19 14:58:35 +02:00
Corentin LIAUD
373a5265a0 chore: v2.1.17 2025-09-21 11:42:58 +02:00
yohane
060e43590d Fix:Regex expression parsing transport incorrectly 2025-09-21 11:37:37 +02:00
Corentin LIAUD
f51ba984ca impr: further improve LogFilter by removing split_inclusive 2025-09-21 11:29:05 +02:00
0vercl0k
66ebc8a030 Reword logic in LogFilter::write to avoid cloning the internal buffer 2025-09-21 11:29:05 +02:00
LIAUD Corentin
d39e98695d fix: wrong msrv badges url 2025-08-03 17:38:11 +02:00
LIAUD Corentin
34d5811420 chore: version 2.1.16 2025-08-03 17:32:50 +02:00
LIAUD Corentin
86e28a6e25 chore: add msrv badges 2025-08-03 17:31:24 +02:00
LIAUD Corentin
9f113bdb93 chore: add msrv + fix clippy lints 2025-08-03 17:27:54 +02:00
cocool97
8670d6db58 fix: use random adb key if not existing (#130) 2025-08-03 17:08:15 +02:00
LIAUD Corentin
0732a0bbad chore: v2.1.15 2025-07-27 20:20:57 +02:00
cocool97
b5673001ca feat: make search_adb_devices and is_adb_device public (#129) 2025-07-27 20:19:03 +02:00
LIAUD Corentin
81829c1523 chore: v2.1.14 2025-07-07 08:21:22 +02:00
LIAUD Corentin
b9d2b8374f dep(homedir): fix to 0.3.4 to fix windows build 2025-07-06 20:00:24 +02:00
LIAUD Corentin
5716784f5d deps(homedir): fix version 0.3.5 because of hard rust 1.88 dep 2025-07-06 19:42:15 +02:00
LIAUD Corentin
b6ddc720d8 chore(clippy): run linter 2025-07-06 19:41:58 +02:00
Sashanoraa
5438e53361 Support devices that don't do auth (#124) 2025-07-06 19:34:34 +02:00
cocool97
39a7f0a8cf chore: bump criterion + pyo3 (#122) 2025-05-24 14:56:34 +02:00
LIAUD Corentin
4129d9d218 chore: v2.1.13 2025-05-12 19:48:19 +02:00
alesharik
c23dca61d7 feat: add fastboot reboot type (#119)
* feat: add fastboot reboot type

* feat: add fastboot command to cli

---------

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2025-05-12 19:47:56 +02:00
LIAUD Corentin
2bc338fdf5 fix: add missing chrono "std" feature 2025-05-11 14:45:50 +02:00
wxitcode
728fb7da95 fix: device long parse error issue (#118)
* fix: device long parse error issue

* test: add device_long unit tests

* fix: prevent copy when parsing DeviceLong

---------

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2025-05-11 14:02:19 +02:00
LIAUD Corentin
2e762400e5 fix: reduce dependencies (#112)
- Reduce tree from 349 to 210.
- Remove unused lazy_static dependency
2025-05-09 19:37:25 +02:00
LIAUD Corentin
c85c76228d chore: version v2.1.12 2025-05-01 12:49:35 +02:00
LIAUD Corentin
e91a35b3ff chore: remove useless .cargo/config.toml file 2025-05-01 12:48:44 +02:00
LIAUD Corentin
8f979eff91 chore: improve pyadb_client README.md 2025-05-01 12:48:44 +02:00
LIAUD Corentin
af51584736 fix: #108 2025-05-01 12:48:44 +02:00
LIAUD Corentin
864bde01f6 feat: add zero-length packet if final_packet_size % endpoint_max_packet_size == 0 2025-05-01 12:48:44 +02:00
LIAUD Corentin
8361a0fe06 fix: implement Drop for USBTransport 2025-05-01 12:48:44 +02:00
LIAUD Corentin
218ec3d679 feat: add more trace info 2025-05-01 12:48:44 +02:00
LIAUD Corentin
4b817c0435 chore: remove unused feature 2025-05-01 12:48:44 +02:00
Ricardo Fernández Serrata
2dd30931f2 docs(logger): setup_logger safety assumptions (#107) 2025-04-22 08:59:23 +02:00
LIAUD Corentin
8b4602c62f chore: version 2.1.11 2025-04-13 16:40:48 +02:00
cocool97
e917a45670 feat: edition 2024 (#106) 2025-04-13 16:38:38 +02:00
cocool97
b0303ad544 feat(ci): add windows + macos build (#105)
* feat(ci): add windows + macos build
2025-04-13 16:24:49 +02:00
LIAUD Corentin
f3f95d92c2 chore: v2.1.10 2025-03-12 17:27:02 +01:00
Cendy
886adfa392 feat: adb custom path (#101)
---------

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2025-03-12 17:26:13 +01:00
128 changed files with 1710 additions and 1061 deletions

View File

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

View File

@@ -10,10 +10,20 @@ env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
jobs: jobs:
build-release: build:
name: "build-release" name: "Build on ${{ matrix.os }}"
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Build project
run: cargo build --release --all-features - name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Build project
run: cargo build --release --features rusb,mdns

View File

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

View File

@@ -4,46 +4,106 @@ on:
release: release:
types: [created] types: [created]
env:
CARGO_TERM_COLOR: always
jobs: jobs:
create-release: release-linux:
name: Linux - Build and Publish
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: "Set up Rust" - name: Set up Rust
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: stable toolchain: stable
override: true override: true
- name: "Install dependencies" - name: Install dependencies
run: | run: |
sudo apt update sudo apt update
sudo apt install -y rpm sudo apt install -y rpm
cargo install cargo-deb cargo install cargo-deb
cargo install cargo-generate-rpm cargo install cargo-generate-rpm
- name: "Publish crates" - name: Publish crates
run: | run: |
cargo publish -p adb_client --token ${CRATES_IO_TOKEN} cargo publish -p adb_client --token ${CRATES_IO_TOKEN}
cargo publish -p adb_cli --token ${CRATES_IO_TOKEN} cargo publish -p adb_cli --token ${CRATES_IO_TOKEN}
env: env:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
- name: "build-release" - name: Build release
run: cargo build --all-features --release run: cargo build -p adb_cli --release
- name: "Build DEB package" - name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-linux
- name: Build DEB package
run: cargo deb -p adb_cli run: cargo deb -p adb_cli
- name: "Build RPM package" - name: Build RPM package
run: cargo generate-rpm -p adb_cli run: cargo generate-rpm -p adb_cli
- name: "Publish GitHub artefacts" - name: Upload Linux artifacts
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
files: | files: |
target/debian/*.deb target/debian/*.deb
target/generate-rpm/*.rpm target/generate-rpm/*.rpm
target/release/adb_cli target/release/adb_cli-linux
release-macos:
name: macOS - Build Binary
runs-on: macos-13
steps:
- uses: actions/checkout@v4
- name: Set up Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Build release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-macos
- name: Upload macOS binary
uses: softprops/action-gh-release@v2
with:
files: target/release/adb_cli-macos
release-windows:
name: Windows - Build Binary
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Set up Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Build 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
- name: Upload Windows binary
uses: softprops/action-gh-release@v2
with:
files: target/release/adb_cli-windows.exe

2
.gitignore vendored
View File

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

View File

@@ -1,15 +1,16 @@
[workspace] [workspace]
members = ["adb_cli", "adb_client", "pyadb_client"] members = ["adb_cli", "adb_client", "examples/mdns", "pyadb_client"]
resolver = "2" resolver = "2"
[workspace.package] [workspace.package]
authors = ["Corentin LIAUD"] authors = ["Corentin LIAUD"]
edition = "2021" edition = "2024"
homepage = "https://github.com/cocool97/adb_client" homepage = "https://github.com/cocool97/adb_client"
keywords = ["adb", "android", "tcp", "usb"] keywords = ["adb", "android", "tcp", "usb"]
license = "MIT" license = "MIT"
repository = "https://github.com/cocool97/adb_client" repository = "https://github.com/cocool97/adb_client"
version = "2.1.9" version = "2.1.18"
rust-version = "1.85.1"
# To build locally when working on a new release # To build locally when working on a new release
[patch.crates-io] [patch.crates-io]

View File

@@ -8,6 +8,9 @@
<a href="https://crates.io/crates/adb_client"> <a href="https://crates.io/crates/adb_client">
<img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/> <img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/>
</a> </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"> <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"/> <img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/>
</a> </a>
@@ -46,6 +49,12 @@ Provides a "real-world" usage example of this library.
Improved documentation available [here](./adb_cli/README.md). 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 ## pyadb_client
Python wrapper using `adb_client` library to export classes usable directly from a Python environment. Python wrapper using `adb_client` library to export classes usable directly from a Python environment.

View File

@@ -7,14 +7,15 @@ license.workspace = true
name = "adb_cli" name = "adb_cli"
readme = "README.md" readme = "README.md"
repository.workspace = true repository.workspace = true
rust-version.workspace = true
version.workspace = true version.workspace = true
[dependencies] [dependencies]
adb_client = { version = "^2.0.0" } adb_client = { version = "^2.1.17", features = ["mdns", "rusb"] }
anyhow = { version = "1.0.94" } anyhow = { version = "1.0.100" }
clap = { version = "4.5.23", features = ["derive"] } clap = { version = "4.5.51", features = ["derive"] }
env_logger = { version = "0.11.5" } env_logger = { version = "0.11.8" }
log = { version = "0.4.26" } log = { version = "0.4.28" }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
termios = { version = "0.3.3" } termios = { version = "0.3.3" }

View File

@@ -2,6 +2,7 @@
[![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli) ![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli)
![MSRV](https://img.shields.io/crates/msrv/adb_cli)
Rust binary providing an improved version of `adb` CLI. 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 : This crate provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
```shell ```shell
cargo install adb_cli cargo install adb_cli
``` ```
Usage is quite simple, and tends to look like `adb`: 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 -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 -k, --private-key <PATH_TO_PRIVATE_KEY> Path to a custom private key to use for authentication
-h, --help Print help -h, --help Print help
``` ```

View File

@@ -2,7 +2,7 @@
use std::os::unix::prelude::{AsRawFd, RawFd}; use std::os::unix::prelude::{AsRawFd, RawFd};
use termios::{tcsetattr, Termios, TCSANOW, VMIN, VTIME}; use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
use crate::Result; use crate::Result;
@@ -13,7 +13,7 @@ pub struct ADBTermios {
} }
impl ADBTermios { impl ADBTermios {
pub fn new(fd: impl AsRawFd) -> Result<Self> { pub fn new(fd: &impl AsRawFd) -> Result<Self> {
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?; let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
let old_termios = new_termios; // Saves previous state let old_termios = new_termios; // Saves previous state
new_termios.c_lflag = 0; new_termios.c_lflag = 0;
@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
fn drop(&mut self) { fn drop(&mut self) {
// Custom drop implementation, restores previous termios structure. // Custom drop implementation, restores previous termios structure.
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) { 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}");
} }
} }
} }

View File

@@ -1,4 +1,4 @@
use adb_client::ADBEmulatorDevice; use adb_client::emulator::ADBEmulatorDevice;
use crate::models::{EmuCommand, EmulatorCommand}; use crate::models::{EmuCommand, EmulatorCommand};

View File

@@ -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}; use crate::models::{HostCommand, MdnsCommand, ServerCommand};
@@ -8,7 +11,7 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
match server_command.command { match server_command.command {
HostCommand::Version => { HostCommand::Version => {
let version = adb_server.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")); log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
} }
HostCommand::Kill => { HostCommand::Kill => {
@@ -18,18 +21,18 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
if long { if long {
log::info!("List of devices attached (extended)"); log::info!("List of devices attached (extended)");
for device in adb_server.devices_long()? { for device in adb_server.devices_long()? {
log::info!("{}", device); log::info!("{device}");
} }
} else { } else {
log::info!("List of devices attached"); log::info!("List of devices attached");
for device in adb_server.devices()? { for device in adb_server.devices()? {
log::info!("{}", device); log::info!("{device}");
} }
} }
} }
HostCommand::TrackDevices => { HostCommand::TrackDevices => {
let callback = |device: DeviceShort| { let callback = |device: DeviceShort| {
log::info!("{}", device); log::info!("{device}");
Ok(()) Ok(())
}; };
log::info!("Live list of devices attached"); 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()?; let server_status = adb_server.server_status()?;
match server_status.mdns_backend { match server_status.mdns_backend {
MDNSBackend::Unknown => log::info!("unknown mdns backend..."), MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
MDNSBackend::Bonjour => match check { MDNSBackend::Bonjour => {
true => log::info!("mdns daemon version [Bonjour]"), if check {
false => log::info!("ERROR: mdns daemon unavailable"), log::info!("mdns daemon version [Bonjour]");
}, } else {
log::info!("ERROR: mdns daemon unavailable");
}
}
MDNSBackend::OpenScreen => { MDNSBackend::OpenScreen => {
log::info!("mdns daemon version [Openscreen discovery 0.0.0]") log::info!("mdns daemon version [Openscreen discovery 0.0.0]");
} }
} }
} }
MdnsCommand::Services => { MdnsCommand::Services => {
log::info!("List of discovered mdns services"); log::info!("List of discovered mdns services");
for service in adb_server.mdns_services()? { for service in adb_server.mdns_services()? {
log::info!("{}", service); log::info!("{service}");
} }
} }
}, },

View File

@@ -1,7 +1,7 @@
use std::{fs::File, io::Write}; use std::{fs::File, io::Write};
use adb_client::ADBServerDevice; use adb_client::server_device::ADBServerDevice;
use anyhow::{anyhow, Result}; use anyhow::{Result, anyhow};
use crate::models::LocalDeviceCommand; use crate::models::LocalDeviceCommand;
@@ -14,7 +14,7 @@ pub fn handle_local_commands(
let features = device let features = device
.host_features()? .host_features()?
.iter() .iter()
.map(|v| v.to_string()) .map(ToString::to_string)
.reduce(|a, b| format!("{a},{b}")) .reduce(|a, b| format!("{a},{b}"))
.ok_or(anyhow!("cannot list features"))?; .ok_or(anyhow!("cannot list features"))?;
log::info!("Available host features: {features}"); log::info!("Available host features: {features}");

View File

@@ -7,10 +7,16 @@ mod handlers;
mod models; mod models;
mod utils; mod utils;
use adb_client::{ use adb_client::ADBDeviceExt;
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService, 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; use adb_termios::ADBTermios;
use anyhow::Result; use anyhow::Result;
use clap::Parser; use clap::Parser;
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands}; use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
@@ -22,9 +28,15 @@ use std::path::Path;
use utils::setup_logger; use utils::setup_logger;
fn main() -> Result<()> { fn main() -> Result<()> {
// This depends on `clap`
let opts = Opts::parse(); let opts = Opts::parse();
setup_logger(opts.debug); // SAFETY:
// We are assuming the entire process is single-threaded
// at this point.
// This seems true for the current version of `clap`,
// but there's no guarantee for future updates
unsafe { setup_logger(opts.debug) };
// Directly handling methods / commands that aren't linked to [`ADBDeviceExt`] trait. // Directly handling methods / commands that aren't linked to [`ADBDeviceExt`] trait.
// Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it. // Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it.
@@ -36,7 +48,7 @@ fn main() -> Result<()> {
// Must start server to communicate with device, but only if this is a local one. // Must start server to communicate with device, but only if this is a local one.
let server_address_ip = server_command.address.ip(); let server_address_ip = server_command.address.ip();
if server_address_ip.is_loopback() || server_address_ip.is_unspecified() { if server_address_ip.is_loopback() || server_address_ip.is_unspecified() {
ADBServer::start(&HashMap::default()); ADBServer::start(&HashMap::default(), &None);
} }
let device = match server_command.serial { let device = match server_command.serial {
@@ -47,28 +59,33 @@ fn main() -> Result<()> {
match server_command.command { match server_command.command {
LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands), LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
LocalCommand::LocalDeviceCommand(local_device_command) => { LocalCommand::LocalDeviceCommand(local_device_command) => {
return handle_local_commands(device, local_device_command) return handle_local_commands(device, local_device_command);
} }
} }
} }
MainCommand::Usb(usb_command) => { MainCommand::Usb(usb_command) => {
let device = match (usb_command.vendor_id, usb_command.product_id) { let device = match (usb_command.vendor_id, usb_command.product_id) {
(Some(vid), Some(pid)) => match usb_command.path_to_private_key { (Some(vid), Some(pid)) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?, Some(pk) => ADBRusbDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBUSBDevice::new(vid, pid)?, None => ADBRusbDevice::new(vid, pid)?,
}, },
(None, None) => match usb_command.path_to_private_key { (None, None) => match usb_command.path_to_private_key {
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?, Some(pk) => ADBRusbDevice::autodetect_with_custom_private_key(pk)?,
None => ADBUSBDevice::autodetect()?, None => ADBRusbDevice::autodetect()?,
}, },
_ => { _ => {
anyhow::bail!("please either supply values for both the --vendor-id and --product-id flags or none."); anyhow::bail!(
"please either supply values for both the --vendor-id and --product-id flags or none."
);
} }
}; };
(device.boxed(), usb_command.commands) (device.boxed(), usb_command.commands)
} }
MainCommand::Tcp(tcp_command) => { 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) (device.boxed(), tcp_command.commands)
} }
MainCommand::Mdns => { MainCommand::Mdns => {
@@ -83,7 +100,7 @@ fn main() -> Result<()> {
"Found device {} with addresses {:?}", "Found device {} with addresses {:?}",
device.fullname, device.fullname,
device.addresses device.addresses
) );
} }
return Ok(service.shutdown()?); return Ok(service.shutdown()?);
@@ -97,17 +114,17 @@ fn main() -> Result<()> {
// Using a scope here would call drop() too early.. // Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))] #[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()?; adb_termios.set_adb_termios()?;
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?; device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
} }
#[cfg(not(any(target_os = "linux", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "macos")))]
{ {
device.shell(std::io::stdin(), std::io::stdout())?; device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
} }
} else { } 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())?; device.shell_command(&commands, &mut std::io::stdout())?;
} }
} }
@@ -121,11 +138,11 @@ fn main() -> Result<()> {
} }
DeviceCommands::Stat { path } => { DeviceCommands::Stat { path } => {
let stat_response = device.stat(&path)?; let stat_response = device.stat(&path)?;
println!("{}", stat_response); println!("{stat_response}");
} }
DeviceCommands::Reboot { reboot_type } => { DeviceCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type); log::info!("Reboots device in mode {reboot_type:?}");
device.reboot(reboot_type.into())? device.reboot(reboot_type.into())?;
} }
DeviceCommands::Push { filename, path } => { DeviceCommands::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?; let mut input = File::open(Path::new(&filename))?;
@@ -141,7 +158,7 @@ fn main() -> Result<()> {
device.install(&path)?; device.install(&path)?;
} }
DeviceCommands::Uninstall { package } => { DeviceCommands::Uninstall { package } => {
log::info!("Uninstalling the package {}...", package); log::info!("Uninstalling the package {package}...");
device.uninstall(&package)?; device.uninstall(&package)?;
} }
DeviceCommands::Framebuffer { path } => { DeviceCommands::Framebuffer { path } => {

View File

@@ -19,7 +19,7 @@ pub enum DeviceCommands {
/// The package whose activity is to be invoked /// The package whose activity is to be invoked
#[clap(short = 'p', long = "package")] #[clap(short = 'p', long = "package")]
package: String, 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")] #[clap(short = 'a', long = "activity")]
activity: String, activity: String,
}, },

View File

@@ -1,6 +1,6 @@
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
use adb_client::{RustADBError, WaitForDeviceTransport}; use adb_client::{RustADBError, server::WaitForDeviceTransport};
use clap::Parser; use clap::Parser;
fn parse_wait_for_device_device_transport( fn parse_wait_for_device_device_transport(

View File

@@ -8,6 +8,7 @@ pub enum RebootTypeCommand {
Recovery, Recovery,
Sideload, Sideload,
SideloadAutoReboot, SideloadAutoReboot,
Fastboot,
} }
impl From<RebootTypeCommand> for RebootType { impl From<RebootTypeCommand> for RebootType {
@@ -18,6 +19,7 @@ impl From<RebootTypeCommand> for RebootType {
RebootTypeCommand::Recovery => RebootType::Recovery, RebootTypeCommand::Recovery => RebootType::Recovery,
RebootTypeCommand::Sideload => RebootType::Sideload, RebootTypeCommand::Sideload => RebootType::Sideload,
RebootTypeCommand::SideloadAutoReboot => RebootType::SideloadAutoReboot, RebootTypeCommand::SideloadAutoReboot => RebootType::SideloadAutoReboot,
RebootTypeCommand::Fastboot => RebootType::Fastboot,
} }
} }
} }

View File

@@ -1,11 +1,15 @@
use clap::Parser; use clap::Parser;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf;
use super::DeviceCommands; use super::DeviceCommands;
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
pub struct TcpCommand { pub struct TcpCommand {
pub address: SocketAddr, 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)] #[clap(subcommand)]
pub commands: DeviceCommands, pub commands: DeviceCommands,
} }

View File

@@ -1,12 +1,13 @@
pub fn setup_logger(debug: bool) { /// # Safety
///
/// This conditionally mutates the process' environment.
/// See [`std::env::set_var`] for more info.
pub unsafe fn setup_logger(debug: bool) {
// RUST_LOG variable has more priority then "--debug" flag // RUST_LOG variable has more priority then "--debug" flag
if std::env::var("RUST_LOG").is_err() { if std::env::var("RUST_LOG").is_err() {
let level = match debug { let level = if debug { "trace" } else { "info" };
true => "trace",
false => "info",
};
std::env::set_var("RUST_LOG", level); unsafe { std::env::set_var("RUST_LOG", level) };
} }
env_logger::init(); env_logger::init();

View File

@@ -7,36 +7,63 @@ license.workspace = true
name = "adb_client" name = "adb_client"
readme = "README.md" readme = "README.md"
repository.workspace = true repository.workspace = true
rust-version.workspace = true
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] [dependencies]
base64 = { version = "0.22.1" } base64 = { version = "0.22.1" }
bincode = { version = "1.3.3" } bincode = { version = "2.0.1", features = ["serde"] }
byteorder = { version = "1.5.0" } byteorder = { version = "1.5.0" }
chrono = { version = "0.4.40" } chrono = { version = "0.4.42", default-features = false, features = ["std"] }
homedir = { version = "0.3.4" } image = { version = "0.25.8", default-features = false }
image = { version = "0.25.5" } log = { version = "0.4.28" }
lazy_static = { version = "1.5.0" }
log = { version = "0.4.26" }
mdns-sd = { version = "0.13.2" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" } num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" } num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" } quick-protobuf = { version = "0.8.1" }
rand = { version = "0.9.0" } rand = { version = "0.8.5" }
rcgen = { version = "0.13.1" } rcgen = { version = "0.13.2", default-features = false, features = [
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] } "pem",
rsa = { version = "0.9.7" } "ring"
rusb = { version = "0.9.4", features = ["vendored"] } ] }
rustls = { version = "0.23.22" } regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
rustls-pki-types = "1.11.0" rustls = { version = "0.23.33", default-features = false, features = ["logging", "ring", "std", "tls12"] }
serde = { version = "1.0.216", features = ["derive"] } rustls-pki-types = { version = "1.12.0", features = ["web"] }
serde_repr = { version = "0.1.19" } serde = { version = "1.0.228", features = ["derive"] }
serde_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] } 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] [dev-dependencies]
anyhow = { version = "1.0.93" } anyhow = { version = "1.0.100" }
criterion = { version = "0.5.1" } # Used for benchmarks criterion = { version = "0.7.0" } # Used for benchmarks
[[bench]] [[bench]]
harness = false harness = false

View File

@@ -3,6 +3,7 @@
[![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT)
[![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client) [![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client)
[![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_client)](https://crates.io/crates/adb_client) [![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_client)](https://crates.io/crates/adb_client)
![MSRV](https://img.shields.io/crates/msrv/adb_client)
Rust library implementing ADB protocol. 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 = "*" 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
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop 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. `ADBServerDevice` performs all operations by using adb server as a bridge.
|File size|Sample size|`ADBServerDevice`|`adb`|Difference| | File size | Sample size | `ADBServerDevice` | `adb` | Difference |
|:-------:|:---------:|:----------:|:---:|:-----:| | :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
|10 MB|100|350,79 ms|356,30 ms|<div style="color:green">-1,57 %</div>| | 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>| | 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>| | 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |
## Examples
### Get available ADB devices
```rust no_run
use adb_client::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```
### Using ADB server as bridge
#### Launch a command on device
```rust no_run
use adb_client::{ADBServer, ADBDeviceExt};
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### Push a file to the device
```rust no_run
use adb_client::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```
### Interact directly with end devices
#### (USB) Launch a command on device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### (USB) Push a file to the device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
use std::fs::File;
use std::path::Path;
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, &"/data/local/tmp");
```
#### (TCP) Get a shell from device
```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use adb_client::{ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
```

View File

@@ -6,14 +6,17 @@ use image::{ImageBuffer, ImageFormat, Rgba};
use crate::models::AdbStatResponse; use crate::models::AdbStatResponse;
use crate::{RebootType, Result}; 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 { pub trait ADBDeviceExt {
/// Runs command in a shell on the device, and write its output and error streams into output. /// Runs command in a shell on the device, and write its output and error streams into output.
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>; fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
/// Starts an interactive shell session on the device. /// Starts an interactive shell session on the device.
/// Input data is read from reader and write to writer. /// 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 /// Display the stat information for a remote file
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>; fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;

View File

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

View File

@@ -1,292 +0,0 @@
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use rusb::Device;
use rusb::DeviceDescriptor;
use rusb::UsbContext;
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::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::ADBDeviceExt;
use crate::ADBMessageTransport;
use crate::ADBTransport;
use crate::{Result, RustADBError, USBTransport};
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
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();
}
}

View File

@@ -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::{get_default_adb_key_path, ADBUSBDevice};
pub use message_writer::MessageWriter;
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
pub use shell_message_writer::ShellMessageWriter;

View File

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

View File

@@ -3,7 +3,10 @@ use std::{
sync::LazyLock, 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; use regex::Regex;
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| { static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
@@ -15,23 +18,22 @@ static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
pub struct ADBEmulatorDevice { pub struct ADBEmulatorDevice {
/// Unique device identifier. /// Unique device identifier.
pub identifier: String, pub identifier: String,
/// Internal [TCPEmulatorTransport] /// Internal [`TCPEmulatorTransport`]
transport: TCPEmulatorTransport, transport: TCPEmulatorTransport,
} }
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Instantiates a new [ADBEmulatorDevice] /// Instantiates a new [`ADBEmulatorDevice`]
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> { pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
let ip_address = match ip_address { let ip_address = match ip_address {
Some(ip_address) => ip_address, Some(ip_address) => ip_address,
None => Ipv4Addr::new(127, 0, 0, 1), None => Ipv4Addr::LOCALHOST,
}; };
let groups = EMULATOR_REGEX let groups = EMULATOR_REGEX
.captures(&identifier) .captures(&identifier)
.ok_or(RustADBError::DeviceNotFound(format!( .ok_or(RustADBError::DeviceNotFound(format!(
"Device {} is likely not an emulator", "Device {identifier} is likely not an emulator"
identifier
)))?; )))?;
let port = groups let port = groups

View File

@@ -1,4 +1,7 @@
use crate::{emulator_device::ADBEmulatorCommand, ADBEmulatorDevice, Result}; use crate::{
Result,
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
};
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Send a SMS to this emulator with given content with given phone number /// Send a SMS to this emulator with given content with given phone number

View File

@@ -1,4 +1,7 @@
use crate::{emulator_device::ADBEmulatorCommand, ADBEmulatorDevice, Result}; use crate::{
Result,
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
};
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Send a SMS to this emulator with given content with given phone number /// Send a SMS to this emulator with given content with given phone number

View File

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

View File

@@ -24,8 +24,7 @@ impl ADBEmulatorCommand {
pub(crate) fn skip_response_lines(&self) -> u8 { pub(crate) fn skip_response_lines(&self) -> u8 {
match self { match self {
ADBEmulatorCommand::Authenticate(_) => 1, ADBEmulatorCommand::Authenticate(_) => 1,
ADBEmulatorCommand::Sms(_, _) => 0, ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
ADBEmulatorCommand::Rotate => 0,
} }
} }
} }

View File

@@ -4,10 +4,9 @@ use std::{
net::{SocketAddrV4, TcpStream}, net::{SocketAddrV4, TcpStream},
}; };
use homedir::my_home; use crate::{
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
use super::ADBTransport; };
use crate::{emulator_device::ADBEmulatorCommand, Result, RustADBError};
/// Emulator transport running on top on TCP. /// Emulator transport running on top on TCP.
#[derive(Debug)] #[derive(Debug)]
@@ -17,7 +16,7 @@ pub struct TCPEmulatorTransport {
} }
impl TCPEmulatorTransport { impl TCPEmulatorTransport {
/// Instantiates a new instance of [TCPEmulatorTransport] /// Instantiates a new instance of [`TCPEmulatorTransport`]
pub fn new(socket_addr: SocketAddrV4) -> Self { pub fn new(socket_addr: SocketAddrV4) -> Self {
Self { Self {
socket_addr, 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> { pub fn get_authentication_token(&mut self) -> Result<String> {
let home = match my_home()? { let Some(home) = std::env::home_dir() else {
Some(home) => home, return Err(RustADBError::NoHomeDirectory);
None => return Err(RustADBError::NoHomeDirectory),
}; };
let mut f = File::open(home.join(".emulator_console_auth_token"))?; let mut f = File::open(home.join(".emulator_console_auth_token"))?;
@@ -54,7 +52,7 @@ impl TCPEmulatorTransport {
self.send_command(ADBEmulatorCommand::Authenticate(token)) self.send_command(ADBEmulatorCommand::Authenticate(token))
} }
/// Send an [ADBEmulatorCommand] to this emulator /// Send an [`ADBEmulatorCommand`] to this emulator
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> { pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> {
let mut connection = self.get_raw_connection()?; let mut connection = self.get_raw_connection()?;
@@ -80,10 +78,11 @@ impl TCPEmulatorTransport {
let mut line = String::new(); let mut line = String::new();
reader.read_line(&mut line)?; reader.read_line(&mut line)?;
match line.starts_with("OK") { if line.starts_with("OK") {
true => Ok(()), return Ok(());
false => Err(RustADBError::ADBRequestFailed(line)),
} }
Err(RustADBError::ADBRequestFailed(line))
} }
} }

View File

@@ -42,6 +42,9 @@ pub enum RustADBError {
/// Indicates that an error occurred when converting a value. /// Indicates that an error occurred when converting a value.
#[error("Conversion error")] #[error("Conversion error")]
ConversionError, ConversionError,
/// Indicates an error with the integer conversion.
#[error(transparent)]
IntegerConversionError(#[from] std::num::TryFromIntError),
/// Remote ADB server does not support shell feature. /// Remote ADB server does not support shell feature.
#[error("Remote ADB server does not support shell feature")] #[error("Remote ADB server does not support shell feature")]
ADBShellNotSupported, ADBShellNotSupported,
@@ -61,12 +64,14 @@ pub enum RustADBError {
#[error("Unimplemented framebuffer image version: {0}")] #[error("Unimplemented framebuffer image version: {0}")]
UnimplementedFramebufferImageVersion(u32), UnimplementedFramebufferImageVersion(u32),
/// An error occurred while getting user's home directory /// An error occurred while getting user's home directory
#[error(transparent)] #[error("Cannot get user home directory")]
HomeError(#[from] homedir::GetHomeError), HomeError,
/// Cannot get home directory /// Cannot get home directory
#[error("Cannot get home directory")] #[error("Cannot get home directory")]
NoHomeDirectory, NoHomeDirectory,
/// Generic USB error /// Generic USB error
#[cfg(feature = "rusb")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
#[error("USB Error: {0}")] #[error("USB Error: {0}")]
UsbError(#[from] rusb::Error), UsbError(#[from] rusb::Error),
/// USB device not found /// USB device not found
@@ -85,6 +90,8 @@ pub enum RustADBError {
#[error(transparent)] #[error(transparent)]
Base64EncodeError(#[from] base64::EncodeSliceError), Base64EncodeError(#[from] base64::EncodeSliceError),
/// An error occurred with RSA engine /// An error occurred with RSA engine
#[cfg(any(feature = "rusb", feature = "webusb"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
#[error(transparent)] #[error(transparent)]
RSAError(#[from] rsa::errors::Error), RSAError(#[from] rsa::errors::Error),
/// Cannot convert given data from slice /// Cannot convert given data from slice
@@ -94,6 +101,8 @@ pub enum RustADBError {
#[error("wrong file extension: {0}")] #[error("wrong file extension: {0}")]
WrongFileExtension(String), WrongFileExtension(String),
/// An error occurred with PKCS8 data /// 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}")] #[error("error with pkcs8: {0}")]
RsaPkcs8Error(#[from] rsa::pkcs8::Error), RsaPkcs8Error(#[from] rsa::pkcs8::Error),
/// Error during certificate generation /// Error during certificate generation
@@ -112,11 +121,13 @@ pub enum RustADBError {
#[error("upgrade error: {0}")] #[error("upgrade error: {0}")]
UpgradeError(String), UpgradeError(String),
/// An error occurred while getting mdns devices /// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)] #[error(transparent)]
MDNSError(#[from] mdns_sd::Error), MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel /// An error occurred while sending data to channel
#[error(transparent)] #[error("error sending data to channel")]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>), SendError,
/// An unknown transport has been provided /// An unknown transport has been provided
#[error("unknown transport: {0}")] #[error("unknown transport: {0}")]
UnknownTransport(String), UnknownTransport(String),

View File

@@ -3,25 +3,34 @@
#![forbid(missing_debug_implementations)] #![forbid(missing_debug_implementations)]
#![forbid(missing_docs)] #![forbid(missing_docs)]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]
// Feature `doc_cfg` is currently only available on nightly.
// It is activated when cfg `docsrs` is enabled.
// Documentation can be build locally using:
// `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features`
#![cfg_attr(docsrs, feature(doc_cfg))]
mod adb_device_ext; mod adb_device_ext;
mod constants; mod adb_transport;
mod device; /// Emulator-related definitions
mod emulator_device; pub mod emulator;
mod error; mod error;
mod mdns; mod message_devices;
mod models; mod models;
mod server;
mod server_device; /// Server-related definitions
mod transports; pub mod server;
/// Device reachable by the server related definitions
pub mod server_device;
mod utils; 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 adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice}; use adb_transport::ADBTransport;
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError}; pub use error::{Result, RustADBError};
pub use mdns::*; pub use message_devices::*;
pub use models::{AdbStatResponse, RebootType}; pub use models::{AdbStatResponse, HostFeatures, RebootType};
pub use server::*;
pub use server_device::ADBServerDevice;
pub use transports::*;

View File

@@ -1,5 +1,7 @@
use std::{collections::HashSet, net::IpAddr}; use std::{collections::HashSet, net::IpAddr};
use mdns_sd::{ResolvedService, ScopedIp};
/// Represent a device found from mdns search /// Represent a device found from mdns search
#[derive(Debug)] #[derive(Debug)]
pub struct MDNSDevice { pub struct MDNSDevice {
@@ -9,11 +11,11 @@ pub struct MDNSDevice {
pub addresses: HashSet<IpAddr>, pub addresses: HashSet<IpAddr>,
} }
impl From<mdns_sd::ServiceInfo> for MDNSDevice { impl From<Box<ResolvedService>> for MDNSDevice {
fn from(value: mdns_sd::ServiceInfo) -> Self { fn from(value: Box<ResolvedService>) -> Self {
Self { Self {
fullname: value.get_fullname().to_string(), fullname: value.fullname,
addresses: value.get_addresses().to_owned(), addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
} }
} }
} }

View File

@@ -1,7 +1,7 @@
use mdns_sd::{ServiceDaemon, ServiceEvent}; use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle}; 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."; const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
@@ -33,19 +33,23 @@ impl MDNSDiscoveryService {
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> { pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?; let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
let handle: JoinHandle<Result<()>> = std::thread::spawn(move || loop { let handle: JoinHandle<Result<()>> = std::thread::spawn(move || {
while let Ok(event) = receiver.recv() { loop {
match event { while let Ok(event) = receiver.recv() {
ServiceEvent::SearchStarted(_) match event {
| ServiceEvent::ServiceRemoved(_, _) ServiceEvent::SearchStarted(_)
| ServiceEvent::ServiceFound(_, _) | ServiceEvent::ServiceRemoved(_, _)
| ServiceEvent::SearchStopped(_) => { | ServiceEvent::ServiceFound(_, _)
// Ignoring these events. We are only interesting in found devices | ServiceEvent::SearchStopped(_) => {
continue; // Ignoring these events. We are only interesting in found devices
} }
ServiceEvent::ServiceResolved(service_info) => { ServiceEvent::ServiceResolved(service_info) => {
if let Err(e) = sender.send(MDNSDevice::from(service_info)) { return sender
return Err(e.into()); .send(MDNSDevice::from(service_info))
.map_err(|_| RustADBError::SendError);
}
e => {
log::warn!("received unknown event type {e:?}");
} }
} }
} }

View File

@@ -1,10 +1,30 @@
use byteorder::{LittleEndian, ReadBytesExt}; use crate::message_devices::adb_message_transport::ADBMessageTransport;
use rand::Rng; 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::io::{Cursor, Read, Seek};
use std::time::Duration;
use crate::{constants::BUFFER_SIZE, ADBMessageTransport, AdbStatResponse, Result, RustADBError}; const BUFFER_SIZE: usize = 65535;
use super::{models::MessageSubcommand, ADBTransportMessage, MessageCommand}; 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`]. /// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
/// Structure is totally agnostic over which transport is truly used. /// Structure is totally agnostic over which transport is truly used.
@@ -33,6 +53,66 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
&mut self.transport &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 /// Receive a message and acknowledge it by replying with an `OKAY` command
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> { pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> {
let message = self.transport.read_message()?; let message = self.transport.read_message()?;
@@ -70,7 +150,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
match len.take() { match len.take() {
Some(0) | None => { Some(0) | None => {
rdr.seek_relative(4)?; rdr.seek_relative(4)?;
len.replace(rdr.read_u32::<LittleEndian>()? as u64); len.replace(u64::from(rdr.read_u32::<byteorder::LittleEndian>()?));
} }
Some(length) => { Some(length) => {
let remaining_bytes = payload.len() as u64 - rdr.position(); 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)]) if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
.read_u32::<LittleEndian>()? .read_u32::<byteorder::LittleEndian>()?
== MessageSubcommand::Done as u32 == MessageSubcommand::Done as u32
{ {
break; break;
@@ -101,12 +181,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
remote_id: u32, remote_id: u32,
mut reader: R, mut reader: R,
) -> std::result::Result<(), RustADBError> { ) -> 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 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 = let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
bincode::serialize(&subcommand_data).map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..amount_read].to_vec()); serialized_message.append(&mut buffer[..amount_read].to_vec());
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
@@ -119,16 +198,14 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
loop { loop {
let mut buffer = [0; BUFFER_SIZE]; let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
match reader.read(&mut buffer) { match reader.read(&mut buffer) {
Ok(0) => { Ok(0) => {
// Currently file mtime is not forwarded // Currently file mtime is not forwarded
let subcommand_data = MessageSubcommand::Done.with_arg(0); let subcommand_data = MessageSubcommand::Done.with_arg(0);
let serialized_message = bincode::serialize(&subcommand_data) let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
.map_err(|_e| RustADBError::ConversionError)?;
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, local_id,
@@ -144,17 +221,15 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
MessageCommand::Write => return Ok(()), MessageCommand::Write => return Ok(()),
c => { c => {
return Err(RustADBError::ADBRequestFailed(format!( return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}", "Wrong command received {c}"
c )));
)))
} }
} }
} }
Ok(size) => { 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) let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
.map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..size].to_vec()); serialized_message.append(&mut buffer[..size].to_vec());
let message = ADBTransportMessage::new( 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> { 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( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, self.get_local_id()?,
self.get_remote_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(message)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
@@ -196,8 +271,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let response = self.transport.read_message()?; let response = self.transport.read_message()?;
// Skip first 4 bytes as this is the literal "STAT". // Skip first 4 bytes as this is the literal "STAT".
// Interesting part starts right after // 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<()> { pub(crate) fn end_transaction(&mut self) -> Result<()> {
@@ -206,18 +281,16 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, self.get_local_id()?,
self.get_remote_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()?; let _discard_close = self.transport.read_message()?;
Ok(()) Ok(())
} }
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> { pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
let mut rng = rand::rng();
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Open, MessageCommand::Open,
rng.random(), // Our 'local-id' rand::random::<u32>(), // Our 'local-id'
0, 0,
data, data,
); );

View File

@@ -1,17 +1,21 @@
use crate::{models::AdbStatResponse, ADBDeviceExt, ADBMessageTransport, RebootType, Result}; use crate::{
ADBDeviceExt, RebootType, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
},
models::AdbStatResponse,
};
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
path::Path, path::Path,
}; };
use super::ADBMessageDevice;
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> { fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.shell_command(command, output) 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) self.shell(reader, writer)
} }

View File

@@ -1,7 +1,9 @@
use std::time::Duration; use std::time::Duration;
use super::ADBTransport; use crate::{
use crate::{device::ADBTransportMessage, Result}; Result, adb_transport::ADBTransport,
message_devices::adb_transport_message::ADBTransportMessage,
};
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(u64::MAX); const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(u64::MAX);
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(2); const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(2);

View File

@@ -1,11 +1,12 @@
use crate::{Result, RustADBError}; use crate::{Result, RustADBError};
use base64::{engine::general_purpose::STANDARD, Engine}; use base64::{Engine, engine::general_purpose::STANDARD};
use num_bigint::{BigUint, ModInverse}; use num_bigint::{BigUint, ModInverse};
use num_traits::cast::ToPrimitive;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use num_traits::cast::ToPrimitive;
use rsa::pkcs8::DecodePrivateKey; use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PublicKeyParts; use rsa::traits::PublicKeyParts;
use rsa::{Pkcs1v15Sign, RsaPrivateKey}; use rsa::{Pkcs1v15Sign, RsaPrivateKey};
use std::fmt::Write;
const ADB_PRIVATE_KEY_SIZE: usize = 2048; const ADB_PRIVATE_KEY_SIZE: usize = 2048;
const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64; const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64;
@@ -92,15 +93,16 @@ impl ADBRsaKey {
.to_u32() .to_u32()
.ok_or(RustADBError::ConversionError)?; .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); let mut encoded = STANDARD.encode(pub_key);
encoded.push(' '); 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>> { pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {

View File

@@ -1,12 +1,9 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{Result, RustADBError}; use crate::{
Result, RustADBError,
use super::models::MessageCommand; message_devices::{adb_message_device, message_commands::MessageCommand},
};
pub const AUTH_TOKEN: u32 = 1;
pub const AUTH_SIGNATURE: u32 = 2;
pub const AUTH_RSAPUBLICKEY: u32 = 3;
#[derive(Debug)] #[derive(Debug)]
pub struct ADBTransportMessage { pub struct ADBTransportMessage {
@@ -58,16 +55,16 @@ impl ADBTransportMessageHeader {
} }
pub(crate) fn compute_crc32(data: &[u8]) -> u32 { 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 { fn compute_magic(command: MessageCommand) -> u32 {
let command_u32 = command as u32; let command_u32 = command as u32;
command_u32 ^ 0xFFFFFFFF command_u32 ^ 0xFFFF_FFFF
} }
pub fn as_bytes(&self) -> Result<Vec<u8>> { 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; type Error = RustADBError;
fn try_from(value: [u8; 24]) -> Result<Self> { fn try_from(value: [u8; 24]) -> Result<Self> {
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError) adb_message_device::bincode_deserialize_from_slice(&value)
} }
} }

View File

@@ -4,9 +4,12 @@ use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, Rgba}; use image::{ImageBuffer, Rgba};
use crate::{ use crate::{
device::{adb_message_device::ADBMessageDevice, MessageCommand}, Result, RustADBError,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
message_commands::MessageCommand,
},
models::{FrameBufferInfoV1, FrameBufferInfoV2}, models::{FrameBufferInfoV1, FrameBufferInfoV2},
ADBMessageTransport, Result, RustADBError,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -32,7 +35,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
payload_cursor.read_to_end(&mut framebuffer_data)?; payload_cursor.read_to_end(&mut framebuffer_data)?;
loop { loop {
if framebuffer_data.len() as u32 == framebuffer_info.size { if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
break; break;
} }
@@ -65,7 +68,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
payload_cursor.read_to_end(&mut framebuffer_data)?; payload_cursor.read_to_end(&mut framebuffer_data)?;
loop { loop {
if framebuffer_data.len() as u32 == framebuffer_info.size { if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
break; break;
} }

View File

@@ -1,11 +1,12 @@
use std::{fs::File, path::Path}; use std::{fs::File, path::Path};
use rand::Rng;
use crate::{ use crate::{
device::{adb_message_device::ADBMessageDevice, MessageWriter}, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
commands::utils::MessageWriter,
},
utils::check_extension_is_apk, utils::check_extension_is_apk,
ADBMessageTransport, Result,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -16,15 +17,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let file_size = apk_file.metadata()?.len(); let file_size = apk_file.metadata()?.len();
let mut rng = rand::rng(); self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?;
let local_id = rng.random();
self.open_session(format!("exec:cmd package 'install' -S {}\0", file_size).as_bytes())?;
let transport = self.get_transport().clone(); let transport = self.get_transport().clone();
let mut writer = MessageWriter::new(transport, local_id, self.get_remote_id()?); let mut writer = MessageWriter::new(transport, self.get_local_id()?, self.get_remote_id()?);
std::io::copy(&mut apk_file, &mut writer)?; std::io::copy(&mut apk_file, &mut writer)?;

View File

@@ -6,3 +6,4 @@ mod reboot;
mod shell; mod shell;
mod stat; mod stat;
mod uninstall; mod uninstall;
mod utils;

View File

@@ -1,11 +1,13 @@
use std::io::Write; use std::io::Write;
use crate::{ use crate::{
device::{ Result, RustADBError,
adb_message_device::ADBMessageDevice, models::MessageSubcommand, ADBTransportMessage, message_devices::{
MessageCommand, adb_message_device::{self, ADBMessageDevice},
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
}, },
ADBMessageTransport, Result, RustADBError,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -29,9 +31,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
std::time::Duration::from_secs(4), std::time::Duration::from_secs(4),
)?; )?;
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32); let recv_buffer = MessageSubcommand::Recv.with_arg(u32::try_from(source.len())?);
let recv_buffer = let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?;
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
self.get_local_id()?, self.get_local_id()?,

View File

@@ -1,11 +1,13 @@
use std::io::Read; use std::io::Read;
use crate::{ use crate::{
device::{ Result,
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand, message_devices::{
MessageSubcommand, adb_message_device::{self, ADBMessageDevice},
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
}, },
ADBMessageTransport, Result, RustADBError,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -14,9 +16,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let path_header = format!("{},0777", path.as_ref()); let path_header = format!("{},0777", path.as_ref());
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32); let send_buffer = MessageSubcommand::Send.with_arg(u32::try_from(path_header.len())?);
let mut send_buffer = let mut send_buffer = adb_message_device::bincode_serialize_to_vec(&send_buffer)?;
bincode::serialize(&send_buffer).map_err(|_e| RustADBError::ConversionError)?;
send_buffer.append(&mut path_header.as_bytes().to_vec()); send_buffer.append(&mut path_header.as_bytes().to_vec());
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(

View File

@@ -1,11 +1,14 @@
use crate::{ use crate::{
device::{adb_message_device::ADBMessageDevice, MessageCommand}, RebootType, Result,
ADBMessageTransport, RebootType, Result, message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
message_commands::MessageCommand,
},
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> { 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() self.get_transport_mut()
.read_message() .read_message()

View File

@@ -1,10 +1,12 @@
use std::io::{ErrorKind, Read, Write}; use std::io::{ErrorKind, Read, Write};
use crate::device::ShellMessageWriter;
use crate::Result;
use crate::{ use crate::{
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand}, Result, RustADBError,
ADBMessageTransport, 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> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -36,7 +38,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn shell( pub(crate) fn shell(
&mut self, &mut self,
mut reader: &mut dyn Read, mut reader: &mut dyn Read,
mut writer: Box<(dyn Write + Send)>, mut writer: Box<dyn Write + Send>,
) -> Result<()> { ) -> Result<()> {
self.open_session(b"shell:\0")?; self.open_session(b"shell:\0")?;
@@ -60,7 +62,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
writer.write_all(&message.into_payload())?; writer.write_all(&message.into_payload())?;
writer.flush()?; writer.flush()?;
} }
MessageCommand::Okay => continue, MessageCommand::Okay => {}
_ => return Err(RustADBError::ADBShellNotSupported), _ => return Err(RustADBError::ADBShellNotSupported),
} }
} }

View File

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

View File

@@ -1,14 +1,19 @@
use crate::{device::adb_message_device::ADBMessageDevice, ADBMessageTransport, Result}; use crate::{
Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
},
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> { 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()?; let final_status = self.get_transport_mut().read_message()?;
match final_status.into_payload().as_slice() { match final_status.into_payload().as_slice() {
b"Success\n" => { b"Success\n" => {
log::info!("Package {} successfully uninstalled", package_name); log::info!("Package {package_name} successfully uninstalled");
Ok(()) Ok(())
} }
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8( d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(

View File

@@ -1,8 +1,9 @@
use std::io::{Error, ErrorKind, Result, Write}; use std::io::{Error, ErrorKind, Result, Write};
use crate::ADBMessageTransport; use crate::message_devices::{
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
use super::{ADBTransportMessage, MessageCommand}; message_commands::MessageCommand,
};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic. /// [`Write`] trait implementation to hide underlying ADB protocol write logic.
/// ///
@@ -35,10 +36,10 @@ impl<T: ADBMessageTransport> Write for MessageWriter<T> {
Ok(response) => { Ok(response) => {
response response
.assert_command(MessageCommand::Okay) .assert_command(MessageCommand::Okay)
.map_err(|e| Error::new(ErrorKind::Other, e))?; .map_err(Error::other)?;
Ok(buf.len()) Ok(buf.len())
} }
Err(e) => Err(Error::new(ErrorKind::Other, e)), Err(e) => Err(Error::other(e)),
} }
} }

View File

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

View File

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

View File

@@ -6,32 +6,32 @@ use std::fmt::Display;
#[repr(u32)] #[repr(u32)]
pub enum MessageCommand { pub enum MessageCommand {
/// Connect to a device /// Connect to a device
Cnxn = 0x4E584E43, Cnxn = 0x4E58_4E43,
/// Close connection to a device /// Close connection to a device
Clse = 0x45534C43, Clse = 0x4553_4C43,
/// Device ask for authentication /// Device ask for authentication
Auth = 0x48545541, Auth = 0x4854_5541,
/// Open a data connection /// Open a data connection
Open = 0x4E45504F, Open = 0x4E45_504F,
/// Write data to connection /// Write data to connection
Write = 0x45545257, Write = 0x4554_5257,
/// Server understood the message /// Server understood the message
Okay = 0x59414B4F, Okay = 0x5941_4B4F,
/// Start a connection using TLS /// Start a connection using TLS
Stls = 0x534C5453, Stls = 0x534C_5453,
} }
#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize_repr, Deserialize_repr)] #[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize_repr, Deserialize_repr)]
#[repr(u32)] #[repr(u32)]
pub enum MessageSubcommand { pub enum MessageSubcommand {
Stat = 0x54415453, Stat = 0x5441_5453,
Send = 0x444E4553, Send = 0x444E_4553,
Recv = 0x56434552, Recv = 0x5643_4552,
Quit = 0x54495551, Quit = 0x5449_5551,
Fail = 0x4C494146, Fail = 0x4C49_4146,
Done = 0x454E4F44, Done = 0x454E_4F44,
Data = 0x41544144, Data = 0x4154_4144,
List = 0x5453494C, List = 0x5453_494C,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]

View 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;

View 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()));
```

View File

@@ -1,22 +1,47 @@
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::{Path, PathBuf};
use std::{io::Read, net::SocketAddr}; use std::{io::Read, net::SocketAddr};
use super::adb_message_device::ADBMessageDevice; use crate::message_devices::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand; use crate::message_devices::adb_message_transport::ADBMessageTransport;
use super::ADBTransportMessage; use crate::message_devices::adb_rsa_key::ADBRsaKey;
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport}; 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. /// Represent a device reached and available over USB.
#[derive(Debug)] #[derive(Debug)]
pub struct ADBTcpDevice { pub struct ADBTcpDevice {
private_key: ADBRsaKey,
inner: ADBMessageDevice<TcpTransport>, inner: ADBMessageDevice<TcpTransport>,
} }
impl ADBTcpDevice { impl ADBTcpDevice {
/// Instantiate a new [`ADBTcpDevice`] /// Instantiate a new [`ADBTcpDevice`]
pub fn new(address: SocketAddr) -> Result<Self> { 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 { let mut device = Self {
private_key,
inner: ADBMessageDevice::new(TcpTransport::new(address)?), inner: ADBMessageDevice::new(TcpTransport::new(address)?),
}; };
@@ -31,8 +56,8 @@ impl ADBTcpDevice {
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Cnxn, MessageCommand::Cnxn,
0x01000000, 0x0100_0000,
1048576, 1_048_576,
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(), format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
); );
@@ -40,26 +65,28 @@ impl ADBTcpDevice {
let message = self.get_transport_mut().read_message()?; 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() { match message.header().command() {
MessageCommand::Stls => { MessageCommand::Stls => {
self.get_transport_mut() self.get_transport_mut()
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?; .write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
self.get_transport_mut().upgrade_connection()?; self.get_transport_mut().upgrade_connection()?;
log::debug!("Connection successfully upgraded from TCP to TLS"); log::debug!("Connection successfully upgraded from TCP to TLS");
Ok(())
} }
MessageCommand::Cnxn => { MessageCommand::Cnxn => {
log::debug!("Unencrypted connection established"); log::debug!("Unencrypted connection established");
Ok(())
} }
_ => { MessageCommand::Auth => {
return Err(crate::RustADBError::WrongResponseReceived( log::debug!("Authentication required");
"Expected CNXN or STLS command".to_string(), self.inner.auth_handshake(message, &self.private_key)
message.header().command().to_string(),
));
} }
_ => Err(crate::RustADBError::WrongResponseReceived(
"Expected CNXN, STLS or AUTH command".to_string(),
message.header().command().to_string(),
)),
} }
Ok(())
} }
#[inline] #[inline]
@@ -75,7 +102,7 @@ impl ADBDeviceExt for ADBTcpDevice {
} }
#[inline] #[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) self.inner.shell(reader, writer)
} }

View File

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

View File

@@ -1,22 +1,24 @@
use rcgen::{CertificateParams, KeyPair, PKCS_RSA_SHA256}; use rcgen::{CertificateParams, KeyPair, PKCS_RSA_SHA256};
use rustls::{ use rustls::{
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{pem::PemObject, CertificateDer, PrivatePkcs8KeyDer},
ClientConfig, ClientConnection, KeyLogFile, SignatureScheme, StreamOwned, ClientConfig, ClientConnection, KeyLogFile, SignatureScheme, StreamOwned,
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{CertificateDer, PrivatePkcs8KeyDer, pem::PemObject},
}; };
use super::{ADBMessageTransport, ADBTransport};
use crate::{ use crate::{
device::{
get_default_adb_key_path, ADBTransportMessage, ADBTransportMessageHeader, MessageCommand,
},
Result, RustADBError, Result, RustADBError,
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::{ use std::{
fs::read_to_string, fs::read_to_string,
io::{Read, Write}, io::{Read, Write},
net::{Shutdown, SocketAddr, TcpStream}, net::{Shutdown, SocketAddr, TcpStream},
ops::{Deref, DerefMut},
path::PathBuf, path::PathBuf,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
time::Duration, time::Duration,
@@ -77,7 +79,7 @@ impl Write for CurrentConnection {
} }
} }
/// Transport running on USB /// Transport running on TCP
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TcpTransport { pub struct TcpTransport {
address: SocketAddr, 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 self.current_connection
.as_ref() .as_ref()
.ok_or(RustADBError::IOError(std::io::Error::new( .ok_or(RustADBError::IOError(std::io::Error::new(
@@ -120,18 +122,15 @@ impl TcpTransport {
} }
pub(crate) fn upgrade_connection(&mut self) -> Result<()> { pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
let current_connection = match self.current_connection.clone() { let Some(current_connection) = self.current_connection.clone() else {
Some(current_connection) => current_connection, return Err(RustADBError::UpgradeError(
None => { "cannot upgrade a non-existing connection...".into(),
return Err(RustADBError::UpgradeError( ));
"cannot upgrade a non-existing connection...".into(),
))
}
}; };
{ {
let mut current_conn_locked = current_connection.lock()?; let mut current_conn_locked = current_connection.lock()?;
match current_conn_locked.deref() { match &*current_conn_locked {
CurrentConnection::Tcp(tcp_stream) => { CurrentConnection::Tcp(tcp_stream) => {
// TODO: Check if we cannot be more precise // TODO: Check if we cannot be more precise
@@ -162,7 +161,7 @@ impl TcpTransport {
CurrentConnection::Tls(_) => { CurrentConnection::Tls(_) => {
return Err(RustADBError::UpgradeError( return Err(RustADBError::UpgradeError(
"cannot upgrade a TLS connection...".into(), "cannot upgrade a TLS connection...".into(),
)) ));
} }
} }
} }
@@ -175,8 +174,7 @@ impl TcpTransport {
Ok(()) Ok(())
} }
c => Err(RustADBError::ADBRequestFailed(format!( c => Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}", "Wrong command received {c}"
c
))), ))),
} }
} }
@@ -193,7 +191,7 @@ impl ADBTransport for TcpTransport {
log::debug!("disconnecting..."); log::debug!("disconnecting...");
if let Some(current_connection) = &self.current_connection { if let Some(current_connection) = &self.current_connection {
let mut lock = current_connection.lock()?; let mut lock = current_connection.lock()?;
match lock.deref_mut() { match &mut *lock {
CurrentConnection::Tcp(tcp_stream) => { CurrentConnection::Tcp(tcp_stream) => {
let _ = tcp_stream.shutdown(Shutdown::Both); let _ = tcp_stream.shutdown(Shutdown::Both);
} }
@@ -212,7 +210,7 @@ impl ADBMessageTransport for TcpTransport {
fn read_message_with_timeout( fn read_message_with_timeout(
&mut self, &mut self,
read_timeout: std::time::Duration, read_timeout: std::time::Duration,
) -> Result<crate::device::ADBTransportMessage> { ) -> Result<ADBTransportMessage> {
let raw_connection_lock = self.get_current_connection()?; let raw_connection_lock = self.get_current_connection()?;
let mut raw_connection = raw_connection_lock.lock()?; let mut raw_connection = raw_connection_lock.lock()?;

View 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");
```

View 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()
}
}

View 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();
}
}

View 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()
}
}

View 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;

View File

@@ -1,33 +1,39 @@
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use rusb::{ use rusb::{
constants::LIBUSB_CLASS_VENDOR_SPEC, Device, DeviceHandle, Direction, GlobalContext, Device, DeviceHandle, Direction, GlobalContext, TransferType,
TransferType, constants::LIBUSB_CLASS_VENDOR_SPEC,
}; };
use super::{ADBMessageTransport, ADBTransport};
use crate::{ use crate::{
device::{ADBTransportMessage, ADBTransportMessageHeader, MessageCommand},
Result, RustADBError, Result, RustADBError,
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)] #[derive(Clone, Debug)]
struct Endpoint { struct Endpoint {
iface: u8, iface: u8,
address: u8, address: u8,
max_packet_size: usize,
} }
/// Transport running on USB /// Transport running on USB using `rusb` as a backend.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct USBTransport { pub struct RusbTransport {
device: Device<GlobalContext>, device: Device<GlobalContext>,
handle: Option<Arc<DeviceHandle<GlobalContext>>>, handle: Option<Arc<DeviceHandle<GlobalContext>>>,
read_endpoint: Option<Endpoint>, read_endpoint: Option<Endpoint>,
write_endpoint: Option<Endpoint>, write_endpoint: Option<Endpoint>,
} }
impl USBTransport { impl RusbTransport {
/// Instantiate a new [`USBTransport`]. /// Instantiate a new [`RusbTransport`].
/// Only the first device with given vendor_id and product_id is returned. /// Only the first device with given vendor_id and product_id is returned.
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> { pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
for device in rusb::devices()?.iter() { for device in rusb::devices()?.iter() {
@@ -39,12 +45,11 @@ impl USBTransport {
} }
Err(RustADBError::DeviceNotFound(format!( Err(RustADBError::DeviceNotFound(format!(
"cannot find USB device with vendor_id={} and product_id={}", "cannot find USB device with vendor_id={vendor_id} and product_id={product_id}",
vendor_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. /// 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 { pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
@@ -90,14 +95,13 @@ impl USBTransport {
Ok(()) 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 read_endpoint: Option<Endpoint> = None;
let mut write_endpoint: Option<Endpoint> = None; let mut write_endpoint: Option<Endpoint> = None;
for n in 0..handle.device().device_descriptor()?.num_configurations() { for n in 0..handle.device().device_descriptor()?.num_configurations() {
let config_desc = match handle.device().config_descriptor(n) { let Ok(config_desc) = handle.device().config_descriptor(n) else {
Ok(c) => c, continue;
Err(_) => continue,
}; };
for interface in config_desc.interfaces() { for interface in config_desc.interfaces() {
@@ -105,27 +109,26 @@ impl USBTransport {
for endpoint_desc in interface_desc.endpoint_descriptors() { for endpoint_desc in interface_desc.endpoint_descriptors() {
if endpoint_desc.transfer_type() == TransferType::Bulk if endpoint_desc.transfer_type() == TransferType::Bulk
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC && 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 && interface_desc.protocol_code() == 0x01
{ {
let endpoint = Endpoint { let endpoint = Endpoint {
iface: interface_desc.interface_number(), iface: interface_desc.interface_number(),
address: endpoint_desc.address(), address: endpoint_desc.address(),
max_packet_size: endpoint_desc.max_packet_size() as usize,
}; };
match endpoint_desc.direction() { match endpoint_desc.direction() {
Direction::In => { Direction::In => {
if let Some(write_endpoint) = write_endpoint { if let Some(write_endpoint) = write_endpoint {
return Ok((endpoint, write_endpoint)); return Ok((endpoint, write_endpoint));
} else {
read_endpoint = Some(endpoint);
} }
read_endpoint = Some(endpoint);
} }
Direction::Out => { Direction::Out => {
if let Some(read_endpoint) = read_endpoint { if let Some(read_endpoint) = read_endpoint {
return Ok((read_endpoint, endpoint)); return Ok((read_endpoint, endpoint));
} else {
write_endpoint = Some(endpoint);
} }
write_endpoint = Some(endpoint);
} }
} }
} }
@@ -136,18 +139,43 @@ impl USBTransport {
Err(RustADBError::USBNoDescriptorFound) Err(RustADBError::USBNoDescriptorFound)
} }
fn write_bulk_data(&self, data: &[u8], timeout: Duration) -> Result<()> {
let endpoint = self.get_write_endpoint()?;
let handle = self.get_raw_connection()?;
let max_packet_size = endpoint.max_packet_size;
let mut offset = 0;
let data_len = data.len();
while offset < data_len {
let end = (offset + max_packet_size).min(data_len);
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}",);
}
if offset % max_packet_size == 0 {
log::trace!("must send final zero-length packet");
handle.write_bulk(endpoint.address, &[], timeout)?;
}
Ok(())
}
} }
impl ADBTransport for USBTransport { impl ADBTransport for RusbTransport {
fn connect(&mut self) -> crate::Result<()> { fn connect(&mut self) -> crate::Result<()> {
let device = self.device.open()?; 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)?; Self::configure_endpoint(&device, &read_endpoint)?;
log::debug!("got read endpoint: {read_endpoint:?}");
self.read_endpoint = Some(read_endpoint); self.read_endpoint = Some(read_endpoint);
Self::configure_endpoint(&device, &write_endpoint)?; Self::configure_endpoint(&device, &write_endpoint)?;
log::debug!("got write endpoint: {write_endpoint:?}");
self.write_endpoint = Some(write_endpoint); self.write_endpoint = Some(write_endpoint);
self.handle = Some(Arc::new(device)); self.handle = Some(Arc::new(device));
@@ -157,39 +185,39 @@ impl ADBTransport for USBTransport {
fn disconnect(&mut self) -> crate::Result<()> { fn disconnect(&mut self) -> crate::Result<()> {
let message = ADBTransportMessage::new(MessageCommand::Clse, 0, 0, &[]); let message = ADBTransportMessage::new(MessageCommand::Clse, 0, 0, &[]);
self.write_message(message) if let Err(e) = self.write_message(message) {
log::error!("error while sending CLSE message: {e}");
}
if let Some(handle) = &self.handle {
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"),
Err(e) => log::error!("error while release interface: {e}"),
}
}
}
Ok(())
} }
} }
impl ADBMessageTransport for USBTransport { impl ADBMessageTransport for RusbTransport {
fn write_message_with_timeout( fn write_message_with_timeout(
&mut self, &mut self,
message: ADBTransportMessage, message: ADBTransportMessage,
timeout: Duration, timeout: Duration,
) -> Result<()> { ) -> Result<()> {
let endpoint = self.get_write_endpoint()?;
let handle = self.get_raw_connection()?;
let message_bytes = message.header().as_bytes()?; let message_bytes = message.header().as_bytes()?;
let mut total_written = 0; self.write_bulk_data(&message_bytes, timeout)?;
loop {
total_written += log::trace!("successfully write header: {} bytes", message_bytes.len());
handle.write_bulk(endpoint.address, &message_bytes[total_written..], timeout)?;
if total_written == message_bytes.len() {
break;
}
}
let payload = message.into_payload(); let payload = message.into_payload();
if !payload.is_empty() { if !payload.is_empty() {
let mut total_written = 0; self.write_bulk_data(&payload, timeout)?;
loop { log::trace!("successfully write payload: {} bytes", payload.len());
total_written +=
handle.write_bulk(endpoint.address, &payload[total_written..], timeout)?;
if total_written == payload.len() {
break;
}
}
} }
Ok(()) Ok(())
@@ -198,29 +226,26 @@ impl ADBMessageTransport for USBTransport {
fn read_message_with_timeout(&mut self, timeout: Duration) -> Result<ADBTransportMessage> { fn read_message_with_timeout(&mut self, timeout: Duration) -> Result<ADBTransportMessage> {
let endpoint = self.get_read_endpoint()?; let endpoint = self.get_read_endpoint()?;
let handle = self.get_raw_connection()?; let handle = self.get_raw_connection()?;
let max_packet_size = endpoint.max_packet_size;
let mut data = [0; 24]; let mut data = [0u8; 24];
let mut total_read = 0; let mut offset = 0;
loop { while offset < data.len() {
total_read += handle.read_bulk(endpoint.address, &mut data[total_read..], timeout)?; let end = (offset + max_packet_size).min(data.len());
if total_read == data.len() { let chunk = &mut data[offset..end];
break; offset += handle.read_bulk(endpoint.address, chunk, timeout)?;
}
} }
let header = ADBTransportMessageHeader::try_from(data)?; let header = ADBTransportMessageHeader::try_from(data)?;
log::trace!("received header {header:?}"); log::trace!("received header {header:?}");
if header.data_length() != 0 { if header.data_length() != 0 {
let mut msg_data = vec![0_u8; header.data_length() as usize]; let mut msg_data = vec![0_u8; header.data_length() as usize];
let mut total_read = 0; let mut offset = 0;
loop { while offset < msg_data.len() {
total_read += let end = (offset + max_packet_size).min(msg_data.len());
handle.read_bulk(endpoint.address, &mut msg_data[total_read..], timeout)?; let chunk = &mut msg_data[offset..end];
if total_read == msg_data.capacity() { offset += handle.read_bulk(endpoint.address, chunk, timeout)?;
break;
}
} }
let message = ADBTransportMessage::from_header_and_payload(header, msg_data); let message = ADBTransportMessage::from_header_and_payload(header, msg_data);

View File

@@ -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!()
}
}

View 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};

View 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
}

View File

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

View File

@@ -1,15 +1,13 @@
mod adb_request_status; mod adb_request_status;
mod adb_server_command;
mod adb_stat_response; mod adb_stat_response;
mod framebuffer_info; mod framebuffer_info;
mod host_features; mod host_features;
mod reboot_type; mod reboot_type;
mod sync_command; mod sync_command;
pub use adb_request_status::AdbRequestStatus; pub(crate) use adb_request_status::AdbRequestStatus;
pub(crate) use adb_server_command::AdbServerCommand;
pub use adb_stat_response::AdbStatResponse; pub use adb_stat_response::AdbStatResponse;
pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2}; pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2};
pub use host_features::HostFeatures; pub use host_features::HostFeatures;
pub use reboot_type::RebootType; pub use reboot_type::RebootType;
pub use sync_command::SyncCommand; pub(crate) use sync_command::SyncCommand;

View File

@@ -13,6 +13,8 @@ pub enum RebootType {
Sideload, Sideload,
/// Same as `Sideload` but reboots after sideloading /// Same as `Sideload` but reboots after sideloading
SideloadAutoReboot, SideloadAutoReboot,
/// Reboots to fastboot
Fastboot,
} }
impl Display for RebootType { impl Display for RebootType {
@@ -23,6 +25,7 @@ impl Display for RebootType {
RebootType::Recovery => write!(f, "recovery"), RebootType::Recovery => write!(f, "recovery"),
RebootType::Sideload => write!(f, "sideload"), RebootType::Sideload => write!(f, "sideload"),
RebootType::SideloadAutoReboot => write!(f, "sideload-auto-reboot"), RebootType::SideloadAutoReboot => write!(f, "sideload-auto-reboot"),
RebootType::Fastboot => write!(f, "fastboot"),
} }
} }
} }

View 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();
```

View File

@@ -1,7 +1,7 @@
use crate::ADBTransport; use crate::ADBTransport;
use crate::Result; use crate::Result;
use crate::RustADBError; use crate::RustADBError;
use crate::TCPServerTransport; use crate::server::tcp_server_transport::TCPServerTransport;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
use std::process::Command; use std::process::Command;
@@ -9,30 +9,44 @@ use std::process::Command;
/// Represents an ADB Server /// Represents an ADB Server
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct ADBServer { pub struct ADBServer {
/// Internal [TcpStream], lazily initialized /// Internal [`TcpStream`], lazily initialized
pub(crate) transport: Option<TCPServerTransport>, pub(crate) transport: Option<TCPServerTransport>,
/// Address to connect to /// Address to connect to
pub(crate) socket_addr: Option<SocketAddrV4>, pub(crate) socket_addr: Option<SocketAddrV4>,
/// adb-server start envs /// adb-server start envs
pub(crate) envs: HashMap<String, String>, pub(crate) envs: HashMap<String, String>,
/// Path to adb binary
/// If not set, will use adb from PATH
pub(crate) adb_path: Option<String>,
} }
impl ADBServer { impl ADBServer {
/// Instantiates a new [ADBServer] /// Instantiates a new [`ADBServer`]
pub fn new(address: SocketAddrV4) -> Self { pub fn new(address: SocketAddrV4) -> Self {
Self { Self {
transport: None, transport: None,
socket_addr: Some(address), socket_addr: Some(address),
envs: HashMap::new(), envs: HashMap::new(),
adb_path: None,
}
}
/// Instantiates a new [`ADBServer`] with a custom adb path
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
Self {
transport: None,
socket_addr: Some(address),
envs: HashMap::new(),
adb_path,
} }
} }
/// Start an instance of `adb-server` /// Start an instance of `adb-server`
pub fn start(envs: &HashMap<String, String>) { pub fn start(envs: &HashMap<String, String>, adb_path: &Option<String>) {
// ADB Server is local, we start it if not already running // ADB Server is local, we start it if not already running
let mut command = Command::new("adb"); let mut command = Command::new(adb_path.as_deref().unwrap_or("adb"));
command.arg("start-server"); 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); command.env(env_k, env_v);
} }
@@ -47,7 +61,7 @@ impl ADBServer {
match child { match child {
Ok(mut child) => { Ok(mut child) => {
if let Err(e) = child.wait() { 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}"), Err(e) => log::error!("error while starting adb server: {e}"),
@@ -79,7 +93,7 @@ impl ADBServer {
}; };
if is_local_ip { if is_local_ip {
Self::start(&self.envs); Self::start(&self.envs, &self.adb_path);
} }
transport.connect()?; transport.connect()?;
@@ -91,7 +105,7 @@ impl ADBServer {
impl Drop for ADBServer { impl Drop for ADBServer {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(ref mut transport) = &mut self.transport { if let Some(transport) = &mut self.transport {
let _ = transport.disconnect(); let _ = transport.disconnect();
} }
} }

View File

@@ -1,8 +1,10 @@
use std::fmt::Display; use std::fmt::Display;
use crate::{WaitForDeviceState, WaitForDeviceTransport}; use crate::{
RebootType,
server::{WaitForDeviceState, WaitForDeviceTransport},
};
use super::RebootType;
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
pub(crate) enum AdbServerCommand { pub(crate) enum AdbServerCommand {
@@ -63,8 +65,8 @@ impl Display for AdbServerCommand {
AdbServerCommand::Reboot(reboot_type) => { AdbServerCommand::Reboot(reboot_type) => {
write!(f, "reboot:{reboot_type}") write!(f, "reboot:{reboot_type}")
} }
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{}", addr), AdbServerCommand::Connect(addr) => write!(f, "host:connect:{addr}"),
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{}", addr), AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{addr}"),
AdbServerCommand::Pair(addr, code) => { AdbServerCommand::Pair(addr, code) => {
write!(f, "host:pair:{code}:{addr}") write!(f, "host:pair:{code}:{addr}")
} }

View File

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

View File

@@ -1,8 +1,10 @@
use std::io::Read; use std::io::Read;
use crate::{ use crate::{
models::AdbServerCommand, ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, Result, RustADBError,
DeviceShort, Result, RustADBError, emulator::ADBEmulatorDevice,
server::{ADBServer, AdbServerCommand, DeviceLong, DeviceShort},
server_device::ADBServerDevice,
}; };
impl ADBServer { impl ADBServer {
@@ -36,7 +38,7 @@ impl ADBServer {
break; break;
} }
vec_devices.push(DeviceLong::try_from(device.to_vec())?); vec_devices.push(DeviceLong::try_from(device)?);
} }
Ok(vec_devices) Ok(vec_devices)
@@ -69,12 +71,12 @@ impl ADBServer {
.filter(|d| d.identifier.as_str() == name) .filter(|d| d.identifier.as_str() == name)
.collect::<Vec<DeviceShort>>() .collect::<Vec<DeviceShort>>()
.len(); .len();
if nb_devices != 1 { if nb_devices == 1 {
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
} else {
Err(RustADBError::DeviceNotFound(format!( Err(RustADBError::DeviceNotFound(format!(
"could not find device {name}" "could not find device {name}"
))) )))
} else {
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
} }
} }

View File

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

View File

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

View File

@@ -1,7 +1,8 @@
use std::io::BufRead; use std::io::BufRead;
use crate::{ use crate::{
models::AdbServerCommand, server::models::MDNSBackend, ADBServer, MDNSServices, Result, Result,
server::{ADBServer, AdbServerCommand, MDNSServices, models::MDNSBackend},
}; };
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN"; const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";
@@ -32,7 +33,7 @@ impl ADBServer {
Ok(service) => { Ok(service) => {
vec_services.push(MDNSServices::try_from(service.as_bytes())?); vec_services.push(MDNSServices::try_from(service.as_bytes())?);
} }
Err(e) => log::error!("{}", e), Err(e) => log::error!("{e}"),
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,11 +2,12 @@ use std::str::FromStr;
use std::sync::LazyLock; use std::sync::LazyLock;
use std::{fmt::Display, str}; use std::{fmt::Display, str};
use crate::{DeviceState, RustADBError}; use crate::RustADBError;
use crate::server::DeviceState;
use regex::bytes::Regex; use regex::bytes::Regex;
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| { static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(?P<identifier>\S+)\s+(?P<state>\w+)\s+(usb:(?P<usb1>\S+)|(?P<usb2>\S+))?\s*(product:(?P<product>\w+)\s+model:(?P<model>\w+)\s+device:(?P<device>\w+)\s+)?transport_id:(?P<transport_id>\d+)$").expect("cannot build devices long regex") Regex::new(r"^(?P<identifier>\S+)\s+(?P<state>\w+)\s+(usb:(?P<usb1>\S+)|(?P<usb2>\S+))?\s*(product:(?P<product>\S+)\s+model:(?P<model>\w+)\s+device:(?P<device>\S+)\s+)?transport_id:(?P<transport_id>\d+)$").expect("cannot build devices long regex")
}); });
/// Represents a new device with more informations. /// Represents a new device with more informations.
@@ -44,12 +45,12 @@ impl Display for DeviceLong {
} }
} }
impl TryFrom<Vec<u8>> for DeviceLong { impl TryFrom<&[u8]> for DeviceLong {
type Error = RustADBError; type Error = RustADBError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> { fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let groups = DEVICES_LONG_REGEX let groups = DEVICES_LONG_REGEX
.captures(&value) .captures(value)
.ok_or(RustADBError::RegexParsingError)?; .ok_or(RustADBError::RegexParsingError)?;
Ok(DeviceLong { Ok(DeviceLong {
@@ -86,15 +87,27 @@ impl TryFrom<Vec<u8>> for DeviceLong {
None => "Unk".to_string(), None => "Unk".to_string(),
Some(device) => String::from_utf8(device.as_bytes().to_vec())?, Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
}, },
transport_id: u32::from_str_radix( transport_id: (str::from_utf8(
str::from_utf8( groups
groups .name("transport_id")
.name("transport_id") .ok_or(RustADBError::RegexParsingError)?
.ok_or(RustADBError::RegexParsingError)? .as_bytes(),
.as_bytes(), )?)
)?, .parse::<u32>()?,
16,
)?,
}) })
} }
} }
#[test]
fn test_static_devices_long() {
let inputs = [
"7a5158f05122195aa device 1-5 product:gts210vewifixx model:SM_T813 device:gts210vewifi transport_id:4",
"n311r05e device usb:0-1.5 product:alioth model:M2012K11AC device:alioth transport_id:58",
"192.168.100.192:5555 device product:alioth model:M2012K11AC device:alioth transport_id:97",
"emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:101",
"QQ20131020250511 device 20-4 product:NOH-AN00 model:NOH_AN00 device:HWNOH transport_id:3",
];
for input in inputs {
DeviceLong::try_from(input.as_bytes()).expect(&format!("cannot parse input: '{input}'"));
}
}

View File

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

View File

@@ -48,11 +48,11 @@ impl Display for UsbBackend {
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default)]
pub enum MDNSBackend { pub enum MDNSBackend {
#[default] #[default]
/// Unknown /// `Unknown`
Unknown = 0, Unknown = 0,
/// Bonjour /// `Bonjour`
Bonjour = 1, Bonjour = 1,
/// OpenScreen /// `OpenScreen`
OpenScreen = 2, OpenScreen = 2,
} }

View File

@@ -2,7 +2,7 @@ use std::fmt::Display;
use crate::RustADBError; use crate::RustADBError;
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
/// List of available transports to wait for. /// List of available transports to wait for.
pub enum WaitForDeviceTransport { pub enum WaitForDeviceTransport {
/// USB transport /// USB transport
@@ -10,15 +10,10 @@ pub enum WaitForDeviceTransport {
/// Local transport /// Local transport
Local, Local,
/// Any transport (default value) /// Any transport (default value)
#[default]
Any, Any,
} }
impl Default for WaitForDeviceTransport {
fn default() -> Self {
Self::Any
}
}
impl Display for WaitForDeviceTransport { impl Display for WaitForDeviceTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {

View File

@@ -4,11 +4,12 @@ use std::str::FromStr;
use byteorder::{ByteOrder, LittleEndian}; use byteorder::{ByteOrder, LittleEndian};
use crate::ADBTransport;
use crate::models::{AdbRequestStatus, SyncCommand}; use crate::models::{AdbRequestStatus, SyncCommand};
use crate::{models::AdbServerCommand, ADBTransport}; use crate::server::AdbServerCommand;
use crate::{Result, RustADBError}; 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; const DEFAULT_SERVER_PORT: u16 = 5037;
/// Server transport running on top on TCP /// Server transport running on top on TCP
@@ -25,7 +26,7 @@ impl Default for TCPServerTransport {
} }
impl TCPServerTransport { impl TCPServerTransport {
/// Instantiates a new instance of [TCPServerTransport] /// Instantiates a new instance of [`TCPServerTransport`]
pub fn new(socket_addr: SocketAddrV4) -> Self { pub fn new(socket_addr: SocketAddrV4) -> Self {
Self { Self {
socket_addr, 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 { pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
match socket_addr { match socket_addr {
Some(s) => Self::new(s), Some(s) => Self::new(s),
@@ -41,7 +42,7 @@ impl TCPServerTransport {
} }
} }
/// Get underlying [SocketAddrV4] /// Get underlying [`SocketAddrV4`]
pub fn get_socketaddr(&self) -> SocketAddrV4 { pub fn get_socketaddr(&self) -> SocketAddrV4 {
self.socket_addr 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<()> { pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> {
// First 4 bytes are the name of the command we want to send // First 4 bytes are the name of the command we want to send
// (e.g. "SEND", "RECV", "STAT", "LIST") // (e.g. "SEND", "RECV", "STAT", "LIST")
@@ -98,22 +99,22 @@ impl TCPServerTransport {
.write_all(command.to_string().as_bytes())?) .write_all(command.to_string().as_bytes())?)
} }
/// Gets the body length from a LittleEndian value /// Gets the body length from a `LittleEndian` value
pub(crate) fn get_body_length(&mut self) -> Result<u32> { pub(crate) fn get_body_length(&self) -> Result<u32> {
let length_buffer = self.read_body_length()?; let length_buffer = self.read_body_length()?;
Ok(LittleEndian::read_u32(&length_buffer)) Ok(LittleEndian::read_u32(&length_buffer))
} }
/// Read 4 bytes representing body length /// 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]; let mut length_buffer = [0; 4];
self.get_raw_connection()?.read_exact(&mut length_buffer)?; self.get_raw_connection()?.read_exact(&mut length_buffer)?;
Ok(length_buffer) Ok(length_buffer)
} }
/// Send the given [AdbCommand] to ADB server, and checks that the request has been taken in consideration. /// 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. /// If an error occurred, a [`RustADBError`] is returned with the response error string.
pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> { pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> {
let adb_command_string = command.to_string(); let adb_command_string = command.to_string();
let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string); let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string);

View 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");
```

View File

@@ -1,4 +1,7 @@
use crate::{models::AdbServerCommand, ADBTransport, Result, TCPServerTransport}; use crate::{
ADBTransport, Result,
server::{AdbServerCommand, TCPServerTransport},
};
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
/// Represents a device connected to the ADB server. /// Represents a device connected to the ADB server.
@@ -6,12 +9,12 @@ use std::net::SocketAddrV4;
pub struct ADBServerDevice { pub struct ADBServerDevice {
/// Unique device identifier. /// Unique device identifier.
pub identifier: Option<String>, pub identifier: Option<String>,
/// Internal [TCPServerTransport] /// Internal [`TCPServerTransport`]
pub(crate) transport: TCPServerTransport, pub(crate) transport: TCPServerTransport,
} }
impl ADBServerDevice { 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 { pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr); 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 { pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr); let transport = TCPServerTransport::new_or_default(server_addr);

View File

@@ -4,13 +4,15 @@ use std::{
}; };
use crate::{ use crate::{
constants::BUFFER_SIZE,
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
ADBDeviceExt, Result, RustADBError, ADBDeviceExt, Result, RustADBError,
models::{AdbStatResponse, HostFeatures},
server::AdbServerCommand,
}; };
use super::ADBServerDevice; use super::ADBServerDevice;
const BUFFER_SIZE: usize = 65535;
impl ADBDeviceExt for ADBServerDevice { impl ADBDeviceExt for ADBServerDevice {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> { fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
let supported_features = self.host_features()?; let supported_features = self.host_features()?;
@@ -25,15 +27,14 @@ impl ADBDeviceExt for ADBServerDevice {
self.transport self.transport
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?; .send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
loop { loop {
let mut buffer = [0; BUFFER_SIZE];
match self.transport.get_raw_connection()?.read(&mut buffer) { match self.transport.get_raw_connection()?.read(&mut buffer) {
Ok(size) => { Ok(size) => {
if size == 0 { if size == 0 {
return Ok(()); return Ok(());
} else {
output.write_all(&buffer[..size])?;
} }
output.write_all(&buffer[..size])?;
} }
Err(e) => { Err(e) => {
return Err(RustADBError::IOError(e)); return Err(RustADBError::IOError(e));
@@ -49,7 +50,7 @@ impl ADBDeviceExt for ADBServerDevice {
fn shell( fn shell(
&mut self, &mut self,
mut reader: &mut dyn Read, mut reader: &mut dyn Read,
mut writer: Box<(dyn Write + Send)>, mut writer: Box<dyn Write + Send>,
) -> Result<()> { ) -> Result<()> {
let supported_features = self.host_features()?; let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2) if !supported_features.contains(&HostFeatures::ShellV2)
@@ -67,8 +68,9 @@ impl ADBDeviceExt for ADBServerDevice {
// Reading thread, reads response from adb-server // Reading thread, reads response from adb-server
std::thread::spawn(move || -> Result<()> { std::thread::spawn(move || -> Result<()> {
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
loop { loop {
let mut buffer = [0; BUFFER_SIZE];
match read_stream.read(&mut buffer) { match read_stream.read(&mut buffer) {
Ok(0) => { Ok(0) => {
read_stream.shutdown(std::net::Shutdown::Both)?; read_stream.shutdown(std::net::Shutdown::Both)?;

View File

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

View File

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

View File

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

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