Compare commits
6 Commits
151-pyadb_
...
features
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b4be5d5cd | ||
|
|
586964128f | ||
|
|
042ca89f12 | ||
|
|
c6b12008a8 | ||
|
|
2bd0b2ca87 | ||
|
|
1589ee9da5 |
45
.github/workflows/python-build.yml
vendored
45
.github/workflows/python-build.yml
vendored
@@ -9,17 +9,8 @@ on:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
# ============================
|
||||
# BUILD (multi-architecture)
|
||||
# ============================
|
||||
build-python-packages:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [x86_64, arm64]
|
||||
|
||||
runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }}
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -32,34 +23,16 @@ jobs:
|
||||
- name: Build Python packages
|
||||
run: maturin build --sdist --release -m pyadb_client/Cargo.toml
|
||||
|
||||
- name: Upload wheels as artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wheels-${{ matrix.arch }}
|
||||
path: target/wheels/*
|
||||
if-no-files-found: error
|
||||
|
||||
# ================================
|
||||
# PUBLISH (release creation only)
|
||||
# ================================
|
||||
publish:
|
||||
name: Publish to PyPI & GitHub Release
|
||||
if: github.event_name == 'release' && github.event.action == 'created'
|
||||
needs: build-python-packages
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download all wheels
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: wheels
|
||||
|
||||
- name: Publish Python packages to PyPI
|
||||
run: maturin publish wheels/**/*.whl --non-interactive
|
||||
- name: Publish Python packages
|
||||
if: github.event_name == 'release' && github.event.action == 'created'
|
||||
run: maturin publish -m pyadb_client/Cargo.toml --non-interactive
|
||||
env:
|
||||
MATURIN_PYPI_TOKEN: ${{ secrets.MATURIN_PYPI_TOKEN }}
|
||||
|
||||
- name: Publish GitHub release artifacts
|
||||
- name: "Publish GitHub artefacts"
|
||||
if: github.event_name == 'release' && github.event.action == 'created'
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: wheels/**/*.*
|
||||
files: |
|
||||
target/wheels/pyadb_client*.whl
|
||||
target/wheels/pyadb_client*.tar.gz
|
||||
|
||||
16
.github/workflows/rust-build.yml
vendored
16
.github/workflows/rust-build.yml
vendored
@@ -6,6 +6,18 @@ on:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build-release:
|
||||
uses: cocool97/action_templates/.github/workflows/rust-build.yml@main
|
||||
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
|
||||
|
||||
39
.github/workflows/rust-quality.yml
vendored
39
.github/workflows/rust-quality.yml
vendored
@@ -6,6 +6,41 @@ on:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
uses: cocool97/action_templates/.github/workflows/rust-quality.yml@main
|
||||
clippy:
|
||||
name: "clippy"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: rustup component add clippy
|
||||
- name: Run clippy
|
||||
run: cargo clippy --all-features
|
||||
|
||||
fmt:
|
||||
name: "fmt"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run formatter
|
||||
run: cargo fmt --all --check
|
||||
|
||||
doc:
|
||||
name: "doc"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run doc
|
||||
run: cargo doc --all-features --no-deps
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
|
||||
tests:
|
||||
name: "tests"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features
|
||||
|
||||
15
.github/workflows/rust-release.yml
vendored
15
.github/workflows/rust-release.yml
vendored
@@ -36,10 +36,10 @@ jobs:
|
||||
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
|
||||
|
||||
- name: Build release
|
||||
run: cargo build -p adb_cli --release
|
||||
run: cargo build --all-features --release
|
||||
|
||||
- name: Rename binary
|
||||
run: cp target/release/adb_cli target/release/adb_cli-linux
|
||||
run: mv target/release/adb_cli target/release/adb_cli-linux
|
||||
|
||||
- name: Build DEB package
|
||||
run: cargo deb -p adb_cli
|
||||
@@ -69,10 +69,10 @@ jobs:
|
||||
override: true
|
||||
|
||||
- name: Build release
|
||||
run: cargo build -p adb_cli --release
|
||||
run: cargo build --all-features --release
|
||||
|
||||
- name: Rename binary
|
||||
run: cp target/release/adb_cli target/release/adb_cli-macos
|
||||
run: mv target/release/adb_cli target/release/adb_cli-macos
|
||||
|
||||
- name: Upload macOS binary
|
||||
uses: softprops/action-gh-release@v2
|
||||
@@ -92,13 +92,8 @@ jobs:
|
||||
toolchain: stable
|
||||
override: true
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- name: Build release
|
||||
run: cargo build -p adb_cli --release
|
||||
run: cargo build --all-features --release
|
||||
|
||||
- name: Rename binary
|
||||
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,4 +3,4 @@ target
|
||||
/.vscode
|
||||
venv
|
||||
/.mypy_cache
|
||||
pyadb_client/pyadb_client.pyi
|
||||
pyadb_client/pyadb_client.pyi
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["adb_cli", "adb_client", "pyadb_client", "examples/mdns"]
|
||||
members = ["adb_cli", "adb_client", "examples/mdns", "pyadb_client"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
@@ -9,8 +9,8 @@ homepage = "https://github.com/cocool97/adb_client"
|
||||
keywords = ["adb", "android", "tcp", "usb"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/cocool97/adb_client"
|
||||
version = "2.1.19"
|
||||
rust-version = "1.91.0"
|
||||
version = "2.1.16"
|
||||
rust-version = "1.85.1"
|
||||
|
||||
# To build locally when working on a new release
|
||||
[patch.crates-io]
|
||||
|
||||
12
README.md
12
README.md
@@ -42,12 +42,6 @@ Rust library implementing both ADB protocols (server and end-devices) and provid
|
||||
|
||||
Improved documentation available [here](./adb_client/README.md).
|
||||
|
||||
## examples
|
||||
|
||||
Some examples showing of to use this library are available in the `examples` directory:
|
||||
|
||||
- `examples/mdns`: mDNS device discovery
|
||||
|
||||
## adb_cli
|
||||
|
||||
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.
|
||||
@@ -55,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.
|
||||
|
||||
@@ -11,10 +11,11 @@ rust-version.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
adb_client = { version = "^2.1.19", features = ["mdns"] }
|
||||
clap = { version = "4.5.53", features = ["derive"] }
|
||||
env_logger = { version = "0.11.8" }
|
||||
log = { version = "0.4.29" }
|
||||
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" }
|
||||
log = { version = "0.4.26" }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
termios = { version = "0.3.3" }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# `adb_cli`
|
||||
# adb_cli
|
||||
|
||||
[](./LICENSE-MIT)
|
||||

|
||||
|
||||
@@ -4,7 +4,7 @@ use std::os::unix::prelude::{AsRawFd, RawFd};
|
||||
|
||||
use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
|
||||
|
||||
use crate::models::{ADBCliError, ADBCliResult};
|
||||
use crate::Result;
|
||||
|
||||
pub struct ADBTermios {
|
||||
fd: RawFd,
|
||||
@@ -13,7 +13,7 @@ pub struct ADBTermios {
|
||||
}
|
||||
|
||||
impl ADBTermios {
|
||||
pub fn new(fd: &impl AsRawFd) -> Result<Self, ADBCliError> {
|
||||
pub fn new(fd: impl AsRawFd) -> Result<Self> {
|
||||
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
|
||||
let old_termios = new_termios; // Saves previous state
|
||||
new_termios.c_lflag = 0;
|
||||
@@ -27,7 +27,7 @@ impl ADBTermios {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_adb_termios(&mut self) -> ADBCliResult<()> {
|
||||
pub fn set_adb_termios(&mut self) -> Result<()> {
|
||||
Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?)
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
|
||||
fn drop(&mut self) {
|
||||
// Custom drop implementation, restores previous termios structure.
|
||||
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
|
||||
log::error!("Error while dropping ADBTermios: {e}");
|
||||
log::error!("Error while dropping ADBTermios: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use adb_client::ADBEmulatorDevice;
|
||||
use adb_client::emulator::ADBEmulatorDevice;
|
||||
|
||||
use crate::models::{ADBCliResult, EmuCommand, EmulatorCommand};
|
||||
use crate::models::{EmuCommand, EmulatorCommand};
|
||||
|
||||
pub fn handle_emulator_commands(emulator_command: EmulatorCommand) -> ADBCliResult<()> {
|
||||
pub fn handle_emulator_commands(emulator_command: EmulatorCommand) -> anyhow::Result<()> {
|
||||
let mut emulator = ADBEmulatorDevice::new(emulator_command.serial, None)?;
|
||||
|
||||
match emulator_command.command {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -53,15 +56,12 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
|
||||
let server_status = adb_server.server_status()?;
|
||||
match server_status.mdns_backend {
|
||||
MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
|
||||
MDNSBackend::Bonjour => {
|
||||
if check {
|
||||
log::info!("mdns daemon version [Bonjour]");
|
||||
} else {
|
||||
log::info!("ERROR: mdns daemon unavailable");
|
||||
}
|
||||
}
|
||||
MDNSBackend::Bonjour => match check {
|
||||
true => log::info!("mdns daemon version [Bonjour]"),
|
||||
false => log::info!("ERROR: mdns daemon unavailable"),
|
||||
},
|
||||
MDNSBackend::OpenScreen => {
|
||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]");
|
||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
use std::{fs::File, io::Write};
|
||||
|
||||
use crate::ADBCliResult;
|
||||
use adb_client::server_device::ADBServerDevice;
|
||||
use anyhow::{Result, anyhow};
|
||||
|
||||
use crate::models::LocalDeviceCommand;
|
||||
use adb_client::ADBServerDevice;
|
||||
|
||||
pub fn handle_local_commands(
|
||||
mut device: ADBServerDevice,
|
||||
local_device_commands: LocalDeviceCommand,
|
||||
) -> ADBCliResult<()> {
|
||||
) -> Result<()> {
|
||||
match local_device_commands {
|
||||
LocalDeviceCommand::HostFeatures => {
|
||||
let features = device
|
||||
.host_features()?
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.map(|v| v.to_string())
|
||||
.reduce(|a, b| format!("{a},{b}"))
|
||||
.unwrap_or_default();
|
||||
.ok_or(anyhow!("cannot list features"))?;
|
||||
log::info!("Available host features: {features}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
LocalDeviceCommand::List { path } => Ok(device.list(path)?),
|
||||
LocalDeviceCommand::Logcat { path } => {
|
||||
let writer: Box<dyn Write> = if let Some(path) = path {
|
||||
let f = File::create(path)?;
|
||||
|
||||
@@ -7,14 +7,17 @@ mod handlers;
|
||||
mod models;
|
||||
mod utils;
|
||||
|
||||
use adb_client::{
|
||||
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
|
||||
mdns::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};
|
||||
use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
|
||||
@@ -22,112 +25,23 @@ use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
use utils::setup_logger;
|
||||
|
||||
use crate::models::{ADBCliError, ADBCliResult};
|
||||
|
||||
fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> ADBCliResult<()> {
|
||||
match command {
|
||||
DeviceCommands::Shell { commands } => {
|
||||
if commands.is_empty() {
|
||||
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
|
||||
// Using a scope here would call drop() too early..
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
let mut adb_termios = ADBTermios::new(&std::io::stdin())?;
|
||||
adb_termios.set_adb_termios()?;
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
|
||||
{
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
} else {
|
||||
let commands: Vec<&str> = commands.iter().map(String::as_str).collect();
|
||||
device.shell_command(&commands, &mut std::io::stdout())?;
|
||||
}
|
||||
}
|
||||
DeviceCommands::Pull {
|
||||
source,
|
||||
destination,
|
||||
} => {
|
||||
let mut output = File::create(Path::new(&destination))?;
|
||||
device.pull(&source, &mut output)?;
|
||||
log::info!("Downloaded {source} as {destination}");
|
||||
}
|
||||
DeviceCommands::Stat { path } => {
|
||||
let stat_response = device.stat(&path)?;
|
||||
println!("{stat_response}");
|
||||
}
|
||||
DeviceCommands::Reboot { reboot_type } => {
|
||||
log::info!("Reboots device in mode {reboot_type:?}");
|
||||
device.reboot(reboot_type.into())?;
|
||||
}
|
||||
DeviceCommands::Push { filename, path } => {
|
||||
let mut input = File::open(Path::new(&filename))?;
|
||||
device.push(&mut input, &path)?;
|
||||
log::info!("Uploaded {filename} to {path}");
|
||||
}
|
||||
DeviceCommands::Run { package, activity } => {
|
||||
let output = device.run_activity(&package, &activity)?;
|
||||
std::io::stdout().write_all(&output)?;
|
||||
}
|
||||
DeviceCommands::Install { path } => {
|
||||
log::info!("Starting installation of APK {}...", path.display());
|
||||
device.install(&path)?;
|
||||
}
|
||||
DeviceCommands::Uninstall { package } => {
|
||||
log::info!("Uninstalling the package {package}...");
|
||||
device.uninstall(&package)?;
|
||||
}
|
||||
DeviceCommands::Framebuffer { path } => {
|
||||
device.framebuffer(&path)?;
|
||||
log::info!("Successfully dumped framebuffer at path {path}");
|
||||
}
|
||||
DeviceCommands::List { path } => {
|
||||
let dirs = device.list(&path)?;
|
||||
for dir in dirs {
|
||||
let list_item_type = match dir.item_type {
|
||||
ADBListItemType::File => "File".to_string(),
|
||||
ADBListItemType::Directory => "Directory".to_string(),
|
||||
ADBListItemType::Symlink => "Symlink".to_string(),
|
||||
};
|
||||
log::info!(
|
||||
"type: {}, name: {}, time: {}, size: {}, permissions: {:#o}",
|
||||
list_item_type,
|
||||
dir.name,
|
||||
dir.time,
|
||||
dir.size,
|
||||
dir.permissions
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
if let Err(err) = inner_main() {
|
||||
log::error!("{err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn inner_main() -> ADBCliResult<()> {
|
||||
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.
|
||||
// This instance will then be used to execute desired command.
|
||||
let (device, commands) = match opts.command {
|
||||
let (mut device, commands) = match opts.command {
|
||||
MainCommand::Host(server_command) => return Ok(handle_host_commands(server_command)?),
|
||||
MainCommand::Emu(emulator_command) => return handle_emulator_commands(emulator_command),
|
||||
MainCommand::Local(server_command) => {
|
||||
@@ -160,19 +74,15 @@ fn inner_main() -> ADBCliResult<()> {
|
||||
None => ADBUSBDevice::autodetect()?,
|
||||
},
|
||||
_ => {
|
||||
return Err(ADBCliError::Standard(
|
||||
"cannot specify flags --vendor-id without --product-id or vice versa"
|
||||
.into(),
|
||||
));
|
||||
anyhow::bail!(
|
||||
"please either supply values for both the --vendor-id and --product-id flags or none."
|
||||
);
|
||||
}
|
||||
};
|
||||
(device.boxed(), usb_command.commands)
|
||||
}
|
||||
MainCommand::Tcp(tcp_command) => {
|
||||
let device = match tcp_command.path_to_private_key {
|
||||
Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
|
||||
None => ADBTcpDevice::new(tcp_command.address)?,
|
||||
};
|
||||
let device = ADBTcpDevice::new(tcp_command.address)?;
|
||||
(device.boxed(), tcp_command.commands)
|
||||
}
|
||||
MainCommand::Mdns => {
|
||||
@@ -184,18 +94,75 @@ fn inner_main() -> ADBCliResult<()> {
|
||||
log::info!("Starting mdns discovery...");
|
||||
while let Ok(device) = rx.recv() {
|
||||
log::info!(
|
||||
"Found device fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
|
||||
"Found device {} with addresses {:?}",
|
||||
device.fullname,
|
||||
device.ipv4_addresses(),
|
||||
device.ipv6_addresses()
|
||||
);
|
||||
device.addresses
|
||||
)
|
||||
}
|
||||
|
||||
return Ok(service.shutdown()?);
|
||||
}
|
||||
};
|
||||
|
||||
run_command(device, commands)?;
|
||||
match commands {
|
||||
DeviceCommands::Shell { commands } => {
|
||||
if commands.is_empty() {
|
||||
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
|
||||
// Using a scope here would call drop() too early..
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
let mut adb_termios = ADBTermios::new(std::io::stdin())?;
|
||||
adb_termios.set_adb_termios()?;
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
|
||||
{
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||
}
|
||||
} else {
|
||||
let commands: Vec<&str> = commands.iter().map(|v| v.as_str()).collect();
|
||||
device.shell_command(&commands, &mut std::io::stdout())?;
|
||||
}
|
||||
}
|
||||
DeviceCommands::Pull {
|
||||
source,
|
||||
destination,
|
||||
} => {
|
||||
let mut output = File::create(Path::new(&destination))?;
|
||||
device.pull(&source, &mut output)?;
|
||||
log::info!("Downloaded {source} as {destination}");
|
||||
}
|
||||
DeviceCommands::Stat { path } => {
|
||||
let stat_response = device.stat(&path)?;
|
||||
println!("{stat_response}");
|
||||
}
|
||||
DeviceCommands::Reboot { reboot_type } => {
|
||||
log::info!("Reboots device in mode {reboot_type:?}");
|
||||
device.reboot(reboot_type.into())?
|
||||
}
|
||||
DeviceCommands::Push { filename, path } => {
|
||||
let mut input = File::open(Path::new(&filename))?;
|
||||
device.push(&mut input, &path)?;
|
||||
log::info!("Uploaded {filename} to {path}");
|
||||
}
|
||||
DeviceCommands::Run { package, activity } => {
|
||||
let output = device.run_activity(&package, &activity)?;
|
||||
std::io::stdout().write_all(&output)?;
|
||||
}
|
||||
DeviceCommands::Install { path } => {
|
||||
log::info!("Starting installation of APK {}...", path.display());
|
||||
device.install(&path)?;
|
||||
}
|
||||
DeviceCommands::Uninstall { package } => {
|
||||
log::info!("Uninstalling the package {package}...");
|
||||
device.uninstall(&package)?;
|
||||
}
|
||||
DeviceCommands::Framebuffer { path } => {
|
||||
device.framebuffer(&path)?;
|
||||
log::info!("Successfully dumped framebuffer at path {path}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use adb_client::RustADBError;
|
||||
|
||||
pub type ADBCliResult<T> = Result<T, ADBCliError>;
|
||||
|
||||
pub enum ADBCliError {
|
||||
Standard(Box<dyn std::error::Error>),
|
||||
MayNeedAnIssue(Box<dyn std::error::Error>),
|
||||
}
|
||||
|
||||
impl Display for ADBCliError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ADBCliError::Standard(error) => write!(f, "{error}"),
|
||||
ADBCliError::MayNeedAnIssue(error) => {
|
||||
write!(
|
||||
f,
|
||||
r"Error: {error}
|
||||
An unexpected error occurred and may indicate a bug.
|
||||
Please report this issue on the project repository (including steps to reproduce if possible): https://github.com/cocool97/adb_client/issues.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for ADBCliError {
|
||||
fn from(value: std::io::Error) -> Self {
|
||||
// We do not consider adb_cli related `std::io::error` as critical
|
||||
Self::Standard(Box::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<adb_client::RustADBError> for ADBCliError {
|
||||
fn from(value: adb_client::RustADBError) -> Self {
|
||||
let value = Box::new(value);
|
||||
|
||||
match value.as_ref() {
|
||||
// List of [`RustADBError`] that may need an issue as abnormal
|
||||
RustADBError::RegexParsingError
|
||||
| RustADBError::WrongResponseReceived(_, _)
|
||||
| RustADBError::FramebufferImageError(_)
|
||||
| RustADBError::FramebufferConversionError
|
||||
| RustADBError::UnimplementedFramebufferImageVersion(_)
|
||||
| RustADBError::IOError(_)
|
||||
| RustADBError::ADBRequestFailed(_)
|
||||
| RustADBError::UnknownDeviceState(_)
|
||||
| RustADBError::Utf8StrError(_)
|
||||
| RustADBError::Utf8StringError(_)
|
||||
| RustADBError::RegexError(_)
|
||||
| RustADBError::ParseIntError(_)
|
||||
| RustADBError::ConversionError
|
||||
| RustADBError::IntegerConversionError(_)
|
||||
| RustADBError::HomeError
|
||||
| RustADBError::NoHomeDirectory
|
||||
| RustADBError::UsbError(_)
|
||||
| RustADBError::InvalidIntegrity(_, _)
|
||||
| RustADBError::Base64DecodeError(_)
|
||||
| RustADBError::Base64EncodeError(_)
|
||||
| RustADBError::RSAError(_)
|
||||
| RustADBError::TryFromSliceError(_)
|
||||
| RustADBError::RsaPkcs8Error(_)
|
||||
| RustADBError::CertificateGenerationError(_)
|
||||
| RustADBError::TLSError(_)
|
||||
| RustADBError::PemCertError(_)
|
||||
| RustADBError::PoisonError
|
||||
| RustADBError::UpgradeError(_)
|
||||
| RustADBError::MDNSError(_)
|
||||
| RustADBError::SendError
|
||||
| RustADBError::UnknownFileMode(_)
|
||||
| RustADBError::UnknownTransport(_) => Self::MayNeedAnIssue(value),
|
||||
// List of [`RustADBError`] that may occur in standard contexts and therefore do not require for issues
|
||||
RustADBError::ADBDeviceNotPaired
|
||||
| RustADBError::UnknownResponseType(_)
|
||||
| RustADBError::DeviceNotFound(_)
|
||||
| RustADBError::USBNoDescriptorFound
|
||||
| RustADBError::ADBShellNotSupported
|
||||
| RustADBError::USBDeviceNotFound(_, _)
|
||||
| RustADBError::WrongFileExtension(_)
|
||||
| RustADBError::AddrParseError(_) => Self::Standard(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub enum DeviceCommands {
|
||||
/// The package whose activity is to be invoked
|
||||
#[clap(short = 'p', long = "package")]
|
||||
package: String,
|
||||
/// The activity to be invoked itself, Usually it is `MainActivity`
|
||||
/// The activity to be invoked itself, Usually it is MainActivity
|
||||
#[clap(short = 'a', long = "activity")]
|
||||
activity: String,
|
||||
},
|
||||
@@ -43,9 +43,4 @@ pub enum DeviceCommands {
|
||||
/// Framebuffer image destination path
|
||||
path: String,
|
||||
},
|
||||
/// List files on device
|
||||
List {
|
||||
/// Path to list files from
|
||||
path: String,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use std::{net::SocketAddrV4, str::FromStr};
|
||||
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(
|
||||
value: &str,
|
||||
) -> Result<WaitForDeviceTransport, RustADBError> {
|
||||
WaitForDeviceTransport::from_str(value)
|
||||
WaitForDeviceTransport::try_from(value)
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
|
||||
@@ -14,6 +14,8 @@ pub enum LocalCommand {
|
||||
pub enum LocalDeviceCommand {
|
||||
/// List available server features.
|
||||
HostFeatures,
|
||||
/// List a directory on device
|
||||
List { path: String },
|
||||
/// Get logs of device
|
||||
Logcat {
|
||||
/// Path to output file (created if not exists)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
mod adb_cli_error;
|
||||
mod device;
|
||||
mod emu;
|
||||
mod host;
|
||||
@@ -8,7 +7,6 @@ mod reboot_type;
|
||||
mod tcp;
|
||||
mod usb;
|
||||
|
||||
pub use adb_cli_error::{ADBCliError, ADBCliResult};
|
||||
pub use device::DeviceCommands;
|
||||
pub use emu::{EmuCommand, EmulatorCommand};
|
||||
pub use host::{HostCommand, MdnsCommand};
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
use clap::Parser;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::DeviceCommands;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct TcpCommand {
|
||||
pub address: SocketAddr,
|
||||
/// Path to a custom private key to use for authentication
|
||||
#[clap(short = 'k', long = "private-key")]
|
||||
pub path_to_private_key: Option<PathBuf>,
|
||||
#[clap(subcommand)]
|
||||
pub commands: DeviceCommands,
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
use env_logger::{Builder, Env};
|
||||
/// # 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 {
|
||||
true => "trace",
|
||||
false => "info",
|
||||
};
|
||||
|
||||
/// Sets up appropriate logger level:
|
||||
/// - if `RUST_LOG` environment variable is set, use its value
|
||||
/// - else, use `debug` CLI option
|
||||
pub fn setup_logger(debug: bool) {
|
||||
Builder::from_env(Env::default().default_filter_or(if debug { "debug" } else { "info" }))
|
||||
.init();
|
||||
unsafe { std::env::set_var("RUST_LOG", level) };
|
||||
}
|
||||
|
||||
env_logger::init();
|
||||
}
|
||||
|
||||
@@ -17,39 +17,47 @@ rustdoc-args = ["--cfg", "docsrs"]
|
||||
[features]
|
||||
default = []
|
||||
mdns = ["dep:mdns-sd"]
|
||||
usb = ["dep:rsa", "dep:rusb"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { version = "0.22.1" }
|
||||
bincode = { version = "2.0.1", features = ["serde"] }
|
||||
bincode = { version = "1.3.3" }
|
||||
byteorder = { version = "1.5.0" }
|
||||
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
|
||||
image = { version = "0.25.9", default-features = false, features = ["png"] }
|
||||
log = { version = "0.4.29" }
|
||||
num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
|
||||
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" }
|
||||
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.2" }
|
||||
rcgen = { version = "0.14.6" }
|
||||
regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
|
||||
rsa = { version = "0.9.9" }
|
||||
rusb = { version = "0.9.4", features = ["vendored"] }
|
||||
rustls = { version = "0.23.35" }
|
||||
rustls-pki-types = { version = "1.13.2" }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_repr = { version = "0.1.20" }
|
||||
rand = { version = "0.9.0" }
|
||||
rcgen = { version = "0.13.1", default-features = false, features = [
|
||||
"aws_lc_rs",
|
||||
"pem",
|
||||
] }
|
||||
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] }
|
||||
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.17" }
|
||||
thiserror = { version = "2.0.7" }
|
||||
|
||||
#########
|
||||
# `mdns` feature-specific dependencies
|
||||
mdns-sd = { version = "0.17.1", default-features = false, features = [
|
||||
# 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.100" }
|
||||
criterion = { version = "0.7.0" } # Used for benchmarks
|
||||
anyhow = { version = "1.0.93" }
|
||||
criterion = { version = "0.6.0" } # Used for benchmarks
|
||||
|
||||
[[bench]]
|
||||
harness = false
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# `adb_client`
|
||||
# adb_client
|
||||
|
||||
[](./LICENSE-MIT)
|
||||
[](https://docs.rs/adb_client)
|
||||
@@ -21,14 +21,21 @@ adb_client = "*"
|
||||
| Feature | Description | Default? |
|
||||
| :-----: | :---------------------------------------------: | :------: |
|
||||
| `mdns` | Enables mDNS device discovery on local network. | No |
|
||||
| `usb` | Enables interactions with USB devices. | No |
|
||||
|
||||
To deactivate some default features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
|
||||
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 = "*", default-features = false, features = ["mdns"] }
|
||||
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
|
||||
@@ -42,84 +49,3 @@ Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel
|
||||
| 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()));
|
||||
```
|
||||
|
||||
@@ -4,9 +4,9 @@ use std::path::Path;
|
||||
use image::{ImageBuffer, ImageFormat, Rgba};
|
||||
|
||||
use crate::models::AdbStatResponse;
|
||||
use crate::{ADBListItem, RebootType, Result};
|
||||
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<()>;
|
||||
@@ -24,9 +24,6 @@ pub trait ADBDeviceExt {
|
||||
/// Push `stream` to `path` on the device.
|
||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()>;
|
||||
|
||||
/// List the items in a directory on the device
|
||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<ADBListItem>>;
|
||||
|
||||
/// Reboot the device using given reboot type
|
||||
fn reboot(&mut self, reboot_type: RebootType) -> Result<()>;
|
||||
|
||||
@@ -50,9 +47,7 @@ pub trait ADBDeviceExt {
|
||||
/// Inner method requesting framebuffer from an Android device
|
||||
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>>;
|
||||
|
||||
/// Dump framebuffer of this device into given path.
|
||||
///
|
||||
/// Output data format is currently only `PNG`.
|
||||
/// Dump framebuffer of this device into given path
|
||||
fn framebuffer(&mut self, path: &dyn AsRef<Path>) -> Result<()> {
|
||||
// Big help from AOSP source code (<https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp>)
|
||||
let img = self.framebuffer_inner()?;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
pub const BUFFER_SIZE: usize = 65536;
|
||||
@@ -1,317 +0,0 @@
|
||||
use super::{ADBRsaKey, ADBTransportMessage, MessageCommand, models::MessageSubcommand};
|
||||
use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
|
||||
use crate::device::models::ADBSession;
|
||||
use crate::{ADBMessageTransport, AdbStatResponse, Result, RustADBError, constants::BUFFER_SIZE};
|
||||
use bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
|
||||
use byteorder::ReadBytesExt;
|
||||
use rand::Rng;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::io::{Cursor, Read, Seek};
|
||||
use std::time::Duration;
|
||||
|
||||
const BINCODE_CONFIG: Configuration<LittleEndian, Fixint, NoLimit> = bincode::config::legacy();
|
||||
|
||||
pub(crate) fn bincode_serialize_to_vec<E: Serialize>(val: E) -> Result<Vec<u8>> {
|
||||
bincode::serde::encode_to_vec(val, BINCODE_CONFIG).map_err(|_e| RustADBError::ConversionError)
|
||||
}
|
||||
|
||||
pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -> Result<D> {
|
||||
let (response, _) = bincode::serde::decode_from_slice(data, BINCODE_CONFIG)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
|
||||
/// Structure is totally agnostic over which transport is truly used.
|
||||
#[derive(Debug)]
|
||||
pub struct ADBMessageDevice<T: ADBMessageTransport> {
|
||||
transport: T,
|
||||
}
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
/// Instantiate a new [`ADBMessageTransport`]
|
||||
pub fn new(transport: T) -> Self {
|
||||
Self { transport }
|
||||
}
|
||||
|
||||
pub(crate) fn get_transport(&mut self) -> &T {
|
||||
&self.transport
|
||||
}
|
||||
|
||||
pub(crate) fn get_transport_mut(&mut self) -> &mut T {
|
||||
&mut self.transport
|
||||
}
|
||||
|
||||
pub(crate) fn auth_handshake(
|
||||
&mut self,
|
||||
message: ADBTransportMessage,
|
||||
private_key: &ADBRsaKey,
|
||||
) -> Result<()> {
|
||||
match message.header().command() {
|
||||
MessageCommand::Auth => {
|
||||
log::debug!("Authentication required");
|
||||
}
|
||||
_ => return Ok(()),
|
||||
}
|
||||
|
||||
// At this point, we should have received an AUTH message with arg0 == 1
|
||||
let auth_message = match message.header().arg0() {
|
||||
AUTH_TOKEN => message,
|
||||
v => {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Received AUTH message with type != 1 ({v})"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let sign = private_key.sign(auth_message.into_payload())?;
|
||||
|
||||
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, &sign);
|
||||
|
||||
self.get_transport_mut().write_message(message)?;
|
||||
|
||||
let received_response = self.get_transport_mut().read_message()?;
|
||||
|
||||
if received_response.header().command() == MessageCommand::Cnxn {
|
||||
log::info!(
|
||||
"Authentication OK, device info {}",
|
||||
String::from_utf8(received_response.into_payload())?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut pubkey = private_key.android_pubkey_encode()?.into_bytes();
|
||||
pubkey.push(b'\0');
|
||||
|
||||
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_RSAPUBLICKEY, 0, &pubkey);
|
||||
|
||||
self.get_transport_mut().write_message(message)?;
|
||||
|
||||
let response = self
|
||||
.get_transport_mut()
|
||||
.read_message_with_timeout(Duration::from_secs(10))
|
||||
.and_then(|message| {
|
||||
message.assert_command(MessageCommand::Cnxn)?;
|
||||
Ok(message)
|
||||
})?;
|
||||
|
||||
log::info!(
|
||||
"Authentication OK, device info {}",
|
||||
String::from_utf8(response.into_payload())?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Receive a message and acknowledge it by replying with an `OKAY` command
|
||||
pub(crate) fn recv_and_reply_okay(
|
||||
&mut self,
|
||||
session: ADBSession,
|
||||
) -> Result<ADBTransportMessage> {
|
||||
let message = self.transport.read_message()?;
|
||||
self.transport.write_message(ADBTransportMessage::new(
|
||||
MessageCommand::Okay,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&[],
|
||||
))?;
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Expect a message with an `OKAY` command after sending a message.
|
||||
pub(crate) fn send_and_expect_okay(
|
||||
&mut self,
|
||||
message: ADBTransportMessage,
|
||||
) -> Result<ADBTransportMessage> {
|
||||
self.transport.write_message(message)?;
|
||||
|
||||
self.transport.read_message().and_then(|message| {
|
||||
message.assert_command(MessageCommand::Okay)?;
|
||||
Ok(message)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn recv_file<W: std::io::Write>(
|
||||
&mut self,
|
||||
session: ADBSession,
|
||||
mut output: W,
|
||||
) -> std::result::Result<(), RustADBError> {
|
||||
let mut len: Option<u64> = None;
|
||||
loop {
|
||||
let payload = self.recv_and_reply_okay(session)?.into_payload();
|
||||
let mut rdr = Cursor::new(&payload);
|
||||
while rdr.position() != payload.len() as u64 {
|
||||
match len.take() {
|
||||
Some(0) | None => {
|
||||
rdr.seek_relative(4)?;
|
||||
len.replace(u64::from(rdr.read_u32::<byteorder::LittleEndian>()?));
|
||||
}
|
||||
Some(length) => {
|
||||
let remaining_bytes = payload.len() as u64 - rdr.position();
|
||||
if length < remaining_bytes {
|
||||
std::io::copy(&mut rdr.by_ref().take(length), &mut output)?;
|
||||
} else {
|
||||
std::io::copy(&mut rdr.take(remaining_bytes), &mut output)?;
|
||||
len.replace(length - remaining_bytes);
|
||||
// this payload is now exhausted
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
|
||||
.read_u32::<byteorder::LittleEndian>()?
|
||||
== MessageSubcommand::Done as u32
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn push_file<R: std::io::Read>(
|
||||
&mut self,
|
||||
session: ADBSession,
|
||||
mut reader: R,
|
||||
) -> std::result::Result<(), RustADBError> {
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
let amount_read = reader.read(&mut buffer)?;
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(amount_read)?);
|
||||
|
||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
serialized_message.append(&mut buffer[..amount_read].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
|
||||
loop {
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => {
|
||||
// Currently file mtime is not forwarded
|
||||
let subcommand_data = MessageSubcommand::Done.with_arg(0);
|
||||
|
||||
let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
|
||||
// Command should end with a Write => Okay
|
||||
let received = self.transport.read_message()?;
|
||||
match received.header().command() {
|
||||
MessageCommand::Write => return Ok(()),
|
||||
c => {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Wrong command received {c}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(size) => {
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(size)?);
|
||||
|
||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
||||
serialized_message.append(&mut buffer[..size].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(RustADBError::IOError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_synchronization(&mut self) -> Result<ADBSession> {
|
||||
self.open_session(b"sync:\0")
|
||||
}
|
||||
|
||||
pub(crate) fn stat_with_explicit_ids(
|
||||
&mut self,
|
||||
session: ADBSession,
|
||||
remote_path: &str,
|
||||
) -> Result<AdbStatResponse> {
|
||||
let stat_buffer = MessageSubcommand::Stat.with_arg(u32::try_from(remote_path.len())?);
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&bincode_serialize_to_vec(&stat_buffer)?,
|
||||
);
|
||||
self.send_and_expect_okay(message)?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
remote_path.as_bytes(),
|
||||
))?;
|
||||
let response = self.transport.read_message()?;
|
||||
// Skip first 4 bytes as this is the literal "STAT".
|
||||
// Interesting part starts right after
|
||||
|
||||
bincode_deserialize_from_slice(&response.into_payload()[4..])
|
||||
}
|
||||
|
||||
pub(crate) fn end_transaction(&mut self, session: ADBSession) -> Result<()> {
|
||||
let quit_buffer = MessageSubcommand::Quit.with_arg(0u32);
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&bincode_serialize_to_vec(&quit_buffer)?,
|
||||
))?;
|
||||
let _discard_close = self.transport.read_message()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBSession> {
|
||||
let mut rng = rand::rng();
|
||||
let local_id: u32 = rng.random();
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Open,
|
||||
local_id, // Our 'local-id'
|
||||
0,
|
||||
data,
|
||||
);
|
||||
self.get_transport_mut().write_message(message)?;
|
||||
|
||||
let response = self.get_transport_mut().read_message()?;
|
||||
|
||||
if response.header().command() != MessageCommand::Okay {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Open session failed: got {} in respone instead of OKAY",
|
||||
response.header().command()
|
||||
)));
|
||||
}
|
||||
|
||||
if response.header().arg1() != local_id {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Open session failed: respones used {} for our local_id instead of {local_id}",
|
||||
response.header().arg1()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(ADBSession::new(local_id, response.header().arg0()))
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
use crate::{
|
||||
ADBListItem, ADBListItemType, ADBMessageTransport, Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, MessageCommand, MessageSubcommand,
|
||||
adb_message_device::{ADBMessageDevice, bincode_serialize_to_vec},
|
||||
},
|
||||
};
|
||||
use byteorder::ByteOrder;
|
||||
use byteorder::LittleEndian;
|
||||
use std::str;
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
/// List the entries in the given directory on the device.
|
||||
/// note: path uses internal file paths, so Documents is at /storage/emulated/0/Documents
|
||||
pub(crate) fn list<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
|
||||
let session = self.begin_synchronization()?;
|
||||
|
||||
let output = self.handle_list(path, session.local_id(), session.remote_id());
|
||||
|
||||
self.end_transaction(session)?;
|
||||
output
|
||||
}
|
||||
|
||||
/// Request amount of bytes from transport, potentially across payloads
|
||||
///
|
||||
/// This automatically request a new payload by sending back "Okay" and waiting for the next payload
|
||||
/// It reads the request bytes across the existing payload, and if there is not enough bytes left,
|
||||
/// reads the rest from the next payload
|
||||
///
|
||||
/// Current index
|
||||
/// ┼───────────────┼ Requested
|
||||
/// ┌─────────────┐
|
||||
/// ┌───────────────┼───────┐ │
|
||||
/// └───────────────────────┘
|
||||
/// Current └─────┘
|
||||
/// payload Wanted in
|
||||
/// Next payload
|
||||
fn read_bytes_from_transport(
|
||||
requested_bytes: usize,
|
||||
current_index: &mut usize,
|
||||
transport: &mut T,
|
||||
payload: &mut Vec<u8>,
|
||||
local_id: u32,
|
||||
remote_id: u32,
|
||||
) -> Result<Vec<u8>> {
|
||||
if *current_index + requested_bytes <= payload.len() {
|
||||
// if there is enough bytes in this payload
|
||||
// Copy from existing payload
|
||||
let slice = &payload[*current_index..*current_index + requested_bytes];
|
||||
*current_index += requested_bytes;
|
||||
Ok(slice.to_vec())
|
||||
} else {
|
||||
// Read the rest of the existing payload, then continue with the next message
|
||||
let mut slice = Vec::new();
|
||||
let bytes_read_from_existing_payload = payload.len() - *current_index;
|
||||
slice.extend_from_slice(
|
||||
&payload[*current_index..*current_index + bytes_read_from_existing_payload],
|
||||
);
|
||||
|
||||
// Request the next message
|
||||
let send_message =
|
||||
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]);
|
||||
transport.write_message(send_message)?;
|
||||
// Read the new message
|
||||
*payload = transport.read_message()?.into_payload();
|
||||
let bytes_read_from_new_payload = requested_bytes - bytes_read_from_existing_payload;
|
||||
slice.extend_from_slice(&payload[..bytes_read_from_new_payload]);
|
||||
*current_index = bytes_read_from_new_payload;
|
||||
Ok(slice)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_list<A: AsRef<str>>(
|
||||
&mut self,
|
||||
path: A,
|
||||
local_id: u32,
|
||||
remote_id: u32,
|
||||
) -> Result<Vec<ADBListItem>> {
|
||||
// TODO: use LIS2 to support files over 2.14 GB in size.
|
||||
// SEE: https://github.com/cstyan/adbDocumentation?tab=readme-ov-file#adb-list
|
||||
{
|
||||
let mut len_buf = Vec::from([0_u8; 4]);
|
||||
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
|
||||
|
||||
let subcommand_data = MessageSubcommand::List;
|
||||
|
||||
let mut serialized_message = bincode_serialize_to_vec(subcommand_data)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
|
||||
serialized_message.append(&mut len_buf);
|
||||
let mut path_bytes: Vec<u8> = Vec::from(path.as_ref().as_bytes());
|
||||
serialized_message.append(&mut path_bytes);
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
local_id,
|
||||
remote_id,
|
||||
&serialized_message,
|
||||
);
|
||||
self.send_and_expect_okay(message)?;
|
||||
}
|
||||
|
||||
let mut list_items = Vec::new();
|
||||
|
||||
let transport = self.get_transport_mut();
|
||||
let mut payload = transport.read_message()?.into_payload();
|
||||
let mut current_index = 0;
|
||||
loop {
|
||||
// Loop though the response for all the entries
|
||||
const STATUS_CODE_LENGTH_IN_BYTES: usize = 4;
|
||||
let status_code = Self::read_bytes_from_transport(
|
||||
STATUS_CODE_LENGTH_IN_BYTES,
|
||||
&mut current_index,
|
||||
transport,
|
||||
&mut payload,
|
||||
local_id,
|
||||
remote_id,
|
||||
)?;
|
||||
match str::from_utf8(&status_code)? {
|
||||
"DENT" => {
|
||||
// Read the file mode, size, mod time and name length in one go, since all their sizes are predictable
|
||||
const U32_SIZE_IN_BYTES: usize = 4;
|
||||
const SIZE_OF_METADATA: usize = U32_SIZE_IN_BYTES * 4;
|
||||
let metadata = Self::read_bytes_from_transport(
|
||||
SIZE_OF_METADATA,
|
||||
&mut current_index,
|
||||
transport,
|
||||
&mut payload,
|
||||
local_id,
|
||||
remote_id,
|
||||
)?;
|
||||
let mode = metadata[..U32_SIZE_IN_BYTES].to_vec();
|
||||
let size = metadata[U32_SIZE_IN_BYTES..2 * U32_SIZE_IN_BYTES].to_vec();
|
||||
let time = metadata[2 * U32_SIZE_IN_BYTES..3 * U32_SIZE_IN_BYTES].to_vec();
|
||||
let name_len = metadata[3 * U32_SIZE_IN_BYTES..4 * U32_SIZE_IN_BYTES].to_vec();
|
||||
|
||||
let mode = LittleEndian::read_u32(&mode);
|
||||
let size = LittleEndian::read_u32(&size);
|
||||
let time = LittleEndian::read_u32(&time);
|
||||
let name_len = LittleEndian::read_u32(&name_len) as usize;
|
||||
// Read the file name, since it requires the length from the name_len
|
||||
let name_buf = Self::read_bytes_from_transport(
|
||||
name_len,
|
||||
&mut current_index,
|
||||
transport,
|
||||
&mut payload,
|
||||
local_id,
|
||||
remote_id,
|
||||
)?;
|
||||
let name = String::from_utf8(name_buf)?;
|
||||
|
||||
// First 9 bits are the file permissions
|
||||
let permissions = mode & 0b1_1111_1111;
|
||||
// Bits 14 to 16 are the file type
|
||||
let item_type = match (mode >> 13) & 0b111 {
|
||||
0b010 => ADBListItemType::Directory,
|
||||
0b100 => ADBListItemType::File,
|
||||
0b101 => ADBListItemType::Symlink,
|
||||
type_code => return Err(RustADBError::UnknownFileMode(type_code)),
|
||||
};
|
||||
let entry = ADBListItem {
|
||||
item_type,
|
||||
name,
|
||||
time,
|
||||
size,
|
||||
permissions,
|
||||
};
|
||||
list_items.push(entry);
|
||||
}
|
||||
"DONE" => {
|
||||
return Ok(list_items);
|
||||
}
|
||||
x => log::error!("Got an unknown response {x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, MessageCommand,
|
||||
adb_message_device::{self, ADBMessageDevice},
|
||||
models::MessageSubcommand,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
|
||||
let session = self.begin_synchronization()?;
|
||||
let source = source.as_ref();
|
||||
|
||||
let adb_stat_response = self.stat_with_explicit_ids(session, source)?;
|
||||
|
||||
if adb_stat_response.file_perm == 0 {
|
||||
return Err(RustADBError::UnknownResponseType(
|
||||
"mode is 0: source file does not exist".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
self.get_transport_mut().write_message_with_timeout(
|
||||
ADBTransportMessage::new(
|
||||
MessageCommand::Okay,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&[],
|
||||
),
|
||||
std::time::Duration::from_secs(4),
|
||||
)?;
|
||||
|
||||
let recv_buffer = MessageSubcommand::Recv.with_arg(u32::try_from(source.len())?);
|
||||
let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&recv_buffer,
|
||||
))?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
source.as_bytes(),
|
||||
))?;
|
||||
|
||||
self.recv_file(session, output)?;
|
||||
self.end_transaction(session)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result,
|
||||
device::{
|
||||
ADBTransportMessage, MessageCommand, MessageSubcommand,
|
||||
adb_message_device::{self, ADBMessageDevice},
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
|
||||
let session = self.begin_synchronization()?;
|
||||
|
||||
let path_header = format!("{},0777", path.as_ref());
|
||||
|
||||
let send_buffer = MessageSubcommand::Send.with_arg(u32::try_from(path_header.len())?);
|
||||
let mut send_buffer = adb_message_device::bincode_serialize_to_vec(&send_buffer)?;
|
||||
send_buffer.append(&mut path_header.as_bytes().to_vec());
|
||||
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&send_buffer,
|
||||
))?;
|
||||
|
||||
self.push_file(session, stream)?;
|
||||
self.end_transaction(session)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
use crate::{
|
||||
ADBMessageTransport, AdbStatResponse, Result, device::adb_message_device::ADBMessageDevice,
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
||||
let session = self.begin_synchronization()?;
|
||||
let adb_stat_response = self.stat_with_explicit_ids(session, remote_path)?;
|
||||
self.end_transaction(session)?;
|
||||
Ok(adb_stat_response)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
mod adb_message_device;
|
||||
mod adb_message_device_commands;
|
||||
mod adb_tcp_device;
|
||||
mod adb_transport_message;
|
||||
mod adb_usb_device;
|
||||
mod commands;
|
||||
mod message_writer;
|
||||
mod models;
|
||||
mod shell_message_writer;
|
||||
|
||||
use adb_message_device::ADBMessageDevice;
|
||||
pub use adb_tcp_device::ADBTcpDevice;
|
||||
pub use adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader};
|
||||
pub use adb_usb_device::{
|
||||
ADBUSBDevice, get_default_adb_key_path, is_adb_device, search_adb_devices,
|
||||
};
|
||||
pub use message_writer::MessageWriter;
|
||||
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
|
||||
pub use shell_message_writer::ShellMessageWriter;
|
||||
@@ -1,23 +0,0 @@
|
||||
/// Represent a session between an `ADBDevice` and remote `adbd`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ADBSession {
|
||||
local_id: u32,
|
||||
remote_id: u32,
|
||||
}
|
||||
|
||||
impl ADBSession {
|
||||
pub fn new(local_id: u32, remote_id: u32) -> Self {
|
||||
Self {
|
||||
local_id,
|
||||
remote_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_id(self) -> u32 {
|
||||
self.local_id
|
||||
}
|
||||
|
||||
pub fn remote_id(self) -> u32 {
|
||||
self.remote_id
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod adb_rsa_key;
|
||||
mod adb_session;
|
||||
mod message_commands;
|
||||
|
||||
pub use adb_rsa_key::ADBRsaKey;
|
||||
pub(crate) use adb_session::ADBSession;
|
||||
pub use message_commands::{MessageCommand, MessageSubcommand};
|
||||
@@ -3,7 +3,10 @@ use std::{
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
|
||||
use crate::{
|
||||
ADBTransport, Result, RustADBError, emulator::tcp_emulator_transport::TCPEmulatorTransport,
|
||||
server_device::ADBServerDevice,
|
||||
};
|
||||
use regex::Regex;
|
||||
|
||||
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
@@ -15,16 +18,16 @@ static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
pub struct ADBEmulatorDevice {
|
||||
/// Unique device identifier.
|
||||
pub identifier: String,
|
||||
/// Internal [`TCPEmulatorTransport`]
|
||||
/// Internal [TCPEmulatorTransport]
|
||||
transport: TCPEmulatorTransport,
|
||||
}
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Instantiates a new [`ADBEmulatorDevice`]
|
||||
/// Instantiates a new [ADBEmulatorDevice]
|
||||
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
|
||||
let ip_address = match ip_address {
|
||||
Some(ip_address) => ip_address,
|
||||
None => Ipv4Addr::LOCALHOST,
|
||||
None => Ipv4Addr::new(127, 0, 0, 1),
|
||||
};
|
||||
|
||||
let groups = EMULATOR_REGEX
|
||||
@@ -1,8 +1,11 @@
|
||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
|
||||
};
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Send a SMS to this emulator with given content with given phone number
|
||||
pub fn rotate(&mut self) -> Result<()> {
|
||||
self.connect()?.send_command(&ADBEmulatorCommand::Rotate)
|
||||
self.connect()?.send_command(ADBEmulatorCommand::Rotate)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
emulator::{ADBEmulatorCommand, ADBEmulatorDevice},
|
||||
};
|
||||
|
||||
impl ADBEmulatorDevice {
|
||||
/// Send a SMS to this emulator with given content with given phone number
|
||||
pub fn send_sms(&mut self, phone_number: &str, content: &str) -> Result<()> {
|
||||
self.connect()?.send_command(&ADBEmulatorCommand::Sms(
|
||||
self.connect()?.send_command(ADBEmulatorCommand::Sms(
|
||||
phone_number.to_string(),
|
||||
content.to_string(),
|
||||
))
|
||||
@@ -1,5 +1,7 @@
|
||||
mod adb_emulator_device;
|
||||
mod commands;
|
||||
mod models;
|
||||
mod tcp_emulator_transport;
|
||||
|
||||
pub use adb_emulator_device::ADBEmulatorDevice;
|
||||
pub(crate) use models::ADBEmulatorCommand;
|
||||
use models::ADBEmulatorCommand;
|
||||
@@ -24,7 +24,8 @@ impl ADBEmulatorCommand {
|
||||
pub(crate) fn skip_response_lines(&self) -> u8 {
|
||||
match self {
|
||||
ADBEmulatorCommand::Authenticate(_) => 1,
|
||||
ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
|
||||
ADBEmulatorCommand::Sms(_, _) => 0,
|
||||
ADBEmulatorCommand::Rotate => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,11 @@ use std::{
|
||||
net::{SocketAddrV4, TcpStream},
|
||||
};
|
||||
|
||||
use super::ADBTransport;
|
||||
use crate::{Result, RustADBError, emulator_device::ADBEmulatorCommand};
|
||||
use homedir::my_home;
|
||||
|
||||
use crate::{
|
||||
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
|
||||
};
|
||||
|
||||
/// Emulator transport running on top on TCP.
|
||||
#[derive(Debug)]
|
||||
@@ -15,8 +18,7 @@ pub struct TCPEmulatorTransport {
|
||||
}
|
||||
|
||||
impl TCPEmulatorTransport {
|
||||
/// Instantiates a new instance of [`TCPEmulatorTransport`]
|
||||
#[must_use]
|
||||
/// Instantiates a new instance of [TCPEmulatorTransport]
|
||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
socket_addr,
|
||||
@@ -33,10 +35,11 @@ impl TCPEmulatorTransport {
|
||||
)))
|
||||
}
|
||||
|
||||
/// Return authentication token stored in `$HOME/.emulator_console_auth_token`
|
||||
/// Return authentication token stored in $HOME/.emulator_console_auth_token
|
||||
pub fn get_authentication_token(&mut self) -> Result<String> {
|
||||
let Some(home) = std::env::home_dir() else {
|
||||
return Err(RustADBError::NoHomeDirectory);
|
||||
let home = match my_home()? {
|
||||
Some(home) => home,
|
||||
None => return Err(RustADBError::NoHomeDirectory),
|
||||
};
|
||||
|
||||
let mut f = File::open(home.join(".emulator_console_auth_token"))?;
|
||||
@@ -49,11 +52,11 @@ impl TCPEmulatorTransport {
|
||||
/// Send an authenticate request to this emulator
|
||||
pub fn authenticate(&mut self) -> Result<()> {
|
||||
let token = self.get_authentication_token()?;
|
||||
self.send_command(&ADBEmulatorCommand::Authenticate(token))
|
||||
self.send_command(ADBEmulatorCommand::Authenticate(token))
|
||||
}
|
||||
|
||||
/// Send an [`ADBEmulatorCommand`] to this emulator
|
||||
pub(crate) fn send_command(&mut self, command: &ADBEmulatorCommand) -> Result<()> {
|
||||
/// Send an [ADBEmulatorCommand] to this emulator
|
||||
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> {
|
||||
let mut connection = self.get_raw_connection()?;
|
||||
|
||||
// Send command
|
||||
@@ -78,11 +81,10 @@ impl TCPEmulatorTransport {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line)?;
|
||||
|
||||
if line.starts_with("OK") {
|
||||
return Ok(());
|
||||
match line.starts_with("OK") {
|
||||
true => Ok(()),
|
||||
false => Err(RustADBError::ADBRequestFailed(line)),
|
||||
}
|
||||
|
||||
Err(RustADBError::ADBRequestFailed(line))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,9 +42,6 @@ pub enum RustADBError {
|
||||
/// Indicates that an error occurred when converting a value.
|
||||
#[error("Conversion error")]
|
||||
ConversionError,
|
||||
/// Indicates an error with the integer conversion.
|
||||
#[error(transparent)]
|
||||
IntegerConversionError(#[from] std::num::TryFromIntError),
|
||||
/// Remote ADB server does not support shell feature.
|
||||
#[error("Remote ADB server does not support shell feature")]
|
||||
ADBShellNotSupported,
|
||||
@@ -64,12 +61,14 @@ pub enum RustADBError {
|
||||
#[error("Unimplemented framebuffer image version: {0}")]
|
||||
UnimplementedFramebufferImageVersion(u32),
|
||||
/// An error occurred while getting user's home directory
|
||||
#[error("Cannot get user home directory")]
|
||||
HomeError,
|
||||
#[error(transparent)]
|
||||
HomeError(#[from] homedir::GetHomeError),
|
||||
/// Cannot get home directory
|
||||
#[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
|
||||
@@ -88,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
|
||||
@@ -97,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
|
||||
@@ -125,9 +128,6 @@ pub enum RustADBError {
|
||||
/// An unknown transport has been provided
|
||||
#[error("unknown transport: {0}")]
|
||||
UnknownTransport(String),
|
||||
/// An unknown file mode was encountered in list
|
||||
#[error("Unknown file mode {0}")]
|
||||
UnknownFileMode(u32),
|
||||
}
|
||||
|
||||
impl<T> From<std::sync::PoisonError<T>> for RustADBError {
|
||||
|
||||
@@ -3,34 +3,34 @@
|
||||
#![forbid(missing_debug_implementations)]
|
||||
#![forbid(missing_docs)]
|
||||
#![doc = include_str!("../README.md")]
|
||||
// Feature `doc_cfg` is currently only available on nightly builds.
|
||||
// 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 message_devices;
|
||||
mod models;
|
||||
|
||||
/// 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;
|
||||
|
||||
mod models;
|
||||
mod server;
|
||||
mod server_device;
|
||||
mod transports;
|
||||
mod utils;
|
||||
|
||||
pub use adb_device_ext::ADBDeviceExt;
|
||||
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
|
||||
pub use emulator_device::ADBEmulatorDevice;
|
||||
use adb_transport::ADBTransport;
|
||||
pub use error::{Result, RustADBError};
|
||||
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
|
||||
pub use server::*;
|
||||
pub use server_device::ADBServerDevice;
|
||||
pub use transports::*;
|
||||
pub use message_devices::*;
|
||||
pub use models::{AdbStatResponse, HostFeatures, RebootType};
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fmt::Display,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr},
|
||||
};
|
||||
|
||||
use mdns_sd::{ResolvedService, ScopedIp};
|
||||
use std::{collections::HashSet, net::IpAddr};
|
||||
|
||||
/// Represent a device found from mdns search
|
||||
#[derive(Debug)]
|
||||
@@ -12,58 +6,14 @@ pub struct MDNSDevice {
|
||||
/// Full device address when resolved
|
||||
pub fullname: String,
|
||||
/// Device IP addresses
|
||||
addresses: HashSet<IpAddr>,
|
||||
pub addresses: HashSet<IpAddr>,
|
||||
}
|
||||
|
||||
impl MDNSDevice {
|
||||
/// Return all adresses linked to this device
|
||||
#[must_use]
|
||||
pub fn addresses(&self) -> HashSet<IpAddr> {
|
||||
self.addresses.clone()
|
||||
}
|
||||
|
||||
/// Return all IPv4 addresses linked to this device
|
||||
#[must_use]
|
||||
pub fn ipv4_addresses(&self) -> HashSet<Ipv4Addr> {
|
||||
self.addresses
|
||||
.iter()
|
||||
.filter_map(|addr| match addr {
|
||||
IpAddr::V4(addr) => Some(addr),
|
||||
IpAddr::V6(_) => None,
|
||||
})
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Return all IPv6 addresses linked to this device
|
||||
#[must_use]
|
||||
pub fn ipv6_addresses(&self) -> HashSet<Ipv6Addr> {
|
||||
self.addresses
|
||||
.iter()
|
||||
.filter_map(|addr| match addr {
|
||||
IpAddr::V4(_) => None,
|
||||
IpAddr::V6(addr) => Some(addr),
|
||||
})
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Box<ResolvedService>> for MDNSDevice {
|
||||
fn from(value: Box<ResolvedService>) -> Self {
|
||||
impl From<mdns_sd::ServiceInfo> for MDNSDevice {
|
||||
fn from(value: mdns_sd::ServiceInfo) -> Self {
|
||||
Self {
|
||||
fullname: value.fullname,
|
||||
addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
|
||||
fullname: value.get_fullname().to_string(),
|
||||
addresses: value.get_addresses().to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for MDNSDevice {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(f, "Device fullname: {}", self.fullname)?;
|
||||
writeln!(f, "IPv4 Addresses: {:?}", self.ipv4_addresses())?;
|
||||
write!(f, "IPv6 Addresses: {:?}", self.ipv6_addresses())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use mdns_sd::{ServiceDaemon, ServiceEvent};
|
||||
use std::{sync::mpsc::Sender, thread::JoinHandle};
|
||||
|
||||
use super::MDNSDevice;
|
||||
use crate::{Result, RustADBError};
|
||||
use crate::{Result, RustADBError, mdns::MDNSDevice};
|
||||
|
||||
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
|
||||
|
||||
@@ -30,7 +29,7 @@ impl MDNSDiscoveryService {
|
||||
})
|
||||
}
|
||||
|
||||
/// Start discovery by spawning a new background thread responsible of getting events.
|
||||
/// Start discovery by spawning a new thread responsible of getting events.
|
||||
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
|
||||
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
|
||||
|
||||
@@ -43,14 +42,12 @@ impl MDNSDiscoveryService {
|
||||
| ServiceEvent::ServiceFound(_, _)
|
||||
| ServiceEvent::SearchStopped(_) => {
|
||||
// Ignoring these events. We are only interesting in found devices
|
||||
continue;
|
||||
}
|
||||
ServiceEvent::ServiceResolved(service_info) => {
|
||||
sender
|
||||
return sender
|
||||
.send(MDNSDevice::from(service_info))
|
||||
.map_err(|_| RustADBError::SendError)?;
|
||||
}
|
||||
e => {
|
||||
log::warn!("received unknown event type {e:?}");
|
||||
.map_err(|_| RustADBError::SendError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
251
adb_client/src/message_devices/adb_message_device.rs
Normal file
251
adb_client/src/message_devices/adb_message_device.rs
Normal file
@@ -0,0 +1,251 @@
|
||||
use byteorder::{LittleEndian, ReadBytesExt};
|
||||
use rand::Rng;
|
||||
use std::io::{Cursor, Read, Seek};
|
||||
|
||||
use crate::{
|
||||
AdbStatResponse, Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage,
|
||||
message_commands::{MessageCommand, MessageSubcommand},
|
||||
},
|
||||
};
|
||||
|
||||
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.
|
||||
#[derive(Debug)]
|
||||
pub struct ADBMessageDevice<T: ADBMessageTransport> {
|
||||
transport: T,
|
||||
local_id: Option<u32>,
|
||||
remote_id: Option<u32>,
|
||||
}
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
/// Instantiate a new [`ADBMessageTransport`]
|
||||
pub fn new(transport: T) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
local_id: None,
|
||||
remote_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_transport(&mut self) -> &T {
|
||||
&self.transport
|
||||
}
|
||||
|
||||
pub(crate) fn get_transport_mut(&mut self) -> &mut T {
|
||||
&mut self.transport
|
||||
}
|
||||
|
||||
/// Receive a message and acknowledge it by replying with an `OKAY` command
|
||||
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> {
|
||||
let message = self.transport.read_message()?;
|
||||
self.transport.write_message(ADBTransportMessage::new(
|
||||
MessageCommand::Okay,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&[],
|
||||
))?;
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Expect a message with an `OKAY` command after sending a message.
|
||||
pub(crate) fn send_and_expect_okay(
|
||||
&mut self,
|
||||
message: ADBTransportMessage,
|
||||
) -> Result<ADBTransportMessage> {
|
||||
self.transport.write_message(message)?;
|
||||
|
||||
self.transport.read_message().and_then(|message| {
|
||||
message.assert_command(MessageCommand::Okay)?;
|
||||
Ok(message)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn recv_file<W: std::io::Write>(
|
||||
&mut self,
|
||||
mut output: W,
|
||||
) -> std::result::Result<(), RustADBError> {
|
||||
let mut len: Option<u64> = None;
|
||||
loop {
|
||||
let payload = self.recv_and_reply_okay()?.into_payload();
|
||||
let mut rdr = Cursor::new(&payload);
|
||||
while rdr.position() != payload.len() as u64 {
|
||||
match len.take() {
|
||||
Some(0) | None => {
|
||||
rdr.seek_relative(4)?;
|
||||
len.replace(rdr.read_u32::<LittleEndian>()? as u64);
|
||||
}
|
||||
Some(length) => {
|
||||
let remaining_bytes = payload.len() as u64 - rdr.position();
|
||||
if length < remaining_bytes {
|
||||
std::io::copy(&mut rdr.by_ref().take(length), &mut output)?;
|
||||
} else {
|
||||
std::io::copy(&mut rdr.take(remaining_bytes), &mut output)?;
|
||||
len.replace(length - remaining_bytes);
|
||||
// this payload is now exhausted
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
|
||||
.read_u32::<LittleEndian>()?
|
||||
== MessageSubcommand::Done as u32
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn push_file<R: std::io::Read>(
|
||||
&mut self,
|
||||
local_id: u32,
|
||||
remote_id: u32,
|
||||
mut reader: R,
|
||||
) -> std::result::Result<(), RustADBError> {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
let amount_read = reader.read(&mut buffer)?;
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(amount_read as u32);
|
||||
|
||||
let mut serialized_message =
|
||||
bincode::serialize(&subcommand_data).map_err(|_e| RustADBError::ConversionError)?;
|
||||
serialized_message.append(&mut buffer[..amount_read].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
local_id,
|
||||
remote_id,
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => {
|
||||
// Currently file mtime is not forwarded
|
||||
let subcommand_data = MessageSubcommand::Done.with_arg(0);
|
||||
|
||||
let serialized_message = bincode::serialize(&subcommand_data)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
local_id,
|
||||
remote_id,
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
|
||||
// Command should end with a Write => Okay
|
||||
let received = self.transport.read_message()?;
|
||||
match received.header().command() {
|
||||
MessageCommand::Write => return Ok(()),
|
||||
c => {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"Wrong command received {c}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(size) => {
|
||||
let subcommand_data = MessageSubcommand::Data.with_arg(size as u32);
|
||||
|
||||
let mut serialized_message = bincode::serialize(&subcommand_data)
|
||||
.map_err(|_e| RustADBError::ConversionError)?;
|
||||
serialized_message.append(&mut buffer[..size].to_vec());
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
local_id,
|
||||
remote_id,
|
||||
&serialized_message,
|
||||
);
|
||||
|
||||
self.send_and_expect_okay(message)?;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(RustADBError::IOError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_synchronization(&mut self) -> Result<()> {
|
||||
self.open_session(b"sync:\0")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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 message = ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&bincode::serialize(&stat_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||
);
|
||||
self.send_and_expect_okay(message)?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
remote_path.as_bytes(),
|
||||
))?;
|
||||
let response = self.transport.read_message()?;
|
||||
// Skip first 4 bytes as this is the literal "STAT".
|
||||
// Interesting part starts right after
|
||||
bincode::deserialize(&response.into_payload()[4..])
|
||||
.map_err(|_e| RustADBError::ConversionError)
|
||||
}
|
||||
|
||||
pub(crate) fn end_transaction(&mut self) -> Result<()> {
|
||||
let quit_buffer = MessageSubcommand::Quit.with_arg(0u32);
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&bincode::serialize(&quit_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||
))?;
|
||||
let _discard_close = self.transport.read_message()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
|
||||
let mut rng = rand::rng();
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Open,
|
||||
rng.random(), // Our 'local-id'
|
||||
0,
|
||||
data,
|
||||
);
|
||||
self.get_transport_mut().write_message(message)?;
|
||||
|
||||
let response = self.get_transport_mut().read_message()?;
|
||||
|
||||
self.local_id = Some(response.header().arg1());
|
||||
self.remote_id = Some(response.header().arg0());
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub(crate) fn get_local_id(&self) -> Result<u32> {
|
||||
self.local_id.ok_or(RustADBError::ADBRequestFailed(
|
||||
"connection not opened, no local_id".into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn get_remote_id(&self) -> Result<u32> {
|
||||
self.remote_id.ok_or(RustADBError::ADBRequestFailed(
|
||||
"connection not opened, no remote_id".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
use crate::{ADBDeviceExt, ADBMessageTransport, RebootType, Result, models::AdbStatResponse};
|
||||
use crate::{
|
||||
ADBDeviceExt, RebootType, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
models::AdbStatResponse,
|
||||
};
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use super::ADBMessageDevice;
|
||||
|
||||
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
|
||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
||||
self.shell_command(command, output)
|
||||
@@ -42,8 +46,4 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
|
||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
||||
self.framebuffer_inner()
|
||||
}
|
||||
|
||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
||||
self.list(path)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::ADBTransport;
|
||||
use crate::{Result, device::ADBTransportMessage};
|
||||
use crate::{
|
||||
Result, adb_transport::ADBTransport,
|
||||
message_devices::adb_transport_message::ADBTransportMessage,
|
||||
};
|
||||
|
||||
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(u64::MAX);
|
||||
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
@@ -1,12 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Result, RustADBError, device::adb_message_device};
|
||||
|
||||
use super::models::MessageCommand;
|
||||
|
||||
pub const AUTH_TOKEN: u32 = 1;
|
||||
pub const AUTH_SIGNATURE: u32 = 2;
|
||||
pub const AUTH_RSAPUBLICKEY: u32 = 3;
|
||||
use crate::{Result, RustADBError, message_devices::message_commands::MessageCommand};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ADBTransportMessage {
|
||||
@@ -58,16 +52,16 @@ impl ADBTransportMessageHeader {
|
||||
}
|
||||
|
||||
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
|
||||
data.iter().map(|&x| u32::from(x)).sum()
|
||||
data.iter().map(|&x| x as u32).sum()
|
||||
}
|
||||
|
||||
fn compute_magic(command: MessageCommand) -> u32 {
|
||||
let command_u32 = command as u32;
|
||||
command_u32 ^ 0xFFFF_FFFF
|
||||
command_u32 ^ 0xFFFFFFFF
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> Result<Vec<u8>> {
|
||||
adb_message_device::bincode_serialize_to_vec(self)
|
||||
bincode::serialize(&self).map_err(|_e| RustADBError::ConversionError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +111,6 @@ impl TryFrom<[u8; 24]> for ADBTransportMessageHeader {
|
||||
type Error = RustADBError;
|
||||
|
||||
fn try_from(value: [u8; 24]) -> Result<Self> {
|
||||
adb_message_device::bincode_deserialize_from_slice(&value)
|
||||
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError)
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,19 @@ use byteorder::{LittleEndian, ReadBytesExt};
|
||||
use image::{ImageBuffer, Rgba};
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result, RustADBError,
|
||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
models::{FrameBufferInfoV1, FrameBufferInfoV2},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
|
||||
let session = self.open_session(b"framebuffer:\0")?;
|
||||
self.open_session(b"framebuffer:\0")?;
|
||||
|
||||
let response = self.recv_and_reply_okay(session)?;
|
||||
let response = self.recv_and_reply_okay()?;
|
||||
|
||||
let mut payload_cursor = Cursor::new(response.payload());
|
||||
|
||||
@@ -32,11 +35,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||
|
||||
loop {
|
||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
||||
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||
break;
|
||||
}
|
||||
|
||||
let response = self.recv_and_reply_okay(session)?;
|
||||
let response = self.recv_and_reply_okay()?;
|
||||
|
||||
framebuffer_data.extend_from_slice(&response.into_payload());
|
||||
|
||||
@@ -65,11 +68,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||
|
||||
loop {
|
||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
||||
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||
break;
|
||||
}
|
||||
|
||||
let response = self.recv_and_reply_okay(session)?;
|
||||
let response = self.recv_and_reply_okay()?;
|
||||
|
||||
framebuffer_data.extend_from_slice(&response.into_payload());
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use std::{fs::File, path::Path};
|
||||
|
||||
use crate::{
|
||||
ADBMessageTransport, Result,
|
||||
device::{MessageWriter, adb_message_device::ADBMessageDevice},
|
||||
Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
commands::utils::MessageWriter,
|
||||
},
|
||||
utils::check_extension_is_apk,
|
||||
};
|
||||
|
||||
@@ -14,12 +17,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
|
||||
let file_size = apk_file.metadata()?.len();
|
||||
|
||||
let session =
|
||||
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").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, session.local_id(), session.remote_id());
|
||||
let mut writer = MessageWriter::new(transport, self.get_local_id()?, self.get_remote_id()?);
|
||||
|
||||
std::io::copy(&mut apk_file, &mut writer)?;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
mod framebuffer;
|
||||
mod install;
|
||||
mod list;
|
||||
mod pull;
|
||||
mod push;
|
||||
mod reboot;
|
||||
mod shell;
|
||||
mod stat;
|
||||
mod uninstall;
|
||||
mod utils;
|
||||
54
adb_client/src/message_devices/commands/pull.rs
Normal file
54
adb_client/src/message_devices/commands/pull.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice,
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage,
|
||||
message_commands::{MessageCommand, MessageSubcommand},
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
|
||||
self.begin_synchronization()?;
|
||||
let source = source.as_ref();
|
||||
|
||||
let adb_stat_response = self.stat_with_explicit_ids(source)?;
|
||||
|
||||
if adb_stat_response.file_perm == 0 {
|
||||
return Err(RustADBError::UnknownResponseType(
|
||||
"mode is 0: source file does not exist".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let local_id = self.get_local_id()?;
|
||||
let remote_id = self.get_remote_id()?;
|
||||
|
||||
self.get_transport_mut().write_message_with_timeout(
|
||||
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]),
|
||||
std::time::Duration::from_secs(4),
|
||||
)?;
|
||||
|
||||
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32);
|
||||
let recv_buffer =
|
||||
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&recv_buffer,
|
||||
))?;
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
source.as_bytes(),
|
||||
))?;
|
||||
|
||||
self.recv_file(output)?;
|
||||
self.end_transaction()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
37
adb_client/src/message_devices/commands/push.rs
Normal file
37
adb_client/src/message_devices/commands/push.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice,
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage,
|
||||
message_commands::{MessageCommand, MessageSubcommand},
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
|
||||
self.begin_synchronization()?;
|
||||
|
||||
let path_header = format!("{},0777", path.as_ref());
|
||||
|
||||
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32);
|
||||
let mut send_buffer =
|
||||
bincode::serialize(&send_buffer).map_err(|_e| RustADBError::ConversionError)?;
|
||||
send_buffer.append(&mut path_header.as_bytes().to_vec());
|
||||
|
||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||
MessageCommand::Write,
|
||||
self.get_local_id()?,
|
||||
self.get_remote_id()?,
|
||||
&send_buffer,
|
||||
))?;
|
||||
|
||||
self.push_file(self.get_local_id()?, self.get_remote_id()?, stream)?;
|
||||
|
||||
self.end_transaction()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
use crate::{
|
||||
ADBMessageTransport, RebootType, Result,
|
||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
||||
RebootType, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
@@ -1,45 +1,35 @@
|
||||
use std::io::{ErrorKind, Read, Write};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::Result;
|
||||
use crate::device::ShellMessageWriter;
|
||||
use crate::{
|
||||
ADBMessageTransport, RustADBError,
|
||||
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
|
||||
Result, RustADBError,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::ADBTransportMessage, commands::utils::ShellMessageWriter,
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
/// Runs 'command' in a shell on the device, and write its output and error streams into output.
|
||||
pub(crate) fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
||||
let session = self.open_session(format!("shell:{}\0", command.join(" "),).as_bytes())?;
|
||||
let response = self.open_session(format!("shell:{}\0", command.join(" "),).as_bytes())?;
|
||||
|
||||
let mut transport = self.get_transport().clone();
|
||||
if response.header().command() != MessageCommand::Okay {
|
||||
return Err(RustADBError::ADBRequestFailed(format!(
|
||||
"wrong command {}",
|
||||
response.header().command()
|
||||
)));
|
||||
}
|
||||
|
||||
loop {
|
||||
let message = transport.read_message()?;
|
||||
let command = message.header().command();
|
||||
|
||||
if command == MessageCommand::Clse {
|
||||
let response = self.get_transport_mut().read_message()?;
|
||||
if response.header().command() != MessageCommand::Write {
|
||||
break;
|
||||
}
|
||||
|
||||
self.get_transport_mut()
|
||||
.write_message(ADBTransportMessage::new(
|
||||
MessageCommand::Okay,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&[],
|
||||
))?;
|
||||
|
||||
output.write_all(&message.into_payload())?;
|
||||
output.write_all(&response.into_payload())?;
|
||||
}
|
||||
|
||||
// some devices will repeat the trailing CLSE command to ensure
|
||||
// the client has acknowledged it. Read them quickly if present.
|
||||
while let Ok(_discard_close_message) =
|
||||
transport.read_message_with_timeout(Duration::from_millis(20))
|
||||
{}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -50,22 +40,21 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
mut reader: &mut dyn Read,
|
||||
mut writer: Box<dyn Write + Send>,
|
||||
) -> Result<()> {
|
||||
let session = self.open_session(b"shell:\0")?;
|
||||
self.open_session(b"shell:\0")?;
|
||||
|
||||
let mut transport = self.get_transport().clone();
|
||||
|
||||
let local_id = self.get_local_id()?;
|
||||
let remote_id = self.get_remote_id()?;
|
||||
|
||||
// Reading thread, reads response from adbd
|
||||
std::thread::spawn(move || -> Result<()> {
|
||||
loop {
|
||||
let message = transport.read_message()?;
|
||||
|
||||
// Acknowledge for more data
|
||||
let response = ADBTransportMessage::new(
|
||||
MessageCommand::Okay,
|
||||
session.local_id(),
|
||||
session.remote_id(),
|
||||
&[],
|
||||
);
|
||||
let response =
|
||||
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]);
|
||||
transport.write_message(response)?;
|
||||
|
||||
match message.header().command() {
|
||||
@@ -73,15 +62,14 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
writer.write_all(&message.into_payload())?;
|
||||
writer.flush()?;
|
||||
}
|
||||
MessageCommand::Okay => {}
|
||||
MessageCommand::Okay => continue,
|
||||
_ => return Err(RustADBError::ADBShellNotSupported),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let transport = self.get_transport().clone();
|
||||
let mut shell_writer =
|
||||
ShellMessageWriter::new(transport, session.local_id(), session.remote_id());
|
||||
let mut shell_writer = ShellMessageWriter::new(transport, local_id, remote_id);
|
||||
|
||||
// Read from given reader (that could be stdin e.g), and write content to device adbd
|
||||
if let Err(e) = std::io::copy(&mut reader, &mut shell_writer) {
|
||||
15
adb_client/src/message_devices/commands/stat.rs
Normal file
15
adb_client/src/message_devices/commands/stat.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use crate::{
|
||||
AdbStatResponse, Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
||||
self.begin_synchronization()?;
|
||||
let adb_stat_response = self.stat_with_explicit_ids(remote_path)?;
|
||||
self.end_transaction()?;
|
||||
Ok(adb_stat_response)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
use crate::{ADBMessageTransport, Result, device::adb_message_device::ADBMessageDevice};
|
||||
use crate::{
|
||||
Result,
|
||||
message_devices::{
|
||||
adb_message_device::ADBMessageDevice, adb_message_transport::ADBMessageTransport,
|
||||
},
|
||||
};
|
||||
|
||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
||||
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {
|
||||
@@ -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.
|
||||
///
|
||||
4
adb_client/src/message_devices/commands/utils/mod.rs
Normal file
4
adb_client/src/message_devices/commands/utils/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
mod message_writer;
|
||||
mod shell_message_writer;
|
||||
pub use message_writer::MessageWriter;
|
||||
pub use shell_message_writer::ShellMessageWriter;
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::ADBMessageTransport;
|
||||
|
||||
use super::{ADBTransportMessage, models::MessageCommand};
|
||||
use crate::message_devices::{
|
||||
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
|
||||
message_commands::MessageCommand,
|
||||
};
|
||||
|
||||
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
|
||||
pub struct ShellMessageWriter<T: ADBMessageTransport> {
|
||||
@@ -6,32 +6,32 @@ use std::fmt::Display;
|
||||
#[repr(u32)]
|
||||
pub enum MessageCommand {
|
||||
/// Connect to a device
|
||||
Cnxn = 0x4E58_4E43,
|
||||
Cnxn = 0x4E584E43,
|
||||
/// Close connection to a device
|
||||
Clse = 0x4553_4C43,
|
||||
Clse = 0x45534C43,
|
||||
/// Device ask for authentication
|
||||
Auth = 0x4854_5541,
|
||||
Auth = 0x48545541,
|
||||
/// Open a data connection
|
||||
Open = 0x4E45_504F,
|
||||
Open = 0x4E45504F,
|
||||
/// Write data to connection
|
||||
Write = 0x4554_5257,
|
||||
Write = 0x45545257,
|
||||
/// Server understood the message
|
||||
Okay = 0x5941_4B4F,
|
||||
Okay = 0x59414B4F,
|
||||
/// Start a connection using TLS
|
||||
Stls = 0x534C_5453,
|
||||
Stls = 0x534C5453,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize_repr, Deserialize_repr)]
|
||||
#[repr(u32)]
|
||||
pub enum MessageSubcommand {
|
||||
Stat = 0x5441_5453,
|
||||
Send = 0x444E_4553,
|
||||
Recv = 0x5643_4552,
|
||||
Quit = 0x5449_5551,
|
||||
Fail = 0x4C49_4146,
|
||||
Done = 0x454E_4F44,
|
||||
Data = 0x4154_4144,
|
||||
List = 0x5453_494C,
|
||||
Stat = 0x54415453,
|
||||
Send = 0x444E4553,
|
||||
Recv = 0x56434552,
|
||||
Quit = 0x54495551,
|
||||
Fail = 0x4C494146,
|
||||
Done = 0x454E4F44,
|
||||
Data = 0x41544144,
|
||||
List = 0x5453494C,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
14
adb_client/src/message_devices/mod.rs
Normal file
14
adb_client/src/message_devices/mod.rs
Normal 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;
|
||||
13
adb_client/src/message_devices/tcp/README.md
Normal file
13
adb_client/src/message_devices/tcp/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Examples
|
||||
|
||||
## Get a shell from device
|
||||
|
||||
```rust no_run
|
||||
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
|
||||
use adb_client::{tcp::ADBTcpDevice, ADBDeviceExt};
|
||||
|
||||
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
|
||||
let device_port = 43210;
|
||||
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
|
||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
|
||||
```
|
||||
@@ -2,42 +2,23 @@ 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::{ADBRsaKey, ADBTransportMessage, get_default_adb_key_path};
|
||||
use crate::device::adb_usb_device::read_adb_private_key;
|
||||
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 TCP.
|
||||
/// Represent a device reached and available over USB.
|
||||
#[derive(Debug)]
|
||||
pub struct ADBTcpDevice {
|
||||
private_key: ADBRsaKey,
|
||||
inner: ADBMessageDevice<TcpTransport>,
|
||||
}
|
||||
|
||||
impl ADBTcpDevice {
|
||||
/// Instantiate a new [`ADBTcpDevice`]
|
||||
pub fn new(address: SocketAddr) -> Result<Self> {
|
||||
Self::new_with_custom_private_key(address, get_default_adb_key_path()?)
|
||||
}
|
||||
|
||||
/// Instantiate a new [`ADBTcpDevice`] using a custom private key path
|
||||
pub fn new_with_custom_private_key<P: AsRef<Path>>(
|
||||
address: SocketAddr,
|
||||
private_key_path: P,
|
||||
) -> Result<Self> {
|
||||
let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
|
||||
private_key
|
||||
} else {
|
||||
log::warn!(
|
||||
"No private key found at path {}. Using a temporary random one.",
|
||||
private_key_path.as_ref().display()
|
||||
);
|
||||
ADBRsaKey::new_random()?
|
||||
};
|
||||
|
||||
let mut device = Self {
|
||||
private_key,
|
||||
inner: ADBMessageDevice::new(TcpTransport::new(address)?),
|
||||
};
|
||||
|
||||
@@ -52,8 +33,8 @@ impl ADBTcpDevice {
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Cnxn,
|
||||
0x0100_0000,
|
||||
1_048_576,
|
||||
0x01000000,
|
||||
1048576,
|
||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||
);
|
||||
|
||||
@@ -61,28 +42,26 @@ impl ADBTcpDevice {
|
||||
|
||||
let message = self.get_transport_mut().read_message()?;
|
||||
|
||||
// Check if a client is requesting a secure connection and upgrade it if necessary
|
||||
// Check if client is requesting a secure connection and upgrade it if necessary
|
||||
match message.header().command() {
|
||||
MessageCommand::Stls => {
|
||||
self.get_transport_mut()
|
||||
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
|
||||
self.get_transport_mut().upgrade_connection()?;
|
||||
log::debug!("Connection successfully upgraded from TCP to TLS");
|
||||
Ok(())
|
||||
}
|
||||
MessageCommand::Cnxn => {
|
||||
log::debug!("Unencrypted connection established");
|
||||
Ok(())
|
||||
}
|
||||
MessageCommand::Auth => {
|
||||
log::debug!("Authentication required");
|
||||
self.inner.auth_handshake(message, &self.private_key)
|
||||
_ => {
|
||||
return Err(crate::RustADBError::WrongResponseReceived(
|
||||
"Expected CNXN or STLS command".to_string(),
|
||||
message.header().command().to_string(),
|
||||
));
|
||||
}
|
||||
_ => Err(crate::RustADBError::WrongResponseReceived(
|
||||
"Expected CNXN, STLS or AUTH command".to_string(),
|
||||
message.header().command().to_string(),
|
||||
)),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -136,10 +115,6 @@ impl ADBDeviceExt for ADBTcpDevice {
|
||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
||||
self.inner.framebuffer_inner()
|
||||
}
|
||||
|
||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
||||
self.inner.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ADBTcpDevice {
|
||||
6
adb_client/src/message_devices/tcp/mod.rs
Normal file
6
adb_client/src/message_devices/tcp/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#![doc = include_str!("./README.md")]
|
||||
|
||||
mod adb_tcp_device;
|
||||
mod tcp_transport;
|
||||
|
||||
pub use adb_tcp_device::ADBTcpDevice;
|
||||
@@ -5,17 +5,21 @@ use rustls::{
|
||||
pki_types::{CertificateDer, PrivatePkcs8KeyDer, pem::PemObject},
|
||||
};
|
||||
|
||||
use super::{ADBMessageTransport, ADBTransport};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
device::{
|
||||
ADBTransportMessage, ADBTransportMessageHeader, MessageCommand, get_default_adb_key_path,
|
||||
adb_transport::ADBTransport,
|
||||
message_devices::{
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
utils::get_default_adb_key_path,
|
||||
};
|
||||
use std::{
|
||||
fs::read_to_string,
|
||||
io::{Read, Write},
|
||||
net::{Shutdown, SocketAddr, TcpStream},
|
||||
ops::{Deref, DerefMut},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
@@ -119,15 +123,18 @@ impl TcpTransport {
|
||||
}
|
||||
|
||||
pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
|
||||
let Some(current_connection) = self.current_connection.clone() else {
|
||||
return Err(RustADBError::UpgradeError(
|
||||
"cannot upgrade a non-existing connection...".into(),
|
||||
));
|
||||
let current_connection = match self.current_connection.clone() {
|
||||
Some(current_connection) => current_connection,
|
||||
None => {
|
||||
return Err(RustADBError::UpgradeError(
|
||||
"cannot upgrade a non-existing connection...".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
let mut current_conn_locked = current_connection.lock()?;
|
||||
match &*current_conn_locked {
|
||||
match current_conn_locked.deref() {
|
||||
CurrentConnection::Tcp(tcp_stream) => {
|
||||
// TODO: Check if we cannot be more precise
|
||||
|
||||
@@ -188,7 +195,7 @@ impl ADBTransport for TcpTransport {
|
||||
log::debug!("disconnecting...");
|
||||
if let Some(current_connection) = &self.current_connection {
|
||||
let mut lock = current_connection.lock()?;
|
||||
match &mut *lock {
|
||||
match lock.deref_mut() {
|
||||
CurrentConnection::Tcp(tcp_stream) => {
|
||||
let _ = tcp_stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
@@ -207,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()?;
|
||||
|
||||
26
adb_client/src/message_devices/usb/README.md
Normal file
26
adb_client/src/message_devices/usb/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# Examples
|
||||
|
||||
## Launch a command on device
|
||||
|
||||
```rust no_run
|
||||
use adb_client::{usb::ADBUSBDevice, ADBDeviceExt};
|
||||
|
||||
let vendor_id = 0x04e8;
|
||||
let product_id = 0x6860;
|
||||
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
|
||||
device.shell_command(&["df", "-h"], &mut std::io::stdout());
|
||||
```
|
||||
|
||||
## Push a file to the device
|
||||
|
||||
```rust no_run
|
||||
use adb_client::{usb::ADBUSBDevice, ADBDeviceExt};
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
let vendor_id = 0x04e8;
|
||||
let product_id = 0x6860;
|
||||
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
|
||||
let mut input = File::open(Path::new("/tmp/file.txt")).expect("Cannot open file");
|
||||
device.push(&mut input, &"/data/local/tmp");
|
||||
```
|
||||
@@ -6,7 +6,6 @@ use num_traits::cast::ToPrimitive;
|
||||
use rsa::pkcs8::DecodePrivateKey;
|
||||
use rsa::traits::PublicKeyParts;
|
||||
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
|
||||
use std::fmt::Write;
|
||||
|
||||
const ADB_PRIVATE_KEY_SIZE: usize = 2048;
|
||||
const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64;
|
||||
@@ -93,16 +92,15 @@ impl ADBRsaKey {
|
||||
.to_u32()
|
||||
.ok_or(RustADBError::ConversionError)?;
|
||||
|
||||
Self::encode_public_key(adb_rsa_pubkey.into_bytes())
|
||||
Ok(self.encode_public_key(adb_rsa_pubkey.into_bytes()))
|
||||
}
|
||||
|
||||
fn encode_public_key(pub_key: Vec<u8>) -> Result<String> {
|
||||
fn encode_public_key(&self, pub_key: Vec<u8>) -> String {
|
||||
let mut encoded = STANDARD.encode(pub_key);
|
||||
encoded.push(' ');
|
||||
write!(encoded, "adb_client@{}", env!("CARGO_PKG_VERSION"))
|
||||
.map_err(|_| RustADBError::ConversionError)?;
|
||||
encoded.push_str(&format!("adb_client@{}", env!("CARGO_PKG_VERSION")));
|
||||
|
||||
Ok(encoded)
|
||||
encoded
|
||||
}
|
||||
|
||||
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
||||
@@ -126,7 +124,7 @@ fn set_bit(n: usize) -> Result<BigUint> {
|
||||
|
||||
#[test]
|
||||
fn test_pubkey_gen() {
|
||||
const DEFAULT_PRIV_KEY: &str = r"-----BEGIN PRIVATE KEY-----
|
||||
const DEFAULT_PRIV_KEY: &'static str = r"-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4Dyn85cxDJnjM
|
||||
uYXQl/w469MDKdlGdviLfmFMWeYLVfL2Mz1AVyvKqscrtlhbbgMQ/M+3lDvEdHS0
|
||||
14RIGAwWRtrlTTmhLvM2/IO+eSKSYeCrCVc4KLG3E3WRryUXbs2ynA29xjTJVw+Z
|
||||
@@ -7,14 +7,23 @@ use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::adb_message_device::ADBMessageDevice;
|
||||
use super::models::MessageCommand;
|
||||
use super::{ADBRsaKey, ADBTransportMessage};
|
||||
use crate::ADBDeviceExt;
|
||||
use crate::ADBMessageTransport;
|
||||
use crate::ADBTransport;
|
||||
use crate::{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>> {
|
||||
// Try to read the private key file from given path
|
||||
@@ -90,12 +99,6 @@ pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor)
|
||||
false
|
||||
}
|
||||
|
||||
pub fn get_default_adb_key_path() -> Result<PathBuf> {
|
||||
std::env::home_dir()
|
||||
.map(|home| home.join(".android").join("adbkey"))
|
||||
.ok_or(RustADBError::NoHomeDirectory)
|
||||
}
|
||||
|
||||
/// Represent a device reached and available over USB.
|
||||
#[derive(Debug)]
|
||||
pub struct ADBUSBDevice {
|
||||
@@ -110,10 +113,10 @@ impl ADBUSBDevice {
|
||||
}
|
||||
|
||||
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path
|
||||
pub fn new_with_custom_private_key<P: AsRef<Path>>(
|
||||
pub fn new_with_custom_private_key(
|
||||
vendor_id: u16,
|
||||
product_id: u16,
|
||||
private_key_path: P,
|
||||
private_key_path: PathBuf,
|
||||
) -> Result<Self> {
|
||||
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
|
||||
}
|
||||
@@ -128,21 +131,22 @@ impl ADBUSBDevice {
|
||||
None => get_default_adb_key_path()?,
|
||||
};
|
||||
|
||||
Self::new_from_transport_inner(transport, &private_key_path)
|
||||
Self::new_from_transport_inner(transport, private_key_path)
|
||||
}
|
||||
|
||||
fn new_from_transport_inner<P: AsRef<Path>>(
|
||||
fn new_from_transport_inner(
|
||||
transport: USBTransport,
|
||||
private_key_path: P,
|
||||
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.as_ref().display()
|
||||
);
|
||||
ADBRsaKey::new_random()?
|
||||
let private_key = match read_adb_private_key(&private_key_path)? {
|
||||
Some(pk) => pk,
|
||||
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 {
|
||||
@@ -178,8 +182,8 @@ impl ADBUSBDevice {
|
||||
|
||||
let message = ADBTransportMessage::new(
|
||||
MessageCommand::Cnxn,
|
||||
0x0100_0000,
|
||||
1_048_576,
|
||||
0x01000000,
|
||||
1048576,
|
||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||
);
|
||||
|
||||
@@ -191,9 +195,55 @@ impl ADBUSBDevice {
|
||||
if message.header().command() == MessageCommand::Cnxn {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
message.assert_command(MessageCommand::Auth)?;
|
||||
self.inner.auth_handshake(message, &self.private_key)
|
||||
|
||||
// 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]
|
||||
@@ -247,10 +297,6 @@ impl ADBDeviceExt for ADBUSBDevice {
|
||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
||||
self.inner.framebuffer_inner()
|
||||
}
|
||||
|
||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
||||
self.inner.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ADBUSBDevice {
|
||||
8
adb_client/src/message_devices/usb/mod.rs
Normal file
8
adb_client/src/message_devices/usb/mod.rs
Normal 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;
|
||||
@@ -5,10 +5,14 @@ use rusb::{
|
||||
constants::LIBUSB_CLASS_VENDOR_SPEC,
|
||||
};
|
||||
|
||||
use super::{ADBMessageTransport, ADBTransport};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
device::{ADBTransportMessage, ADBTransportMessageHeader, MessageCommand},
|
||||
adb_transport::ADBTransport,
|
||||
message_devices::{
|
||||
adb_message_transport::ADBMessageTransport,
|
||||
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
||||
message_commands::MessageCommand,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -29,14 +33,13 @@ pub struct USBTransport {
|
||||
|
||||
impl USBTransport {
|
||||
/// Instantiate a new [`USBTransport`].
|
||||
/// 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> {
|
||||
for device in rusb::devices()?.iter() {
|
||||
if let Ok(descriptor) = device.device_descriptor()
|
||||
&& descriptor.vendor_id() == vendor_id
|
||||
&& descriptor.product_id() == product_id
|
||||
{
|
||||
return Ok(Self::new_from_device(device));
|
||||
if let Ok(descriptor) = device.device_descriptor() {
|
||||
if descriptor.vendor_id() == vendor_id && descriptor.product_id() == product_id {
|
||||
return Ok(Self::new_from_device(device));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +51,6 @@ impl USBTransport {
|
||||
/// Instantiate a new [`USBTransport`] from a [`rusb::Device`].
|
||||
///
|
||||
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
|
||||
#[must_use]
|
||||
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
|
||||
Self {
|
||||
device: rusb_device,
|
||||
@@ -92,13 +94,14 @@ impl USBTransport {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_endpoints(handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
||||
fn find_endpoints(&self, handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
||||
let mut read_endpoint: Option<Endpoint> = None;
|
||||
let mut write_endpoint: Option<Endpoint> = None;
|
||||
|
||||
for n in 0..handle.device().device_descriptor()?.num_configurations() {
|
||||
let Ok(config_desc) = handle.device().config_descriptor(n) else {
|
||||
continue;
|
||||
let config_desc = match handle.device().config_descriptor(n) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
for interface in config_desc.interfaces() {
|
||||
@@ -118,14 +121,16 @@ impl USBTransport {
|
||||
Direction::In => {
|
||||
if let Some(write_endpoint) = write_endpoint {
|
||||
return Ok((endpoint, write_endpoint));
|
||||
} else {
|
||||
read_endpoint = Some(endpoint);
|
||||
}
|
||||
read_endpoint = Some(endpoint);
|
||||
}
|
||||
Direction::Out => {
|
||||
if let Some(read_endpoint) = read_endpoint {
|
||||
return Ok((read_endpoint, endpoint));
|
||||
} else {
|
||||
write_endpoint = Some(endpoint);
|
||||
}
|
||||
write_endpoint = Some(endpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,7 +154,7 @@ impl USBTransport {
|
||||
let write_amount = handle.write_bulk(endpoint.address, &data[offset..end], timeout)?;
|
||||
offset += write_amount;
|
||||
|
||||
log::trace!("wrote chunk of size {write_amount} - {offset}/{data_len}",);
|
||||
log::trace!("wrote chunk of size {write_amount} - {offset}/{data_len}",)
|
||||
}
|
||||
|
||||
if offset % max_packet_size == 0 {
|
||||
@@ -165,7 +170,7 @@ impl ADBTransport for USBTransport {
|
||||
fn connect(&mut self) -> crate::Result<()> {
|
||||
let device = self.device.open()?;
|
||||
|
||||
let (read_endpoint, write_endpoint) = Self::find_endpoints(&device)?;
|
||||
let (read_endpoint, write_endpoint) = self.find_endpoints(&device)?;
|
||||
|
||||
Self::configure_endpoint(&device, &read_endpoint)?;
|
||||
log::debug!("got read endpoint: {read_endpoint:?}");
|
||||
@@ -1,8 +1,11 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
/// Available host features.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum HostFeatures {
|
||||
/// Shell version 2.
|
||||
ShellV2,
|
||||
/// Command.
|
||||
Cmd,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
/// A list entry on the remote device
|
||||
pub struct ADBListItem {
|
||||
/// The name of the file, not the path
|
||||
pub name: String,
|
||||
/// The unix time stamp of when it was last modified
|
||||
pub time: u32,
|
||||
/// The unix mode of the file, used for permissions and special bits
|
||||
pub permissions: u32,
|
||||
/// The size of the file
|
||||
pub size: u32,
|
||||
/// The type of item this is, file, directory or symlink
|
||||
pub item_type: ADBListItemType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
/// The different types of item that the list item can be
|
||||
pub enum ADBListItemType {
|
||||
/// The entry is a file
|
||||
File,
|
||||
/// The entry is a directory
|
||||
Directory,
|
||||
/// The entry is a symlink
|
||||
Symlink,
|
||||
}
|
||||
@@ -1,17 +1,13 @@
|
||||
mod adb_request_status;
|
||||
mod adb_server_command;
|
||||
mod adb_stat_response;
|
||||
mod framebuffer_info;
|
||||
mod host_features;
|
||||
mod list_info;
|
||||
mod reboot_type;
|
||||
mod sync_command;
|
||||
|
||||
pub 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 list_info::{ADBListItem, ADBListItemType};
|
||||
pub use reboot_type::RebootType;
|
||||
pub use sync_command::SyncCommand;
|
||||
pub(crate) use sync_command::SyncCommand;
|
||||
|
||||
15
adb_client/src/server/README.md
Normal file
15
adb_client/src/server/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Examples
|
||||
|
||||
## Get available ADB devices
|
||||
|
||||
```rust no_run
|
||||
use adb_client::server::ADBServer;
|
||||
use std::net::{SocketAddrV4, Ipv4Addr};
|
||||
|
||||
// A custom server address can be provided
|
||||
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
|
||||
let server_port = 5037;
|
||||
|
||||
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
|
||||
server.devices();
|
||||
```
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::ADBTransport;
|
||||
use crate::Result;
|
||||
use crate::RustADBError;
|
||||
use crate::TCPServerTransport;
|
||||
use crate::server::tcp_server_transport::TCPServerTransport;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddrV4;
|
||||
use std::process::Command;
|
||||
@@ -9,7 +9,7 @@ use std::process::Command;
|
||||
/// Represents an ADB Server
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ADBServer {
|
||||
/// Internal [`TcpStream`], lazily initialized
|
||||
/// Internal [TcpStream], lazily initialized
|
||||
pub(crate) transport: Option<TCPServerTransport>,
|
||||
/// Address to connect to
|
||||
pub(crate) socket_addr: Option<SocketAddrV4>,
|
||||
@@ -21,8 +21,7 @@ pub struct ADBServer {
|
||||
}
|
||||
|
||||
impl ADBServer {
|
||||
/// Instantiates a new [`ADBServer`]
|
||||
#[must_use]
|
||||
/// Instantiates a new [ADBServer]
|
||||
pub fn new(address: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
transport: None,
|
||||
@@ -32,8 +31,7 @@ impl ADBServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a new [`ADBServer`] with a custom adb path
|
||||
#[must_use]
|
||||
/// Instantiates a new [ADBServer] with a custom adb path
|
||||
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
|
||||
Self {
|
||||
transport: None,
|
||||
@@ -48,7 +46,7 @@ impl ADBServer {
|
||||
// ADB Server is local, we start it if not already running
|
||||
let mut command = Command::new(adb_path.as_deref().unwrap_or("adb"));
|
||||
command.arg("start-server");
|
||||
for (env_k, env_v) in envs {
|
||||
for (env_k, env_v) in envs.iter() {
|
||||
command.env(env_k, env_v);
|
||||
}
|
||||
|
||||
@@ -63,7 +61,7 @@ impl ADBServer {
|
||||
match child {
|
||||
Ok(mut child) => {
|
||||
if let Err(e) = child.wait() {
|
||||
log::error!("error while starting adb server: {e}");
|
||||
log::error!("error while starting adb server: {e}")
|
||||
}
|
||||
}
|
||||
Err(e) => log::error!("error while starting adb server: {e}"),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::{WaitForDeviceState, WaitForDeviceTransport};
|
||||
use crate::{
|
||||
RebootType,
|
||||
server::{WaitForDeviceState, WaitForDeviceTransport},
|
||||
};
|
||||
|
||||
use super::RebootType;
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
pub(crate) enum AdbServerCommand {
|
||||
@@ -26,7 +28,7 @@ pub(crate) enum AdbServerCommand {
|
||||
Install(u64),
|
||||
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
|
||||
// Local commands
|
||||
ShellCommand(String, Vec<String>),
|
||||
ShellCommand(String),
|
||||
Shell,
|
||||
FrameBuffer,
|
||||
Sync,
|
||||
@@ -51,14 +53,10 @@ impl Display for AdbServerCommand {
|
||||
AdbServerCommand::TrackDevices => write!(f, "host:track-devices"),
|
||||
AdbServerCommand::TransportAny => write!(f, "host:transport-any"),
|
||||
AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"),
|
||||
AdbServerCommand::ShellCommand(command, args) => {
|
||||
let args_s = args.join(",");
|
||||
write!(
|
||||
f,
|
||||
"shell{}{args_s},raw:{command}",
|
||||
if args.is_empty() { "" } else { "," }
|
||||
)
|
||||
}
|
||||
AdbServerCommand::ShellCommand(command) => match std::env::var("TERM") {
|
||||
Ok(term) => write!(f, "shell,TERM={term},raw:{command}"),
|
||||
Err(_) => write!(f, "shell,raw:{command}"),
|
||||
},
|
||||
AdbServerCommand::Shell => match std::env::var("TERM") {
|
||||
Ok(term) => write!(f, "shell,TERM={term},raw:"),
|
||||
Err(_) => write!(f, "shell,raw:"),
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::{
|
||||
ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, DeviceShort, Result, RustADBError,
|
||||
models::AdbServerCommand,
|
||||
Result, RustADBError,
|
||||
emulator::ADBEmulatorDevice,
|
||||
server::{ADBServer, AdbServerCommand, DeviceLong, DeviceShort},
|
||||
server_device::ADBServerDevice,
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
@@ -69,12 +71,12 @@ impl ADBServer {
|
||||
.filter(|d| d.identifier.as_str() == name)
|
||||
.collect::<Vec<DeviceShort>>()
|
||||
.len();
|
||||
if nb_devices == 1 {
|
||||
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
||||
} else {
|
||||
if nb_devices != 1 {
|
||||
Err(RustADBError::DeviceNotFound(format!(
|
||||
"could not find device {name}"
|
||||
)))
|
||||
} else {
|
||||
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, RustADBError, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Asks the ADB server to quit immediately.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::io::BufRead;
|
||||
|
||||
use crate::{
|
||||
ADBServer, MDNSServices, Result, models::AdbServerCommand, server::models::MDNSBackend,
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, MDNSServices, models::MDNSBackend},
|
||||
};
|
||||
|
||||
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::models::AdbServerCommand;
|
||||
use crate::{ADBServer, Result, RustADBError};
|
||||
use crate::{
|
||||
Result, RustADBError,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Reconnect the device
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, Result, models::AdbServerCommand, server::models::ServerStatus};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, models::ServerStatus},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Check ADB server status
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBServer, AdbVersion, Result, models::AdbServerCommand};
|
||||
use crate::{
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, AdbVersion},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
/// Gets server's internal version number.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::{
|
||||
ADBServer, Result, WaitForDeviceState, WaitForDeviceTransport, models::AdbServerCommand,
|
||||
Result,
|
||||
server::{ADBServer, AdbServerCommand, WaitForDeviceState, WaitForDeviceTransport},
|
||||
};
|
||||
|
||||
impl ADBServer {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
#![doc = include_str!("./README.md")]
|
||||
|
||||
mod adb_server;
|
||||
mod adb_server_command;
|
||||
mod commands;
|
||||
mod models;
|
||||
mod tcp_server_transport;
|
||||
|
||||
pub use adb_server::ADBServer;
|
||||
pub(crate) use adb_server_command::AdbServerCommand;
|
||||
pub use models::*;
|
||||
pub use tcp_server_transport::TCPServerTransport;
|
||||
|
||||
@@ -15,8 +15,7 @@ pub struct AdbVersion {
|
||||
}
|
||||
|
||||
impl AdbVersion {
|
||||
/// Instantiates a new [`AdbVersion`].
|
||||
#[must_use]
|
||||
/// Instantiates a new [AdbVersion].
|
||||
pub fn new(minor: u32, revision: u32) -> Self {
|
||||
Self {
|
||||
major: 1,
|
||||
|
||||
@@ -2,7 +2,8 @@ use std::str::FromStr;
|
||||
use std::sync::LazyLock;
|
||||
use std::{fmt::Display, str};
|
||||
|
||||
use crate::{DeviceState, RustADBError};
|
||||
use crate::RustADBError;
|
||||
use crate::server::DeviceState;
|
||||
use regex::bytes::Regex;
|
||||
|
||||
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
@@ -86,13 +87,15 @@ impl TryFrom<&[u8]> for DeviceLong {
|
||||
None => "Unk".to_string(),
|
||||
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
||||
},
|
||||
transport_id: (str::from_utf8(
|
||||
groups
|
||||
.name("transport_id")
|
||||
.ok_or(RustADBError::RegexParsingError)?
|
||||
.as_bytes(),
|
||||
)?)
|
||||
.parse::<u32>()?,
|
||||
transport_id: u32::from_str_radix(
|
||||
str::from_utf8(
|
||||
groups
|
||||
.name("transport_id")
|
||||
.ok_or(RustADBError::RegexParsingError)?
|
||||
.as_bytes(),
|
||||
)?,
|
||||
16,
|
||||
)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -107,7 +110,6 @@ fn test_static_devices_long() {
|
||||
"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())
|
||||
.unwrap_or_else(|_| panic!("cannot parse input: '{input}'"));
|
||||
DeviceLong::try_from(input.as_bytes()).expect(&format!("cannot parse input: '{input}'"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use regex::bytes::Regex;
|
||||
use std::{fmt::Display, str::FromStr, sync::LazyLock};
|
||||
|
||||
use crate::{DeviceState, RustADBError};
|
||||
use crate::{RustADBError, server::DeviceState};
|
||||
|
||||
static DEVICES_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));
|
||||
|
||||
@@ -48,11 +48,11 @@ impl Display for UsbBackend {
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub enum MDNSBackend {
|
||||
#[default]
|
||||
/// `Unknown`
|
||||
/// Unknown
|
||||
Unknown = 0,
|
||||
/// `Bonjour`
|
||||
/// Bonjour
|
||||
Bonjour = 1,
|
||||
/// `OpenScreen`
|
||||
/// OpenScreen
|
||||
OpenScreen = 2,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::RustADBError;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug)]
|
||||
/// List of available transports to wait for.
|
||||
pub enum WaitForDeviceTransport {
|
||||
/// USB transport
|
||||
@@ -10,10 +10,15 @@ pub enum WaitForDeviceTransport {
|
||||
/// Local transport
|
||||
Local,
|
||||
/// Any transport (default value)
|
||||
#[default]
|
||||
Any,
|
||||
}
|
||||
|
||||
impl Default for WaitForDeviceTransport {
|
||||
fn default() -> Self {
|
||||
Self::Any
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for WaitForDeviceTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
@@ -24,10 +29,10 @@ impl Display for WaitForDeviceTransport {
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for WaitForDeviceTransport {
|
||||
type Err = RustADBError;
|
||||
impl TryFrom<&str> for WaitForDeviceTransport {
|
||||
type Error = RustADBError;
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
"usb" => Ok(Self::Usb),
|
||||
"local" => Ok(Self::Local),
|
||||
|
||||
@@ -4,11 +4,12 @@ use std::str::FromStr;
|
||||
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
|
||||
use crate::ADBTransport;
|
||||
use crate::models::{AdbRequestStatus, SyncCommand};
|
||||
use crate::{ADBTransport, models::AdbServerCommand};
|
||||
use crate::server::AdbServerCommand;
|
||||
use crate::{Result, RustADBError};
|
||||
|
||||
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::LOCALHOST;
|
||||
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
|
||||
const DEFAULT_SERVER_PORT: u16 = 5037;
|
||||
|
||||
/// Server transport running on top on TCP
|
||||
@@ -25,8 +26,7 @@ impl Default for TCPServerTransport {
|
||||
}
|
||||
|
||||
impl TCPServerTransport {
|
||||
/// Instantiates a new instance of [`TCPServerTransport`]
|
||||
#[must_use]
|
||||
/// Instantiates a new instance of [TCPServerTransport]
|
||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||
Self {
|
||||
socket_addr,
|
||||
@@ -34,8 +34,7 @@ impl TCPServerTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiate a new instance of [`TCPServerTransport`] using given address, or default if not specified.
|
||||
#[must_use]
|
||||
/// Instantiate a new instance of [TCPServerTransport] using given address, or default if not specified.
|
||||
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
|
||||
match socket_addr {
|
||||
Some(s) => Self::new(s),
|
||||
@@ -43,8 +42,7 @@ impl TCPServerTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get underlying [`SocketAddrV4`]
|
||||
#[must_use]
|
||||
/// Get underlying [SocketAddrV4]
|
||||
pub fn get_socketaddr(&self) -> SocketAddrV4 {
|
||||
self.socket_addr
|
||||
}
|
||||
@@ -92,8 +90,8 @@ impl TCPServerTransport {
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Send the given [`SyncCommand`] to ADB server, and checks that the request has been taken in consideration.
|
||||
pub(crate) fn send_sync_request(&mut self, command: &SyncCommand) -> Result<()> {
|
||||
/// Send the given [SyncCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||
pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> {
|
||||
// First 4 bytes are the name of the command we want to send
|
||||
// (e.g. "SEND", "RECV", "STAT", "LIST")
|
||||
Ok(self
|
||||
@@ -101,7 +99,7 @@ impl TCPServerTransport {
|
||||
.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(&self) -> Result<u32> {
|
||||
let length_buffer = self.read_body_length()?;
|
||||
Ok(LittleEndian::read_u32(&length_buffer))
|
||||
@@ -115,8 +113,8 @@ impl TCPServerTransport {
|
||||
Ok(length_buffer)
|
||||
}
|
||||
|
||||
/// Send the given [`AdbCommand`] to ADB server, and checks that the request has been taken in consideration.
|
||||
/// If an error occurred, a [`RustADBError`] is returned with the response error string.
|
||||
/// Send the given [AdbCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||
/// If an error occurred, a [RustADBError] is returned with the response error string.
|
||||
pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> {
|
||||
let adb_command_string = command.to_string();
|
||||
let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string);
|
||||
25
adb_client/src/server_device/README.md
Normal file
25
adb_client/src/server_device/README.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# Examples
|
||||
|
||||
## Launch a command on device
|
||||
|
||||
```rust no_run
|
||||
use adb_client::{server::ADBServer, ADBDeviceExt};
|
||||
|
||||
let mut server = ADBServer::default();
|
||||
let mut device = server.get_device().expect("cannot get device");
|
||||
device.shell_command(&["df", "-h"], &mut std::io::stdout());
|
||||
```
|
||||
|
||||
## Push a file to the device
|
||||
|
||||
```rust no_run
|
||||
use adb_client::server::ADBServer;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
let mut server = ADBServer::default();
|
||||
let mut device = server.get_device().expect("cannot get device");
|
||||
let mut input = File::open(Path::new("/tmp/file.txt")).expect("Cannot open file");
|
||||
device.push(&mut input, "/data/local/tmp");
|
||||
```
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{ADBTransport, Result, TCPServerTransport, models::AdbServerCommand};
|
||||
use crate::{
|
||||
ADBTransport, Result,
|
||||
server::{AdbServerCommand, TCPServerTransport},
|
||||
};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
/// Represents a device connected to the ADB server.
|
||||
@@ -6,13 +9,12 @@ use std::net::SocketAddrV4;
|
||||
pub struct ADBServerDevice {
|
||||
/// Unique device identifier.
|
||||
pub identifier: Option<String>,
|
||||
/// Internal [`TCPServerTransport`]
|
||||
/// Internal [TCPServerTransport]
|
||||
pub(crate) transport: TCPServerTransport,
|
||||
}
|
||||
|
||||
impl ADBServerDevice {
|
||||
/// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
|
||||
#[must_use]
|
||||
/// Instantiates a new [ADBServerDevice], knowing its ADB identifier (as returned by `adb devices` command).
|
||||
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
|
||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||
|
||||
@@ -22,8 +24,7 @@ impl ADBServerDevice {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
|
||||
#[must_use]
|
||||
/// Instantiates a new [ADBServerDevice], assuming only one is currently connected.
|
||||
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
|
||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||
|
||||
|
||||
@@ -5,12 +5,14 @@ use std::{
|
||||
|
||||
use crate::{
|
||||
ADBDeviceExt, Result, RustADBError,
|
||||
constants::BUFFER_SIZE,
|
||||
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
|
||||
models::{AdbStatResponse, HostFeatures},
|
||||
server::AdbServerCommand,
|
||||
};
|
||||
|
||||
use super::ADBServerDevice;
|
||||
|
||||
const BUFFER_SIZE: usize = 65535;
|
||||
|
||||
impl ADBDeviceExt for ADBServerDevice {
|
||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
||||
let supported_features = self.host_features()?;
|
||||
@@ -22,33 +24,18 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
|
||||
self.set_serial_transport()?;
|
||||
|
||||
// Prepare shell command arguments
|
||||
let mut args = Vec::new();
|
||||
let command_string = command.join(" ");
|
||||
|
||||
// Add v2 mode if supported
|
||||
if supported_features.contains(&HostFeatures::ShellV2) {
|
||||
log::debug!("using shell_v2 feature");
|
||||
args.push("v2".to_string());
|
||||
}
|
||||
|
||||
// Include terminal information if available
|
||||
if let Ok(term) = std::env::var("TERM") {
|
||||
args.push(format!("TERM={term}"));
|
||||
}
|
||||
|
||||
// Send the request
|
||||
self.transport
|
||||
.send_adb_request(AdbServerCommand::ShellCommand(command_string, args))?;
|
||||
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
|
||||
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
match self.transport.get_raw_connection()?.read(&mut buffer) {
|
||||
Ok(size) => {
|
||||
if size == 0 {
|
||||
return Ok(());
|
||||
} else {
|
||||
output.write_all(&buffer[..size])?;
|
||||
}
|
||||
output.write_all(&buffer[..size])?;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(RustADBError::IOError(e));
|
||||
@@ -82,9 +69,8 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
|
||||
// Reading thread, reads response from adb-server
|
||||
std::thread::spawn(move || -> Result<()> {
|
||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
||||
|
||||
loop {
|
||||
let mut buffer = [0; BUFFER_SIZE];
|
||||
match read_stream.read(&mut buffer) {
|
||||
Ok(0) => {
|
||||
read_stream.shutdown(std::net::Shutdown::Both)?;
|
||||
@@ -135,8 +121,4 @@ impl ADBDeviceExt for ADBServerDevice {
|
||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
||||
self.framebuffer_inner()
|
||||
}
|
||||
|
||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
||||
self.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{ADBServerDevice, Result, models::AdbServerCommand};
|
||||
use crate::{Result, server::AdbServerCommand, server_device::ADBServerDevice};
|
||||
|
||||
impl ADBServerDevice {
|
||||
/// Forward socket connection
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user