36 Commits

Author SHA1 Message Date
Corentin LIAUD
5b4be5d5cd feat: improve README.md 2025-09-03 20:53:57 +02:00
Corentin LIAUD
586964128f feat: improve modules ordering 2025-09-01 21:40:40 +02:00
Corentin LIAUD
042ca89f12 fix: python package build 2025-08-27 21:03:45 +02:00
Corentin LIAUD
c6b12008a8 breaking(feature): add usb feature 2025-08-27 21:00:11 +02:00
Corentin LIAUD
2bd0b2ca87 doc: add section in README.md 2025-08-27 19:44:59 +02:00
Corentin LIAUD
1589ee9da5 breaking(features): add mdns feature + example 2025-08-27 19:40:27 +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
114 changed files with 811 additions and 573 deletions

View File

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

View File

@@ -10,10 +10,14 @@ env:
CARGO_TERM_COLOR: always
jobs:
build-release:
name: "build-release"
runs-on: ubuntu-latest
build:
name: "Build on ${{ matrix.os }}"
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v4
- name: Build project
run: cargo build --release --all-features
- uses: actions/checkout@v4
- name: Build project
run: cargo build --release --all-features

View File

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

View File

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

View File

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

View File

@@ -7,10 +7,11 @@ license.workspace = true
name = "adb_cli"
readme = "README.md"
repository.workspace = true
rust-version.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "^2.0.0" }
adb_client = { version = "^2.0.0", features = ["mdns", "usb"] }
anyhow = { version = "1.0.94" }
clap = { version = "4.5.23", features = ["derive"] }
env_logger = { version = "0.11.5" }

View File

@@ -2,6 +2,7 @@
[![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)
![MSRV](https://img.shields.io/crates/msrv/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 :
```shell
cargo install adb_cli
cargo install adb_cli
```
Usage is quite simple, and tends to look like `adb`:
@@ -64,4 +65,4 @@ Options:
-p, --product-id <PID> Hexadecimal product id of this USB device
-k, --private-key <PATH_TO_PRIVATE_KEY> Path to a custom private key to use for authentication
-h, --help Print help
```
```

View File

@@ -2,7 +2,7 @@
use std::os::unix::prelude::{AsRawFd, RawFd};
use termios::{tcsetattr, Termios, TCSANOW, VMIN, VTIME};
use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
use crate::Result;

View File

@@ -1,4 +1,4 @@
use adb_client::ADBEmulatorDevice;
use adb_client::emulator::ADBEmulatorDevice;
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};
@@ -8,7 +11,7 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
match server_command.command {
HostCommand::Version => {
let version = adb_server.version()?;
log::info!("Android Debug Bridge version {}", version);
log::info!("Android Debug Bridge version {version}");
log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
}
HostCommand::Kill => {
@@ -18,18 +21,18 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
if long {
log::info!("List of devices attached (extended)");
for device in adb_server.devices_long()? {
log::info!("{}", device);
log::info!("{device}");
}
} else {
log::info!("List of devices attached");
for device in adb_server.devices()? {
log::info!("{}", device);
log::info!("{device}");
}
}
}
HostCommand::TrackDevices => {
let callback = |device: DeviceShort| {
log::info!("{}", device);
log::info!("{device}");
Ok(())
};
log::info!("Live list of devices attached");
@@ -65,7 +68,7 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
MdnsCommand::Services => {
log::info!("List of discovered 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 adb_client::ADBServerDevice;
use anyhow::{anyhow, Result};
use adb_client::server_device::ADBServerDevice;
use anyhow::{Result, anyhow};
use crate::models::LocalDeviceCommand;

View File

@@ -7,10 +7,16 @@ mod handlers;
mod models;
mod utils;
use adb_client::{
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService,
};
use adb_client::ADBDeviceExt;
use adb_client::mdns::MDNSDiscoveryService;
use adb_client::server::ADBServer;
use adb_client::server_device::ADBServerDevice;
use adb_client::tcp::ADBTcpDevice;
use adb_client::usb::ADBUSBDevice;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use adb_termios::ADBTermios;
use anyhow::Result;
use clap::Parser;
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
@@ -22,9 +28,15 @@ use std::path::Path;
use utils::setup_logger;
fn main() -> Result<()> {
// This depends on `clap`
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.
// Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it.
@@ -47,7 +59,7 @@ fn main() -> Result<()> {
match server_command.command {
LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
LocalCommand::LocalDeviceCommand(local_device_command) => {
return handle_local_commands(device, local_device_command)
return handle_local_commands(device, local_device_command);
}
}
}
@@ -62,7 +74,9 @@ fn main() -> Result<()> {
None => ADBUSBDevice::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)
@@ -104,7 +118,7 @@ fn main() -> Result<()> {
#[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 {
let commands: Vec<&str> = commands.iter().map(|v| v.as_str()).collect();
@@ -121,10 +135,10 @@ fn main() -> Result<()> {
}
DeviceCommands::Stat { path } => {
let stat_response = device.stat(&path)?;
println!("{}", stat_response);
println!("{stat_response}");
}
DeviceCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
log::info!("Reboots device in mode {reboot_type:?}");
device.reboot(reboot_type.into())?
}
DeviceCommands::Push { filename, path } => {
@@ -141,7 +155,7 @@ fn main() -> Result<()> {
device.install(&path)?;
}
DeviceCommands::Uninstall { package } => {
log::info!("Uninstalling the package {}...", package);
log::info!("Uninstalling the package {package}...");
device.uninstall(&package)?;
}
DeviceCommands::Framebuffer { path } => {

View File

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

View File

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

View File

@@ -1,4 +1,8 @@
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
if std::env::var("RUST_LOG").is_err() {
let level = match debug {
@@ -6,7 +10,7 @@ pub fn setup_logger(debug: bool) {
false => "info",
};
std::env::set_var("RUST_LOG", level);
unsafe { std::env::set_var("RUST_LOG", level) };
}
env_logger::init();

View File

@@ -7,36 +7,57 @@ license.workspace = true
name = "adb_client"
readme = "README.md"
repository.workspace = true
rust-version.workspace = true
version.workspace = true
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[features]
default = []
mdns = ["dep:mdns-sd"]
usb = ["dep:rsa", "dep:rusb"]
[dependencies]
base64 = { version = "0.22.1" }
bincode = { version = "1.3.3" }
byteorder = { version = "1.5.0" }
chrono = { version = "0.4.40" }
homedir = { version = "0.3.4" }
image = { version = "0.25.5" }
lazy_static = { version = "1.5.0" }
chrono = { version = "0.4.40", default-features = false, features = ["std"] }
homedir = { version = "= 0.3.4" }
image = { version = "0.25.5", default-features = false }
log = { version = "0.4.26" }
mdns-sd = { version = "0.13.2" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
rand = { version = "0.9.0" }
rcgen = { version = "0.13.1" }
rcgen = { version = "0.13.1", default-features = false, features = [
"aws_lc_rs",
"pem",
] }
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] }
rsa = { version = "0.9.7" }
rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.22" }
rustls-pki-types = "1.11.0"
rustls = { version = "0.23.27" }
rustls-pki-types = { version = "1.11.0" }
serde = { version = "1.0.216", features = ["derive"] }
serde_repr = { version = "0.1.19" }
sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.7" }
#########
# MDNS-only dependencies
mdns-sd = { version = "0.13.9", 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 }
#########
[dev-dependencies]
anyhow = { version = "1.0.93" }
criterion = { version = "0.5.1" } # Used for benchmarks
criterion = { version = "0.6.0" } # Used for benchmarks
[[bench]]
harness = false

View File

@@ -3,6 +3,7 @@
[![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)
[![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.
@@ -15,6 +16,26 @@ Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
adb_client = "*"
```
## Crate features
| Feature | Description | Default? |
| :-----: | :---------------------------------------------: | :------: |
| `mdns` | Enables mDNS device discovery on local network. | No |
| `usb` | Enables interactions with USB devices. | No |
To deactivate some features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
```toml
[dependencies]
adb_client = { version = "*" }
```
## Examples
Usage examples can be found in the `examples/` directory of this repository.
Some example are also provided in the various `README.md` files of modules.
## Benchmarks
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
@@ -23,89 +44,8 @@ Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel
`ADBServerDevice` performs all operations by using adb server as a bridge.
|File size|Sample size|`ADBServerDevice`|`adb`|Difference|
|:-------:|:---------:|:----------:|:---:|:-----:|
|10 MB|100|350,79 ms|356,30 ms|<div style="color:green">-1,57 %</div>|
|500 MB|50|15,60 s|15,64 s|<div style="color:green">-0,25 %</div>|
|1 GB|20|31,09 s|31,12 s|<div style="color:green">-0,10 %</div>|
## Examples
### Get available ADB devices
```rust no_run
use adb_client::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```
### Using ADB server as bridge
#### Launch a command on device
```rust no_run
use adb_client::{ADBServer, ADBDeviceExt};
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### Push a file to the device
```rust no_run
use adb_client::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```
### Interact directly with end devices
#### (USB) Launch a command on device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(&["df", "-h"], &mut std::io::stdout());
```
#### (USB) Push a file to the device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
use std::fs::File;
use std::path::Path;
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, &"/data/local/tmp");
```
#### (TCP) Get a shell from device
```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use adb_client::{ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
```
| File size | Sample size | `ADBServerDevice` | `adb` | Difference |
| :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
| 10 MB | 100 | 350,79 ms | 356,30 ms | <div style="color:green">-1,57 %</div> |
| 500 MB | 50 | 15,60 s | 15,64 s | <div style="color:green">-0,25 %</div> |
| 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |

View File

@@ -6,14 +6,14 @@ use image::{ImageBuffer, ImageFormat, Rgba};
use crate::models::AdbStatResponse;
use crate::{RebootType, Result};
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
/// Trait representing all features available on both [`crate::server_device::ADBServerDevice`] and [`crate::usb::ADBUSBDevice`]
pub trait ADBDeviceExt {
/// Runs command in a shell on the device, and write its output and error streams into output.
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
/// Starts an interactive shell session on the device.
/// Input data is read from reader and write to writer.
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()>;
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()>;
/// Display the stat information for a remote file
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;

View File

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

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,
};
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
use crate::{
ADBTransport, Result, RustADBError, emulator::tcp_emulator_transport::TCPEmulatorTransport,
server_device::ADBServerDevice,
};
use regex::Regex;
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
@@ -30,8 +33,7 @@ impl ADBEmulatorDevice {
let groups = EMULATOR_REGEX
.captures(&identifier)
.ok_or(RustADBError::DeviceNotFound(format!(
"Device {} is likely not an emulator",
identifier
"Device {identifier} is likely not an emulator"
)))?;
let port = groups

View File

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

View File

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

View File

@@ -6,8 +6,9 @@ use std::{
use homedir::my_home;
use super::ADBTransport;
use crate::{emulator_device::ADBEmulatorCommand, Result, RustADBError};
use crate::{
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
};
/// Emulator transport running on top on TCP.
#[derive(Debug)]

View File

@@ -67,6 +67,8 @@ pub enum RustADBError {
#[error("Cannot get home directory")]
NoHomeDirectory,
/// Generic USB error
#[cfg(feature = "usb")]
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
#[error("USB Error: {0}")]
UsbError(#[from] rusb::Error),
/// USB device not found
@@ -85,6 +87,8 @@ pub enum RustADBError {
#[error(transparent)]
Base64EncodeError(#[from] base64::EncodeSliceError),
/// An error occurred with RSA engine
#[cfg(feature = "usb")]
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
#[error(transparent)]
RSAError(#[from] rsa::errors::Error),
/// Cannot convert given data from slice
@@ -94,6 +98,8 @@ pub enum RustADBError {
#[error("wrong file extension: {0}")]
WrongFileExtension(String),
/// An error occurred with PKCS8 data
#[cfg(feature = "usb")]
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
#[error("error with pkcs8: {0}")]
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
/// Error during certificate generation
@@ -112,11 +118,13 @@ pub enum RustADBError {
#[error("upgrade error: {0}")]
UpgradeError(String),
/// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)]
MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
#[error("error sending data to channel")]
SendError,
/// An unknown transport has been provided
#[error("unknown transport: {0}")]
UnknownTransport(String),

View File

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

View File

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

View File

@@ -2,9 +2,16 @@ use byteorder::{LittleEndian, ReadBytesExt};
use rand::Rng;
use std::io::{Cursor, Read, Seek};
use crate::{constants::BUFFER_SIZE, ADBMessageTransport, AdbStatResponse, Result, RustADBError};
use crate::{
AdbStatResponse, Result, RustADBError,
message_devices::{
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
},
};
use super::{models::MessageSubcommand, ADBTransportMessage, MessageCommand};
const BUFFER_SIZE: usize = 65535;
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
/// Structure is totally agnostic over which transport is truly used.
@@ -144,9 +151,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
MessageCommand::Write => return Ok(()),
c => {
return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
)))
"Wrong command received {c}"
)));
}
}
}

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::{
io::{Read, Write},
path::Path,
};
use super::ADBMessageDevice;
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
self.shell_command(command, output)
}
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()> {
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.shell(reader, writer)
}

View File

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

View File

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

View File

@@ -4,9 +4,12 @@ use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, Rgba};
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},
ADBMessageTransport, Result, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {

View File

@@ -1,11 +1,12 @@
use std::{fs::File, path::Path};
use rand::Rng;
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,
ADBMessageTransport, Result,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -16,15 +17,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let file_size = apk_file.metadata()?.len();
let mut rng = rand::rng();
let local_id = rng.random();
self.open_session(format!("exec:cmd package 'install' -S {}\0", file_size).as_bytes())?;
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?;
let transport = self.get_transport().clone();
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)?;

View File

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

View File

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

View File

@@ -1,11 +1,13 @@
use std::io::Read;
use crate::{
device::{
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand,
MessageSubcommand,
Result, RustADBError,
message_devices::{
adb_message_device::ADBMessageDevice,
adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage,
message_commands::{MessageCommand, MessageSubcommand},
},
ADBMessageTransport, Result, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {

View File

@@ -1,11 +1,14 @@
use crate::{
device::{adb_message_device::ADBMessageDevice, MessageCommand},
ADBMessageTransport, RebootType, Result,
RebootType, Result,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
message_commands::MessageCommand,
},
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
self.open_session(format!("reboot:{}\0", reboot_type).as_bytes())?;
self.open_session(format!("reboot:{reboot_type}\0").as_bytes())?;
self.get_transport_mut()
.read_message()

View File

@@ -1,10 +1,12 @@
use std::io::{ErrorKind, Read, Write};
use crate::device::ShellMessageWriter;
use crate::Result;
use crate::{
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
ADBMessageTransport, RustADBError,
Result, RustADBError,
message_devices::{
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
adb_transport_message::ADBTransportMessage, commands::utils::ShellMessageWriter,
message_commands::MessageCommand,
},
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
@@ -36,7 +38,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn shell(
&mut self,
mut reader: &mut dyn Read,
mut writer: Box<(dyn Write + Send)>,
mut writer: Box<dyn Write + Send>,
) -> Result<()> {
self.open_session(b"shell:\0")?;

View File

@@ -1,5 +1,8 @@
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> {

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> {
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {
self.open_session(format!("exec:cmd package 'uninstall' {}\0", package_name).as_bytes())?;
self.open_session(format!("exec:cmd package 'uninstall' {package_name}\0").as_bytes())?;
let final_status = self.get_transport_mut().read_message()?;
match final_status.into_payload().as_slice() {
b"Success\n" => {
log::info!("Package {} successfully uninstalled", package_name);
log::info!("Package {package_name} successfully uninstalled");
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(

View File

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

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 crate::ADBMessageTransport;
use super::{models::MessageCommand, ADBTransportMessage};
use crate::message_devices::{
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
message_commands::MessageCommand,
};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
pub struct ShellMessageWriter<T: ADBMessageTransport> {

View File

@@ -0,0 +1,14 @@
/// USB-related definitions
#[cfg(feature = "usb")]
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
pub mod usb;
/// Device reachable over TCP related definition
pub mod tcp;
mod adb_message_device;
mod adb_message_device_commands;
mod adb_message_transport;
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

@@ -2,10 +2,12 @@ use std::io::Write;
use std::path::Path;
use std::{io::Read, net::SocketAddr};
use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand;
use super::ADBTransportMessage;
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport};
use crate::message_devices::adb_message_device::ADBMessageDevice;
use crate::message_devices::adb_message_transport::ADBMessageTransport;
use crate::message_devices::adb_transport_message::ADBTransportMessage;
use crate::message_devices::message_commands::MessageCommand;
use crate::tcp::tcp_transport::TcpTransport;
use crate::{ADBDeviceExt, ADBTransport, Result};
/// Represent a device reached and available over USB.
#[derive(Debug)]
@@ -75,7 +77,7 @@ impl ADBDeviceExt for ADBTcpDevice {
}
#[inline]
fn shell(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()> {
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}

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,16 +1,19 @@
use rcgen::{CertificateParams, KeyPair, PKCS_RSA_SHA256};
use rustls::{
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{pem::PemObject, CertificateDer, PrivatePkcs8KeyDer},
ClientConfig, ClientConnection, KeyLogFile, SignatureScheme, StreamOwned,
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{CertificateDer, PrivatePkcs8KeyDer, pem::PemObject},
};
use super::{ADBMessageTransport, ADBTransport};
use crate::{
device::{
get_default_adb_key_path, ADBTransportMessage, ADBTransportMessageHeader, MessageCommand,
},
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::{
fs::read_to_string,
@@ -109,7 +112,7 @@ impl TcpTransport {
})
}
fn get_current_connection(&mut self) -> Result<Arc<Mutex<CurrentConnection>>> {
fn get_current_connection(&self) -> Result<Arc<Mutex<CurrentConnection>>> {
self.current_connection
.as_ref()
.ok_or(RustADBError::IOError(std::io::Error::new(
@@ -125,7 +128,7 @@ impl TcpTransport {
None => {
return Err(RustADBError::UpgradeError(
"cannot upgrade a non-existing connection...".into(),
))
));
}
};
@@ -162,7 +165,7 @@ impl TcpTransport {
CurrentConnection::Tls(_) => {
return Err(RustADBError::UpgradeError(
"cannot upgrade a TLS connection...".into(),
))
));
}
}
}
@@ -175,8 +178,7 @@ impl TcpTransport {
Ok(())
}
c => Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
"Wrong command received {c}"
))),
}
}
@@ -212,7 +214,7 @@ impl ADBMessageTransport for TcpTransport {
fn read_message_with_timeout(
&mut self,
read_timeout: std::time::Duration,
) -> Result<crate::device::ADBTransportMessage> {
) -> Result<ADBTransportMessage> {
let raw_connection_lock = self.get_current_connection()?;
let mut raw_connection = raw_connection_lock.lock()?;

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(Path::new("/tmp/file.txt")).expect("Cannot open file");
device.push(&mut input, &"/data/local/tmp");
```

View File

@@ -1,8 +1,8 @@
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_traits::cast::ToPrimitive;
use num_traits::FromPrimitive;
use num_traits::cast::ToPrimitive;
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PublicKeyParts;
use rsa::{Pkcs1v15Sign, RsaPrivateKey};

View File

@@ -1,7 +1,7 @@
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use rusb::Device;
use rusb::DeviceDescriptor;
use rusb::UsbContext;
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use std::fs::read_to_string;
use std::io::Read;
use std::io::Write;
@@ -9,29 +9,41 @@ 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};
use crate::Result;
use crate::RustADBError;
use crate::adb_transport::ADBTransport;
use crate::message_devices::adb_message_device::ADBMessageDevice;
use crate::message_devices::adb_message_transport::ADBMessageTransport;
use crate::message_devices::adb_transport_message::ADBTransportMessage;
use crate::message_devices::message_commands::MessageCommand;
use crate::usb::adb_rsa_key::ADBRsaKey;
use crate::usb::usb_transport::USBTransport;
use crate::utils::get_default_adb_key_path;
const AUTH_TOKEN: u32 = 1;
const AUTH_SIGNATURE: u32 = 2;
const AUTH_RSAPUBLICKEY: u32 = 3;
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
}
}
})?)
// Try to read the private key file from given path
// If the file is not found, return None
// If there is another error while reading the file, return this error
// Else, return the private key content
let pk = match read_to_string(private_key_path.as_ref()) {
Ok(pk) => pk,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
match ADBRsaKey::new_from_pkcs8(&pk) {
Ok(pk) => Ok(Some(pk)),
Err(e) => Err(e),
}
}
/// Search for adb devices with known interface class and subclass values
fn search_adb_devices() -> Result<Option<(u16, u16)>> {
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 {
@@ -51,13 +63,13 @@ fn search_adb_devices() -> Result<Option<(u16, u16)>> {
(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
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
))),
}
}
fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
/// Check whether a device with given descriptor is an ADB device
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
const ADB_SUBCLASS: u8 = 0x42;
const ADB_PROTOCOL: u8 = 0x1;
@@ -87,14 +99,6 @@ fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> b
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 {
@@ -134,9 +138,15 @@ impl ADBUSBDevice {
transport: USBTransport,
private_key_path: PathBuf,
) -> Result<Self> {
let private_key = match read_adb_private_key(private_key_path)? {
let private_key = match read_adb_private_key(&private_key_path)? {
Some(pk) => pk,
None => ADBRsaKey::new_random()?,
None => {
log::warn!(
"No private key found at path {}. Using a temporary random one.",
private_key_path.display()
);
ADBRsaKey::new_random()?
}
};
let mut s = Self {
@@ -180,6 +190,11 @@ impl ADBUSBDevice {
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
@@ -188,7 +203,7 @@ impl ADBUSBDevice {
v => {
return Err(RustADBError::ADBRequestFailed(format!(
"Received AUTH message with type != 1 ({v})"
)))
)));
}
};
@@ -244,7 +259,7 @@ impl ADBDeviceExt for ADBUSBDevice {
}
#[inline]
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<(dyn Write + Send)>) -> Result<()> {
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.inner.shell(reader, writer)
}

View File

@@ -0,0 +1,8 @@
#![doc = include_str!("./README.md")]
mod adb_rsa_key;
mod adb_usb_device;
mod usb_transport;
pub use adb_usb_device::ADBUSBDevice;
pub use usb_transport::USBTransport;

View File

@@ -1,20 +1,25 @@
use std::{sync::Arc, time::Duration};
use rusb::{
constants::LIBUSB_CLASS_VENDOR_SPEC, Device, DeviceHandle, Direction, GlobalContext,
TransferType,
Device, DeviceHandle, Direction, GlobalContext, TransferType,
constants::LIBUSB_CLASS_VENDOR_SPEC,
};
use super::{ADBMessageTransport, ADBTransport};
use crate::{
device::{ADBTransportMessage, ADBTransportMessageHeader, MessageCommand},
Result, RustADBError,
adb_transport::ADBTransport,
message_devices::{
adb_message_transport::ADBMessageTransport,
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
message_commands::MessageCommand,
},
};
#[derive(Clone, Debug)]
struct Endpoint {
iface: u8,
address: u8,
max_packet_size: usize,
}
/// Transport running on USB
@@ -39,8 +44,7 @@ impl USBTransport {
}
Err(RustADBError::DeviceNotFound(format!(
"cannot find USB device with vendor_id={} and product_id={}",
vendor_id, product_id
"cannot find USB device with vendor_id={vendor_id} and product_id={product_id}",
)))
}
@@ -111,6 +115,7 @@ impl USBTransport {
let endpoint = Endpoint {
iface: interface_desc.interface_number(),
address: endpoint_desc.address(),
max_packet_size: endpoint_desc.max_packet_size() as usize,
};
match endpoint_desc.direction() {
Direction::In => {
@@ -136,6 +141,29 @@ impl USBTransport {
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 {
@@ -145,9 +173,11 @@ impl ADBTransport for USBTransport {
let (read_endpoint, write_endpoint) = self.find_endpoints(&device)?;
Self::configure_endpoint(&device, &read_endpoint)?;
log::debug!("got read endpoint: {read_endpoint:?}");
self.read_endpoint = Some(read_endpoint);
Self::configure_endpoint(&device, &write_endpoint)?;
log::debug!("got write endpoint: {write_endpoint:?}");
self.write_endpoint = Some(write_endpoint);
self.handle = Some(Arc::new(device));
@@ -157,7 +187,21 @@ impl ADBTransport for USBTransport {
fn disconnect(&mut self) -> crate::Result<()> {
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(())
}
}
@@ -167,29 +211,15 @@ impl ADBMessageTransport for USBTransport {
message: ADBTransportMessage,
timeout: Duration,
) -> Result<()> {
let endpoint = self.get_write_endpoint()?;
let handle = self.get_raw_connection()?;
let message_bytes = message.header().as_bytes()?;
let mut total_written = 0;
loop {
total_written +=
handle.write_bulk(endpoint.address, &message_bytes[total_written..], timeout)?;
if total_written == message_bytes.len() {
break;
}
}
self.write_bulk_data(&message_bytes, timeout)?;
log::trace!("successfully write header: {} bytes", message_bytes.len());
let payload = message.into_payload();
if !payload.is_empty() {
let mut total_written = 0;
loop {
total_written +=
handle.write_bulk(endpoint.address, &payload[total_written..], timeout)?;
if total_written == payload.len() {
break;
}
}
self.write_bulk_data(&payload, timeout)?;
log::trace!("successfully write payload: {} bytes", payload.len());
}
Ok(())
@@ -198,29 +228,26 @@ impl ADBMessageTransport for USBTransport {
fn read_message_with_timeout(&mut self, timeout: Duration) -> Result<ADBTransportMessage> {
let endpoint = self.get_read_endpoint()?;
let handle = self.get_raw_connection()?;
let max_packet_size = endpoint.max_packet_size;
let mut data = [0; 24];
let mut total_read = 0;
loop {
total_read += handle.read_bulk(endpoint.address, &mut data[total_read..], timeout)?;
if total_read == data.len() {
break;
}
let mut data = [0u8; 24];
let mut offset = 0;
while offset < data.len() {
let end = (offset + max_packet_size).min(data.len());
let chunk = &mut data[offset..end];
offset += handle.read_bulk(endpoint.address, chunk, timeout)?;
}
let header = ADBTransportMessageHeader::try_from(data)?;
log::trace!("received header {header:?}");
if header.data_length() != 0 {
let mut msg_data = vec![0_u8; header.data_length() as usize];
let mut total_read = 0;
loop {
total_read +=
handle.read_bulk(endpoint.address, &mut msg_data[total_read..], timeout)?;
if total_read == msg_data.capacity() {
break;
}
let mut offset = 0;
while offset < msg_data.len() {
let end = (offset + max_packet_size).min(msg_data.len());
let chunk = &mut msg_data[offset..end];
offset += handle.read_bulk(endpoint.address, chunk, timeout)?;
}
let message = ADBTransportMessage::from_header_and_payload(header, msg_data);

View File

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

View File

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

View File

@@ -13,6 +13,8 @@ pub enum RebootType {
Sideload,
/// Same as `Sideload` but reboots after sideloading
SideloadAutoReboot,
/// Reboots to fastboot
Fastboot,
}
impl Display for RebootType {
@@ -23,6 +25,7 @@ impl Display for RebootType {
RebootType::Recovery => write!(f, "recovery"),
RebootType::Sideload => write!(f, "sideload"),
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::Result;
use crate::RustADBError;
use crate::TCPServerTransport;
use crate::server::tcp_server_transport::TCPServerTransport;
use std::collections::HashMap;
use std::net::SocketAddrV4;
use std::process::Command;
@@ -105,7 +105,7 @@ impl ADBServer {
impl Drop for ADBServer {
fn drop(&mut self) {
if let Some(ref mut transport) = &mut self.transport {
if let Some(transport) = &mut self.transport {
let _ = transport.disconnect();
}
}

View File

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

View File

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

View File

@@ -1,8 +1,10 @@
use std::io::Read;
use crate::{
models::AdbServerCommand, ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong,
DeviceShort, Result, RustADBError,
Result, RustADBError,
emulator::ADBEmulatorDevice,
server::{ADBServer, AdbServerCommand, DeviceLong, DeviceShort},
server_device::ADBServerDevice,
};
impl ADBServer {
@@ -36,7 +38,7 @@ impl ADBServer {
break;
}
vec_devices.push(DeviceLong::try_from(device.to_vec())?);
vec_devices.push(DeviceLong::try_from(device)?);
}
Ok(vec_devices)

View File

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

View File

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

View File

@@ -1,7 +1,8 @@
use std::io::BufRead;
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";
@@ -32,7 +33,7 @@ impl ADBServer {
Ok(service) => {
vec_services.push(MDNSServices::try_from(service.as_bytes())?);
}
Err(e) => log::error!("{}", e),
Err(e) => log::error!("{e}"),
}
}

View File

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

View File

@@ -1,4 +1,7 @@
use crate::{models::AdbServerCommand, ADBServer, Result};
use crate::{
Result,
server::{ADBServer, AdbServerCommand},
};
impl ADBServer {
/// 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 {
/// 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 {
/// Gets server's internal version number.

View File

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

View File

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

View File

@@ -2,11 +2,12 @@ use std::str::FromStr;
use std::sync::LazyLock;
use std::{fmt::Display, str};
use crate::{DeviceState, RustADBError};
use crate::RustADBError;
use crate::server::DeviceState;
use regex::bytes::Regex;
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
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.
@@ -44,12 +45,12 @@ impl Display for DeviceLong {
}
}
impl TryFrom<Vec<u8>> for DeviceLong {
impl TryFrom<&[u8]> for DeviceLong {
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
.captures(&value)
.captures(value)
.ok_or(RustADBError::RegexParsingError)?;
Ok(DeviceLong {
@@ -98,3 +99,17 @@ impl TryFrom<Vec<u8>> for DeviceLong {
})
}
}
#[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 std::{fmt::Display, str::FromStr, sync::LazyLock};
use crate::{DeviceState, RustADBError};
use crate::{RustADBError, server::DeviceState};
static DEVICES_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));

View File

@@ -4,8 +4,9 @@ use std::str::FromStr;
use byteorder::{ByteOrder, LittleEndian};
use crate::ADBTransport;
use crate::models::{AdbRequestStatus, SyncCommand};
use crate::{models::AdbServerCommand, ADBTransport};
use crate::server::AdbServerCommand;
use crate::{Result, RustADBError};
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
@@ -99,13 +100,13 @@ impl TCPServerTransport {
}
/// 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()?;
Ok(LittleEndian::read_u32(&length_buffer))
}
/// Read 4 bytes representing body length
fn read_body_length(&mut self) -> Result<[u8; 4]> {
fn read_body_length(&self) -> Result<[u8; 4]> {
let mut length_buffer = [0; 4];
self.get_raw_connection()?.read_exact(&mut length_buffer)?;

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(Path::new("/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;
/// Represents a device connected to the ADB server.

View File

@@ -4,13 +4,15 @@ use std::{
};
use crate::{
constants::BUFFER_SIZE,
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
ADBDeviceExt, Result, RustADBError,
models::{AdbStatResponse, HostFeatures},
server::AdbServerCommand,
};
use super::ADBServerDevice;
const BUFFER_SIZE: usize = 65535;
impl ADBDeviceExt for ADBServerDevice {
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
let supported_features = self.host_features()?;
@@ -49,7 +51,7 @@ impl ADBDeviceExt for ADBServerDevice {
fn shell(
&mut self,
mut reader: &mut dyn Read,
mut writer: Box<(dyn Write + Send)>,
mut writer: Box<dyn Write + Send>,
) -> Result<()> {
let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2)

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
use crate::{
models::{AdbServerCommand, SyncCommand},
ADBServerDevice, Result,
Result, models::SyncCommand, server::AdbServerCommand, server_device::ADBServerDevice,
};
use byteorder::{ByteOrder, LittleEndian};
use std::{
@@ -64,7 +63,7 @@ impl ADBServerDevice {
"DONE" => {
return Ok(());
}
x => log::error!("Got an unknown response {}", x),
x => log::error!("Got an unknown response {x}"),
}
}
}

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,5 @@
use crate::{
constants,
models::{AdbServerCommand, SyncCommand},
ADBServerDevice, Result,
Result, models::SyncCommand, server::AdbServerCommand, server_device::ADBServerDevice,
};
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{BufReader, BufWriter, Read, Write};
@@ -43,18 +41,14 @@ impl<R: Read> Read for ADBRecvCommandReader<R> {
let mut error_msg = vec![0; length];
self.inner.read_exact(&mut error_msg)?;
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"ADB request failed: {}",
String::from_utf8_lossy(&error_msg)
),
))
Err(std::io::Error::other(format!(
"ADB request failed: {}",
String::from_utf8_lossy(&error_msg)
)))
}
_ => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Unknown response from device {:#?}", header),
)),
_ => Err(std::io::Error::other(format!(
"Unknown response from device {header:#?}"
))),
}
} else {
// Computing minimum to ensure to stop reading before next header...
@@ -68,6 +62,8 @@ impl<R: Read> Read for ADBRecvCommandReader<R> {
}
}
const BUFFER_SIZE: usize = 65535;
impl ADBServerDevice {
/// Receives path to stream from the device.
pub fn pull(&mut self, path: &dyn AsRef<str>, stream: &mut dyn Write) -> Result<()> {
@@ -97,8 +93,8 @@ impl ADBServerDevice {
let reader = ADBRecvCommandReader::new(raw_connection);
std::io::copy(
&mut BufReader::with_capacity(constants::BUFFER_SIZE, reader),
&mut BufWriter::with_capacity(constants::BUFFER_SIZE, output),
&mut BufReader::with_capacity(BUFFER_SIZE, reader),
&mut BufWriter::with_capacity(BUFFER_SIZE, output),
)?;
// Connection should've been left in SYNC mode by now

View File

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

View File

@@ -1,7 +1,8 @@
use crate::{
constants,
models::{AdbRequestStatus, AdbServerCommand, SyncCommand},
ADBServerDevice, Result, RustADBError,
Result, RustADBError,
models::{AdbRequestStatus, SyncCommand},
server::AdbServerCommand,
server_device::ADBServerDevice,
};
use std::{
convert::TryInto,
@@ -41,6 +42,8 @@ impl<W: Write> Write for ADBSendCommandWriter<W> {
}
}
const BUFFER_SIZE: usize = 65535;
impl ADBServerDevice {
/// Send stream to path on the device.
pub fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
@@ -72,8 +75,8 @@ impl ADBServerDevice {
let writer = ADBSendCommandWriter::new(raw_connection);
std::io::copy(
&mut BufReader::with_capacity(constants::BUFFER_SIZE, input),
&mut BufWriter::with_capacity(constants::BUFFER_SIZE, writer),
&mut BufReader::with_capacity(BUFFER_SIZE, input),
&mut BufWriter::with_capacity(BUFFER_SIZE, writer),
)?;
// Copy is finished, we can now notify as finished

View File

@@ -3,8 +3,8 @@ use std::io::{Read, Write};
use byteorder::{ByteOrder, LittleEndian};
use crate::{
models::{AdbServerCommand, AdbStatResponse, SyncCommand},
ADBServerDevice, Result, RustADBError,
AdbStatResponse, Result, RustADBError, models::SyncCommand, server::AdbServerCommand,
server_device::ADBServerDevice,
};
impl ADBServerDevice {
@@ -31,8 +31,7 @@ impl ADBServerDevice {
Ok(data.into())
}
x => Err(RustADBError::UnknownResponseType(format!(
"Unknown response {}",
x
"Unknown response {x}"
))),
}
}

View File

@@ -1,4 +1,4 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
impl ADBServerDevice {
/// Set adb daemon to tcp/ip mode

View File

@@ -1,4 +1,4 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
impl ADBServerDevice {
/// Asks ADB server to switch the connection to either the device or emulator connect to/running on the host. Will fail if there is more than one such device/emulator available.

View File

@@ -1,6 +1,6 @@
use std::io::Read;
use crate::{models::AdbServerCommand, server_device::ADBServerDevice, Result};
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
impl ADBServerDevice {
/// Uninstall a package from device
@@ -15,7 +15,7 @@ impl ADBServerDevice {
match &data[0..read_amount] {
b"Success\n" => {
log::info!("Package {} successfully uninstalled", package_name);
log::info!("Package {package_name} successfully uninstalled");
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(

View File

@@ -1,4 +1,4 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
impl ADBServerDevice {
/// Set adb daemon to usb mode

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