Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6210a6a587 |
38
.github/workflows/python-build.yml
vendored
38
.github/workflows/python-build.yml
vendored
@@ -1,38 +0,0 @@
|
|||||||
name: Python - Build packages & Release
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
pull_request:
|
|
||||||
release:
|
|
||||||
types: [created]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-python-packages:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Build Python stubs
|
|
||||||
run: cargo run --bin stub_gen
|
|
||||||
|
|
||||||
- name: Install Python build dependencies
|
|
||||||
run: pip install maturin==1.8.2
|
|
||||||
|
|
||||||
- name: Build Python packages
|
|
||||||
run: maturin build --sdist --release -m pyadb_client/Cargo.toml
|
|
||||||
|
|
||||||
- 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 artefacts"
|
|
||||||
if: github.event_name == 'release' && github.event.action == 'created'
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
files: |
|
|
||||||
target/wheels/pyadb_client*.whl
|
|
||||||
target/wheels/pyadb_client*.tar.gz
|
|
||||||
29
.github/workflows/rust-build.yml
vendored
29
.github/workflows/rust-build.yml
vendored
@@ -1,29 +0,0 @@
|
|||||||
name: Rust - Build
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
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: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.10"
|
|
||||||
|
|
||||||
- name: Build project
|
|
||||||
run: cargo build --release --all-features
|
|
||||||
46
.github/workflows/rust-quality.yml
vendored
46
.github/workflows/rust-quality.yml
vendored
@@ -1,46 +0,0 @@
|
|||||||
name: Rust - Quality
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
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 -- -Dwarnings
|
|
||||||
|
|
||||||
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
|
|
||||||
109
.github/workflows/rust-release.yml
vendored
109
.github/workflows/rust-release.yml
vendored
@@ -1,109 +0,0 @@
|
|||||||
name: Rust - Release creation
|
|
||||||
|
|
||||||
on:
|
|
||||||
release:
|
|
||||||
types: [created]
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release-linux:
|
|
||||||
name: Linux - Build and Publish
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Rust
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install -y rpm
|
|
||||||
cargo install cargo-deb
|
|
||||||
cargo install cargo-generate-rpm
|
|
||||||
|
|
||||||
- name: Publish crates
|
|
||||||
run: |
|
|
||||||
cargo publish -p adb_client --token ${CRATES_IO_TOKEN}
|
|
||||||
cargo publish -p adb_cli --token ${CRATES_IO_TOKEN}
|
|
||||||
env:
|
|
||||||
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build release
|
|
||||||
run: cargo build -p adb_cli --release
|
|
||||||
|
|
||||||
- name: Rename binary
|
|
||||||
run: cp target/release/adb_cli target/release/adb_cli-linux
|
|
||||||
|
|
||||||
- name: Build DEB package
|
|
||||||
run: cargo deb -p adb_cli
|
|
||||||
|
|
||||||
- name: Build RPM package
|
|
||||||
run: cargo generate-rpm -p adb_cli
|
|
||||||
|
|
||||||
- name: Upload Linux artifacts
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
files: |
|
|
||||||
target/debian/*.deb
|
|
||||||
target/generate-rpm/*.rpm
|
|
||||||
target/release/adb_cli-linux
|
|
||||||
|
|
||||||
release-macos:
|
|
||||||
name: macOS - Build Binary
|
|
||||||
runs-on: macos-13
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Rust
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Build release
|
|
||||||
run: cargo build -p adb_cli --release
|
|
||||||
|
|
||||||
- name: Rename binary
|
|
||||||
run: cp target/release/adb_cli target/release/adb_cli-macos
|
|
||||||
|
|
||||||
- name: Upload macOS binary
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
files: target/release/adb_cli-macos
|
|
||||||
|
|
||||||
release-windows:
|
|
||||||
name: Windows - Build Binary
|
|
||||||
runs-on: windows-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Rust
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.10"
|
|
||||||
|
|
||||||
- name: Build release
|
|
||||||
run: cargo build -p adb_cli --release
|
|
||||||
|
|
||||||
- name: Rename binary
|
|
||||||
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe
|
|
||||||
|
|
||||||
- name: Upload Windows binary
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
files: target/release/adb_cli-windows.exe
|
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -1,6 +1,3 @@
|
|||||||
target
|
target
|
||||||
/Cargo.lock
|
Cargo.lock
|
||||||
/.vscode
|
.vscode
|
||||||
venv
|
|
||||||
/.mypy_cache
|
|
||||||
pyadb_client/pyadb_client.pyi
|
|
||||||
|
|||||||
21
Cargo.toml
21
Cargo.toml
@@ -1,24 +1,13 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = ["adb_cli", "adb_client", "pyadb_client", "examples/mdns"]
|
members = ["adb_cli", "adb_client"]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
authors = ["Corentin LIAUD"]
|
edition = "2021"
|
||||||
edition = "2024"
|
|
||||||
homepage = "https://github.com/cocool97/adb_client"
|
|
||||||
keywords = ["adb", "android", "tcp", "usb"]
|
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
repository = "https://github.com/cocool97/adb_client"
|
repository = "https://github.com/cocool97/adb_client"
|
||||||
version = "2.1.19"
|
version = "1.0.5"
|
||||||
rust-version = "1.91.0"
|
|
||||||
|
|
||||||
# To build locally when working on a new release
|
# To build locally when working on a new version
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
adb_client = { path = "./adb_client" }
|
adb_client = { path = "./adb_client" }
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
codegen-units = 1
|
|
||||||
debug-assertions = false
|
|
||||||
lto = "thin"
|
|
||||||
opt-level = 'z'
|
|
||||||
strip = true
|
|
||||||
21
LICENSE
21
LICENSE
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2023-2024 Corentin LIAUD
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
68
README.md
68
README.md
@@ -1,69 +1,31 @@
|
|||||||
<p align="center" style="text-align: center">
|
# Rust adb_client
|
||||||
<img src="assets/logo.png" width="33%">
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center">
|
[](https://crates.io/crates/adb_client)
|
||||||
<p align="center">Android Debug Bridge (ADB) client implementation in pure Rust !</p>
|
[](https://deps.rs/repo/github/cocool97/adb_client)
|
||||||
<p align="center">
|
|
||||||
<a href="https://crates.io/crates/adb_client">
|
|
||||||
<img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/>
|
|
||||||
</a>
|
|
||||||
<a href="https://crates.io/crates/adb_client">
|
|
||||||
<img alt="msrv" src="https://img.shields.io/crates/msrv/adb_client"/>
|
|
||||||
</a>
|
|
||||||
<a href="https://github.com/cocool97/adb_client/actions">
|
|
||||||
<img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/>
|
|
||||||
</a>
|
|
||||||
<a href="https://deps.rs/repo/github/cocool97/adb_client">
|
|
||||||
<img alt="dependency status" src="https://deps.rs/repo/github/cocool97/adb_client/status.svg"/>
|
|
||||||
</a>
|
|
||||||
<a href="https://opensource.org/licenses/MIT">
|
|
||||||
<img alt="dependency status" src="https://img.shields.io/badge/License-MIT-yellow.svg"/>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
Main features of this library:
|
**A**ndroid **D**ebug **B**ridge (ADB) client implementation in pure Rust !
|
||||||
|
|
||||||
- Full Rust, don't use `adb *` shell commands to interact with devices
|
Main features :
|
||||||
- Supports
|
|
||||||
- Using ADB server as a proxy (standard behavior when using `adb` CLI)
|
- Full Rust, no need to use `adb *` shell commands
|
||||||
- Connecting directly to end devices (without using adb-server)
|
- Currently only support server TCP/IP protocol
|
||||||
- Over **USB**
|
|
||||||
- Over **TCP/IP**
|
|
||||||
- Implements hidden `adb` features, like `framebuffer`
|
|
||||||
- Highly configurable
|
- Highly configurable
|
||||||
- Provides wrappers to use directly from Python code
|
|
||||||
- Easy to use !
|
- Easy to use !
|
||||||
|
|
||||||
## adb_client
|
## adb_client
|
||||||
|
|
||||||
Rust library implementing both ADB protocols (server and end-devices) and providing a high-level abstraction over the many supported commands.
|
Rust library implementing ADB protocol and providing high-level abstraction over commands.
|
||||||
|
|
||||||
Improved documentation available [here](./adb_client/README.md).
|
Improved documentation [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
|
## adb_cli
|
||||||
|
|
||||||
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.
|
Rust binary providing an improved version of `adb` CLI, using `adb_client` library. Can be used as an usage example of the library.
|
||||||
Provides a "real-world" usage example of this library.
|
|
||||||
|
|
||||||
Improved documentation available [here](./adb_cli/README.md).
|
Improved documentation [here](./adb_cli/README.md).
|
||||||
|
|
||||||
## pyadb_client
|
## Missing features
|
||||||
|
|
||||||
Python wrapper using `adb_client` library to export classes usable directly from a Python environment.
|
- USB protocol (Work in progress)
|
||||||
|
|
||||||
Improved documentation available [here](./pyadb_client/README.md)
|
All pull requests are welcome !
|
||||||
|
|
||||||
## Related publications
|
|
||||||
|
|
||||||
- [Diving into ADB protocol internals (1/2)](https://www.synacktiv.com/publications/diving-into-adb-protocol-internals-12)
|
|
||||||
- [Diving into ADB protocol internals (2/2)](https://www.synacktiv.com/publications/diving-into-adb-protocol-internals-22)
|
|
||||||
|
|
||||||
Some features may still be missing, all pull requests are welcome !
|
|
||||||
|
|||||||
@@ -1,39 +1,16 @@
|
|||||||
[package]
|
[package]
|
||||||
authors.workspace = true
|
|
||||||
description = "Rust ADB (Android Debug Bridge) CLI"
|
description = "Rust ADB (Android Debug Bridge) CLI"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
keywords.workspace = true
|
keywords = ["adb", "android"]
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
name = "adb_cli"
|
name = "adb_cli"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
rust-version.workspace = true
|
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
adb_client = { version = "^2.1.19", features = ["mdns"] }
|
adb_client = { version = "1.0.5" }
|
||||||
clap = { version = "4.5.53", features = ["derive"] }
|
anyhow = { version = "1.0.86" }
|
||||||
env_logger = { version = "0.11.8" }
|
clap = { version = "4.5.17", features = ["derive"] }
|
||||||
log = { version = "0.4.29" }
|
env_logger = { version = "0.11.5" }
|
||||||
|
log = "0.4.22"
|
||||||
[target.'cfg(unix)'.dependencies]
|
|
||||||
termios = { version = "0.3.3" }
|
|
||||||
|
|
||||||
#####################################
|
|
||||||
# Debian package build instructions #
|
|
||||||
#####################################
|
|
||||||
[package.metadata.deb]
|
|
||||||
assets = [
|
|
||||||
{ source = "target/release/adb_cli", dest = "usr/bin/", mode = "755" },
|
|
||||||
]
|
|
||||||
priority = "optional"
|
|
||||||
section = "utility"
|
|
||||||
|
|
||||||
##################################
|
|
||||||
# RPM package build instructions #
|
|
||||||
##################################
|
|
||||||
[package.metadata.generate-rpm]
|
|
||||||
assets = [
|
|
||||||
{ source = "target/release/adb_cli", dest = "/usr/bin/adb_cli", mode = "755" },
|
|
||||||
]
|
|
||||||
license = "MIT"
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
# `adb_cli`
|
# adb_cli
|
||||||
|
|
||||||
[](./LICENSE-MIT)
|
[](./LICENSE-MIT)
|
||||||

|

|
||||||

|
|
||||||
|
|
||||||
Rust binary providing an improved version of `adb` CLI.
|
Rust binary providing an improved version of `adb` CLI.
|
||||||
|
|
||||||
@@ -11,58 +10,42 @@ Rust binary providing an improved version of `adb` CLI.
|
|||||||
This crate provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
|
This crate provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
cargo install adb_cli
|
cargo install adb_cli
|
||||||
```
|
```
|
||||||
|
|
||||||
Usage is quite simple, and tends to look like `adb`:
|
Usage is quite simple, and tends to look like `adb`:
|
||||||
|
|
||||||
- To use ADB server as a proxy:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
user@laptop ~/adb_client (main)> adb_cli local --help
|
user@laptop ~/adb_client (main)> adb_cli --help
|
||||||
Device related commands using server
|
Rust ADB (Android Debug Bridge) CLI
|
||||||
|
|
||||||
Usage: adb_cli local [OPTIONS] <COMMAND>
|
Usage: adb_cli [OPTIONS] <COMMAND>
|
||||||
|
|
||||||
Commands:
|
Commands:
|
||||||
shell Spawn an interactive shell or run a list of commands on the device
|
|
||||||
pull Pull a file from device
|
|
||||||
push Push a file on device
|
|
||||||
stat Stat a file on device
|
|
||||||
run Run an activity on device specified by the intent
|
|
||||||
reboot Reboot the device
|
|
||||||
install Install an APK on device
|
|
||||||
framebuffer Dump framebuffer of device
|
|
||||||
host-features List available server features
|
host-features List available server features
|
||||||
|
push Push a file on device
|
||||||
|
pull Pull a file from device
|
||||||
list List a directory on device
|
list List a directory on device
|
||||||
|
stat Stat a file specified on device
|
||||||
|
shell Spawn an interactive shell or run a list of commands on the device
|
||||||
|
reboot Reboot the device
|
||||||
|
framebuffer Dump framebuffer of device
|
||||||
logcat Get logs of device
|
logcat Get logs of device
|
||||||
|
version Print current ADB version
|
||||||
|
kill Ask ADB server to quit immediately
|
||||||
|
devices List connected devices
|
||||||
|
track-devices Track new devices showing up
|
||||||
|
pair Pair device with a given code
|
||||||
|
connect Connect device over WI-FI
|
||||||
|
disconnect Disconnect device over WI-FI
|
||||||
|
sms Send a SMS with given phone number and given content
|
||||||
|
rotate Rotate device screen from 90°
|
||||||
help Print this message or the help of the given subcommand(s)
|
help Print this message or the help of the given subcommand(s)
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
|
-d, --debug
|
||||||
-a, --address <ADDRESS> [default: 127.0.0.1:5037]
|
-a, --address <ADDRESS> [default: 127.0.0.1:5037]
|
||||||
-s, --serial <SERIAL> Serial id of a specific device. Every request will be sent to this device
|
-s, --serial <SERIAL> Serial id of a specific device. Every request will be sent to this device
|
||||||
-h, --help Print help
|
-h, --help Print help
|
||||||
```
|
-V, --version Print version
|
||||||
|
|
||||||
- To interact directly with end devices
|
|
||||||
|
|
||||||
```bash
|
|
||||||
user@laptop ~/adb_client (main)> adb_cli usb --help
|
|
||||||
Device commands via USB, no server needed
|
|
||||||
|
|
||||||
Usage: adb_cli usb [OPTIONS] --vendor-id <VID> --product-id <PID> <COMMAND>
|
|
||||||
|
|
||||||
Commands:
|
|
||||||
shell Spawn an interactive shell or run a list of commands on the device
|
|
||||||
pull Pull a file from device
|
|
||||||
push Push a file on device
|
|
||||||
stat Stat a file on device
|
|
||||||
reboot Reboot the device
|
|
||||||
help Print this message or the help of the given subcommand(s)
|
|
||||||
|
|
||||||
Options:
|
|
||||||
-v, --vendor-id <VID> Hexadecimal vendor id of this USB device
|
|
||||||
-p, --product-id <PID> Hexadecimal product id of this USB device
|
|
||||||
-k, --private-key <PATH_TO_PRIVATE_KEY> Path to a custom private key to use for authentication
|
|
||||||
-h, --help Print help
|
|
||||||
```
|
```
|
||||||
|
|||||||
12
adb_cli/src/commands/emu.rs
Normal file
12
adb_cli/src/commands/emu.rs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub enum EmuCommand {
|
||||||
|
/// Send a SMS with given phone number and given content
|
||||||
|
Sms {
|
||||||
|
phone_number: String,
|
||||||
|
content: String,
|
||||||
|
},
|
||||||
|
/// Rotate device screen from 90°
|
||||||
|
Rotate,
|
||||||
|
}
|
||||||
24
adb_cli/src/commands/host.rs
Normal file
24
adb_cli/src/commands/host.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
use std::net::SocketAddrV4;
|
||||||
|
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub enum HostCommand {
|
||||||
|
/// Print current ADB version.
|
||||||
|
Version,
|
||||||
|
/// Ask ADB server to quit immediately.
|
||||||
|
Kill,
|
||||||
|
/// List connected devices.
|
||||||
|
Devices {
|
||||||
|
#[clap(short = 'l', long = "long")]
|
||||||
|
long: bool,
|
||||||
|
},
|
||||||
|
/// Track new devices showing up.
|
||||||
|
TrackDevices,
|
||||||
|
/// Pair device with a given code
|
||||||
|
Pair { address: SocketAddrV4, code: u32 },
|
||||||
|
/// Connect device over WI-FI
|
||||||
|
Connect { address: SocketAddrV4 },
|
||||||
|
/// Disconnect device over WI-FI
|
||||||
|
Disconnect { address: SocketAddrV4 },
|
||||||
|
}
|
||||||
31
adb_cli/src/commands/local.rs
Normal file
31
adb_cli/src/commands/local.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
use crate::models::RebootTypeCommand;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub enum LocalCommand {
|
||||||
|
/// List available server features.
|
||||||
|
HostFeatures,
|
||||||
|
/// Push a file on device
|
||||||
|
Push { filename: String, path: String },
|
||||||
|
/// Pull a file from device
|
||||||
|
Pull { path: String, filename: String },
|
||||||
|
/// List a directory on device
|
||||||
|
List { path: String },
|
||||||
|
/// Stat a file specified on device
|
||||||
|
Stat { path: String },
|
||||||
|
/// Spawn an interactive shell or run a list of commands on the device
|
||||||
|
Shell { command: Vec<String> },
|
||||||
|
/// Reboot the device
|
||||||
|
Reboot {
|
||||||
|
#[clap(subcommand)]
|
||||||
|
sub_command: RebootTypeCommand,
|
||||||
|
},
|
||||||
|
/// Dump framebuffer of device
|
||||||
|
Framebuffer { path: String },
|
||||||
|
/// Get logs of device
|
||||||
|
Logcat {
|
||||||
|
/// Path to output file (created if not exists)
|
||||||
|
path: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
7
adb_cli/src/commands/mod.rs
Normal file
7
adb_cli/src/commands/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
mod emu;
|
||||||
|
mod host;
|
||||||
|
mod local;
|
||||||
|
|
||||||
|
pub use emu::EmuCommand;
|
||||||
|
pub use host::HostCommand;
|
||||||
|
pub use local::LocalCommand;
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
use adb_client::ADBEmulatorDevice;
|
|
||||||
|
|
||||||
use crate::models::{ADBCliResult, EmuCommand, EmulatorCommand};
|
|
||||||
|
|
||||||
pub fn handle_emulator_commands(emulator_command: EmulatorCommand) -> ADBCliResult<()> {
|
|
||||||
let mut emulator = ADBEmulatorDevice::new(emulator_command.serial, None)?;
|
|
||||||
|
|
||||||
match emulator_command.command {
|
|
||||||
EmuCommand::Sms {
|
|
||||||
phone_number,
|
|
||||||
content,
|
|
||||||
} => {
|
|
||||||
emulator.send_sms(&phone_number, &content)?;
|
|
||||||
log::info!("SMS sent to {phone_number}");
|
|
||||||
}
|
|
||||||
EmuCommand::Rotate => emulator.rotate()?,
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
use adb_client::{ADBServer, DeviceShort, MDNSBackend, Result, WaitForDeviceState};
|
|
||||||
|
|
||||||
use crate::models::{HostCommand, MdnsCommand, ServerCommand};
|
|
||||||
|
|
||||||
pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Result<()> {
|
|
||||||
let mut adb_server = ADBServer::new(server_command.address);
|
|
||||||
|
|
||||||
match server_command.command {
|
|
||||||
HostCommand::Version => {
|
|
||||||
let version = adb_server.version()?;
|
|
||||||
log::info!("Android Debug Bridge version {version}");
|
|
||||||
log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
|
|
||||||
}
|
|
||||||
HostCommand::Kill => {
|
|
||||||
adb_server.kill()?;
|
|
||||||
}
|
|
||||||
HostCommand::Devices { long } => {
|
|
||||||
if long {
|
|
||||||
log::info!("List of devices attached (extended)");
|
|
||||||
for device in adb_server.devices_long()? {
|
|
||||||
log::info!("{device}");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log::info!("List of devices attached");
|
|
||||||
for device in adb_server.devices()? {
|
|
||||||
log::info!("{device}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
HostCommand::TrackDevices => {
|
|
||||||
let callback = |device: DeviceShort| {
|
|
||||||
log::info!("{device}");
|
|
||||||
Ok(())
|
|
||||||
};
|
|
||||||
log::info!("Live list of devices attached");
|
|
||||||
adb_server.track_devices(callback)?;
|
|
||||||
}
|
|
||||||
HostCommand::Pair { address, code } => {
|
|
||||||
adb_server.pair(address, code)?;
|
|
||||||
log::info!("Paired device {address}");
|
|
||||||
}
|
|
||||||
HostCommand::Connect { address } => {
|
|
||||||
adb_server.connect_device(address)?;
|
|
||||||
log::info!("Connected to {address}");
|
|
||||||
}
|
|
||||||
HostCommand::Disconnect { address } => {
|
|
||||||
adb_server.disconnect_device(address)?;
|
|
||||||
log::info!("Disconnected {address}");
|
|
||||||
}
|
|
||||||
HostCommand::Mdns { subcommand } => match subcommand {
|
|
||||||
MdnsCommand::Check => {
|
|
||||||
let check = adb_server.mdns_check()?;
|
|
||||||
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::OpenScreen => {
|
|
||||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MdnsCommand::Services => {
|
|
||||||
log::info!("List of discovered mdns services");
|
|
||||||
for service in adb_server.mdns_services()? {
|
|
||||||
log::info!("{service}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
HostCommand::ServerStatus => {
|
|
||||||
log::info!("{}", adb_server.server_status()?);
|
|
||||||
}
|
|
||||||
HostCommand::WaitForDevice { transport } => {
|
|
||||||
log::info!("waiting for device to be connected...");
|
|
||||||
adb_server.wait_for_device(WaitForDeviceState::Device, transport)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
use std::{fs::File, io::Write};
|
|
||||||
|
|
||||||
use crate::ADBCliResult;
|
|
||||||
use crate::models::LocalDeviceCommand;
|
|
||||||
use adb_client::ADBServerDevice;
|
|
||||||
|
|
||||||
pub fn handle_local_commands(
|
|
||||||
mut device: ADBServerDevice,
|
|
||||||
local_device_commands: LocalDeviceCommand,
|
|
||||||
) -> ADBCliResult<()> {
|
|
||||||
match local_device_commands {
|
|
||||||
LocalDeviceCommand::HostFeatures => {
|
|
||||||
let features = device
|
|
||||||
.host_features()?
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.reduce(|a, b| format!("{a},{b}"))
|
|
||||||
.unwrap_or_default();
|
|
||||||
log::info!("Available host features: {features}");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
LocalDeviceCommand::Logcat { path } => {
|
|
||||||
let writer: Box<dyn Write> = if let Some(path) = path {
|
|
||||||
let f = File::create(path)?;
|
|
||||||
Box::new(f)
|
|
||||||
} else {
|
|
||||||
Box::new(std::io::stdout())
|
|
||||||
};
|
|
||||||
Ok(device.get_logs(writer)?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
mod emulator_commands;
|
|
||||||
mod host_commands;
|
|
||||||
mod local_commands;
|
|
||||||
|
|
||||||
pub use emulator_commands::handle_emulator_commands;
|
|
||||||
pub use host_commands::handle_host_commands;
|
|
||||||
pub use local_commands::handle_local_commands;
|
|
||||||
@@ -1,201 +1,156 @@
|
|||||||
#![doc = include_str!("../README.md")]
|
mod commands;
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
|
||||||
mod adb_termios;
|
|
||||||
|
|
||||||
mod handlers;
|
|
||||||
mod models;
|
mod models;
|
||||||
mod utils;
|
|
||||||
|
|
||||||
use adb_client::{
|
|
||||||
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
|
|
||||||
mdns::MDNSDiscoveryService,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
|
||||||
use adb_termios::ADBTermios;
|
|
||||||
|
|
||||||
|
use adb_client::{ADBEmulatorDevice, ADBServer, DeviceShort};
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
|
use commands::{EmuCommand, HostCommand, LocalCommand};
|
||||||
use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
|
use env_logger::Builder;
|
||||||
use std::collections::HashMap;
|
use log::LevelFilter;
|
||||||
|
use models::{Command, Opts};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::process::ExitCode;
|
|
||||||
use utils::setup_logger;
|
|
||||||
|
|
||||||
use crate::models::{ADBCliError, ADBCliResult};
|
fn main() -> Result<()> {
|
||||||
|
let opt = Opts::parse();
|
||||||
|
|
||||||
fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> ADBCliResult<()> {
|
let max_level = if opt.verbose {
|
||||||
match command {
|
LevelFilter::Trace
|
||||||
DeviceCommands::Shell { commands } => {
|
} else {
|
||||||
if commands.is_empty() {
|
LevelFilter::Info
|
||||||
// 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<()> {
|
|
||||||
// This depends on `clap`
|
|
||||||
let opts = Opts::parse();
|
|
||||||
|
|
||||||
setup_logger(opts.debug);
|
|
||||||
|
|
||||||
// Directly handling methods / commands that aren't linked to [`ADBDeviceExt`] trait.
|
|
||||||
// Other methods just have to create a concrete [`ADBDeviceExt`] instance, and return it.
|
|
||||||
// This instance will then be used to execute desired command.
|
|
||||||
let (device, commands) = match opts.command {
|
|
||||||
MainCommand::Host(server_command) => return Ok(handle_host_commands(server_command)?),
|
|
||||||
MainCommand::Emu(emulator_command) => return handle_emulator_commands(emulator_command),
|
|
||||||
MainCommand::Local(server_command) => {
|
|
||||||
// Must start server to communicate with device, but only if this is a local one.
|
|
||||||
let server_address_ip = server_command.address.ip();
|
|
||||||
if server_address_ip.is_loopback() || server_address_ip.is_unspecified() {
|
|
||||||
ADBServer::start(&HashMap::default(), &None);
|
|
||||||
}
|
|
||||||
|
|
||||||
let device = match server_command.serial {
|
|
||||||
Some(serial) => ADBServerDevice::new(serial, Some(server_command.address)),
|
|
||||||
None => ADBServerDevice::autodetect(Some(server_command.address)),
|
|
||||||
};
|
|
||||||
|
|
||||||
match server_command.command {
|
|
||||||
LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
|
|
||||||
LocalCommand::LocalDeviceCommand(local_device_command) => {
|
|
||||||
return handle_local_commands(device, local_device_command);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MainCommand::Usb(usb_command) => {
|
|
||||||
let device = match (usb_command.vendor_id, usb_command.product_id) {
|
|
||||||
(Some(vid), Some(pid)) => match usb_command.path_to_private_key {
|
|
||||||
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
|
|
||||||
None => ADBUSBDevice::new(vid, pid)?,
|
|
||||||
},
|
|
||||||
(None, None) => match usb_command.path_to_private_key {
|
|
||||||
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
|
|
||||||
None => ADBUSBDevice::autodetect()?,
|
|
||||||
},
|
|
||||||
_ => {
|
|
||||||
return Err(ADBCliError::Standard(
|
|
||||||
"cannot specify flags --vendor-id without --product-id or vice versa"
|
|
||||||
.into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
(device.boxed(), usb_command.commands)
|
|
||||||
}
|
|
||||||
MainCommand::Tcp(tcp_command) => {
|
|
||||||
let device = match tcp_command.path_to_private_key {
|
|
||||||
Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
|
|
||||||
None => ADBTcpDevice::new(tcp_command.address)?,
|
|
||||||
};
|
|
||||||
(device.boxed(), tcp_command.commands)
|
|
||||||
}
|
|
||||||
MainCommand::Mdns => {
|
|
||||||
let mut service = MDNSDiscoveryService::new()?;
|
|
||||||
|
|
||||||
let (tx, rx) = std::sync::mpsc::channel();
|
|
||||||
service.start(tx)?;
|
|
||||||
|
|
||||||
log::info!("Starting mdns discovery...");
|
|
||||||
while let Ok(device) = rx.recv() {
|
|
||||||
log::info!(
|
|
||||||
"Found device fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
|
|
||||||
device.fullname,
|
|
||||||
device.ipv4_addresses(),
|
|
||||||
device.ipv6_addresses()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(service.shutdown()?);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
let mut builder = Builder::default();
|
||||||
|
builder.filter_level(max_level);
|
||||||
|
builder.init();
|
||||||
|
|
||||||
run_command(device, commands)?;
|
match opt.command {
|
||||||
|
Command::Local(local) => {
|
||||||
|
let mut adb_server = ADBServer::new(opt.address);
|
||||||
|
|
||||||
|
let mut device = match opt.serial {
|
||||||
|
Some(serial) => adb_server.get_device_by_name(&serial)?,
|
||||||
|
None => adb_server.get_device()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
match local {
|
||||||
|
LocalCommand::Pull { path, filename } => {
|
||||||
|
let mut output = File::create(Path::new(&filename))?;
|
||||||
|
device.recv(&path, &mut output)?;
|
||||||
|
log::info!("Downloaded {path} as {filename}");
|
||||||
|
}
|
||||||
|
LocalCommand::Push { filename, path } => {
|
||||||
|
let mut input = File::open(Path::new(&filename))?;
|
||||||
|
device.send(&mut input, &path)?;
|
||||||
|
log::info!("Uploaded {filename} to {path}");
|
||||||
|
}
|
||||||
|
LocalCommand::List { path } => {
|
||||||
|
device.list(path)?;
|
||||||
|
}
|
||||||
|
LocalCommand::Stat { path } => {
|
||||||
|
let stat_response = device.stat(path)?;
|
||||||
|
log::info!("{}", stat_response);
|
||||||
|
}
|
||||||
|
LocalCommand::Shell { command } => {
|
||||||
|
if command.is_empty() {
|
||||||
|
device.shell()?;
|
||||||
|
} else {
|
||||||
|
device.shell_command(command, std::io::stdout())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LocalCommand::HostFeatures => {
|
||||||
|
let features = device
|
||||||
|
.host_features()?
|
||||||
|
.iter()
|
||||||
|
.map(|v| v.to_string())
|
||||||
|
.reduce(|a, b| format!("{a},{b}"))
|
||||||
|
.ok_or(anyhow!("cannot list features"))?;
|
||||||
|
log::info!("Available host features: {features}");
|
||||||
|
}
|
||||||
|
LocalCommand::Reboot { sub_command } => {
|
||||||
|
log::info!("Reboots device");
|
||||||
|
device.reboot(sub_command.into())?
|
||||||
|
}
|
||||||
|
LocalCommand::Framebuffer { path } => {
|
||||||
|
device.framebuffer(&path)?;
|
||||||
|
log::info!("Framebuffer dropped: {path}");
|
||||||
|
}
|
||||||
|
LocalCommand::Logcat { path } => {
|
||||||
|
let writer: Box<dyn Write> = if let Some(path) = path {
|
||||||
|
let f = File::create(path)?;
|
||||||
|
Box::new(f)
|
||||||
|
} else {
|
||||||
|
Box::new(std::io::stdout())
|
||||||
|
};
|
||||||
|
device.get_logs(writer)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Host(host) => {
|
||||||
|
let mut adb_server = ADBServer::new(opt.address);
|
||||||
|
|
||||||
|
match host {
|
||||||
|
HostCommand::Version => {
|
||||||
|
let version = adb_server.version()?;
|
||||||
|
log::info!("Android Debug Bridge version {}", version);
|
||||||
|
log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
|
||||||
|
}
|
||||||
|
HostCommand::Kill => {
|
||||||
|
adb_server.kill()?;
|
||||||
|
}
|
||||||
|
HostCommand::Devices { long } => {
|
||||||
|
if long {
|
||||||
|
log::info!("List of devices attached (extended)");
|
||||||
|
for device in adb_server.devices_long()? {
|
||||||
|
log::info!("{}", device);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log::info!("List of devices attached");
|
||||||
|
for device in adb_server.devices()? {
|
||||||
|
log::info!("{}", device);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HostCommand::TrackDevices => {
|
||||||
|
let callback = |device: DeviceShort| {
|
||||||
|
log::info!("{}", device);
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
log::info!("Live list of devices attached");
|
||||||
|
adb_server.track_devices(callback)?;
|
||||||
|
}
|
||||||
|
HostCommand::Pair { address, code } => {
|
||||||
|
adb_server.pair(address, code)?;
|
||||||
|
log::info!("Paired device {address}");
|
||||||
|
}
|
||||||
|
HostCommand::Connect { address } => {
|
||||||
|
adb_server.connect_device(address)?;
|
||||||
|
log::info!("Connected to {address}");
|
||||||
|
}
|
||||||
|
HostCommand::Disconnect { address } => {
|
||||||
|
adb_server.disconnect_device(address)?;
|
||||||
|
log::info!("Disconnected {address}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Emu(emu) => {
|
||||||
|
let mut emulator = match opt.serial {
|
||||||
|
Some(serial) => ADBEmulatorDevice::new(serial, None)?,
|
||||||
|
None => return Err(anyhow!("Serial must be set to use emulators !")),
|
||||||
|
};
|
||||||
|
|
||||||
|
match emu {
|
||||||
|
EmuCommand::Sms {
|
||||||
|
phone_number,
|
||||||
|
content,
|
||||||
|
} => {
|
||||||
|
emulator.send_sms(&phone_number, &content)?;
|
||||||
|
log::info!("SMS sent to {phone_number}");
|
||||||
|
}
|
||||||
|
EmuCommand::Rotate => emulator.rotate()?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
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),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use clap::Parser;
|
|
||||||
|
|
||||||
use super::RebootTypeCommand;
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub enum DeviceCommands {
|
|
||||||
/// Spawn an interactive shell or run a list of commands on the device
|
|
||||||
Shell { commands: Vec<String> },
|
|
||||||
/// Pull a file from device
|
|
||||||
Pull { source: String, destination: String },
|
|
||||||
/// Push a file on device
|
|
||||||
Push { filename: String, path: String },
|
|
||||||
/// Stat a file on device
|
|
||||||
Stat { path: String },
|
|
||||||
/// Run an activity on device specified by the intent
|
|
||||||
Run {
|
|
||||||
/// 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`
|
|
||||||
#[clap(short = 'a', long = "activity")]
|
|
||||||
activity: String,
|
|
||||||
},
|
|
||||||
/// Reboot the device
|
|
||||||
Reboot {
|
|
||||||
#[clap(subcommand)]
|
|
||||||
reboot_type: RebootTypeCommand,
|
|
||||||
},
|
|
||||||
/// Install an APK on device
|
|
||||||
Install {
|
|
||||||
/// Path to APK file. Extension must be ".apk"
|
|
||||||
path: PathBuf,
|
|
||||||
},
|
|
||||||
/// Uninstall a package from the device
|
|
||||||
Uninstall {
|
|
||||||
/// Name of the package to uninstall
|
|
||||||
package: String,
|
|
||||||
},
|
|
||||||
/// Dump framebuffer of device
|
|
||||||
Framebuffer {
|
|
||||||
/// Framebuffer image destination path
|
|
||||||
path: String,
|
|
||||||
},
|
|
||||||
/// List files on device
|
|
||||||
List {
|
|
||||||
/// Path to list files from
|
|
||||||
path: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
use clap::{Parser, Subcommand};
|
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
|
||||||
pub struct EmulatorCommand {
|
|
||||||
#[clap(short = 's', long = "serial")]
|
|
||||||
pub serial: String,
|
|
||||||
#[clap(subcommand)]
|
|
||||||
pub command: EmuCommand,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Subcommand)]
|
|
||||||
pub enum EmuCommand {
|
|
||||||
/// Send a SMS with given phone number and given content
|
|
||||||
Sms {
|
|
||||||
phone_number: String,
|
|
||||||
content: String,
|
|
||||||
},
|
|
||||||
/// Rotate device screen from 90°
|
|
||||||
Rotate,
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
use std::{net::SocketAddrV4, str::FromStr};
|
|
||||||
|
|
||||||
use adb_client::{RustADBError, WaitForDeviceTransport};
|
|
||||||
use clap::Parser;
|
|
||||||
|
|
||||||
fn parse_wait_for_device_device_transport(
|
|
||||||
value: &str,
|
|
||||||
) -> Result<WaitForDeviceTransport, RustADBError> {
|
|
||||||
WaitForDeviceTransport::from_str(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub enum HostCommand {
|
|
||||||
/// Print current ADB version.
|
|
||||||
Version,
|
|
||||||
/// Ask ADB server to quit immediately.
|
|
||||||
Kill,
|
|
||||||
/// List connected devices.
|
|
||||||
Devices {
|
|
||||||
#[clap(short = 'l', long = "long")]
|
|
||||||
long: bool,
|
|
||||||
},
|
|
||||||
/// Track new devices showing up.
|
|
||||||
TrackDevices,
|
|
||||||
/// Pair device with a given code
|
|
||||||
Pair { address: SocketAddrV4, code: String },
|
|
||||||
/// Connect device over WI-FI
|
|
||||||
Connect { address: SocketAddrV4 },
|
|
||||||
/// Disconnect device over WI-FI
|
|
||||||
Disconnect { address: SocketAddrV4 },
|
|
||||||
/// MDNS services
|
|
||||||
Mdns {
|
|
||||||
#[clap(subcommand)]
|
|
||||||
subcommand: MdnsCommand,
|
|
||||||
},
|
|
||||||
/// Display server status
|
|
||||||
ServerStatus,
|
|
||||||
/// Wait for a device, on optionally given transport
|
|
||||||
WaitForDevice {
|
|
||||||
/// Transport on which wait for devices
|
|
||||||
#[clap(short = 't', long = "transport", value_parser = parse_wait_for_device_device_transport)]
|
|
||||||
transport: Option<WaitForDeviceTransport>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub enum MdnsCommand {
|
|
||||||
/// Check mdns status
|
|
||||||
Check,
|
|
||||||
/// List mdns services available
|
|
||||||
Services,
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
use clap::Parser;
|
|
||||||
|
|
||||||
use super::DeviceCommands;
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub enum LocalCommand {
|
|
||||||
#[clap(flatten)]
|
|
||||||
DeviceCommands(DeviceCommands),
|
|
||||||
#[clap(flatten)]
|
|
||||||
LocalDeviceCommand(LocalDeviceCommand),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub enum LocalDeviceCommand {
|
|
||||||
/// List available server features.
|
|
||||||
HostFeatures,
|
|
||||||
/// Get logs of device
|
|
||||||
Logcat {
|
|
||||||
/// Path to output file (created if not exists)
|
|
||||||
path: Option<String>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,5 @@
|
|||||||
mod adb_cli_error;
|
|
||||||
mod device;
|
|
||||||
mod emu;
|
|
||||||
mod host;
|
|
||||||
mod local;
|
|
||||||
mod opts;
|
mod opts;
|
||||||
mod reboot_type;
|
mod reboot_type;
|
||||||
mod tcp;
|
|
||||||
mod usb;
|
|
||||||
|
|
||||||
pub use adb_cli_error::{ADBCliError, ADBCliResult};
|
pub use opts::{Command, Opts};
|
||||||
pub use device::DeviceCommands;
|
|
||||||
pub use emu::{EmuCommand, EmulatorCommand};
|
|
||||||
pub use host::{HostCommand, MdnsCommand};
|
|
||||||
pub use local::{LocalCommand, LocalDeviceCommand};
|
|
||||||
pub use opts::{MainCommand, Opts, ServerCommand};
|
|
||||||
pub use reboot_type::RebootTypeCommand;
|
pub use reboot_type::RebootTypeCommand;
|
||||||
pub use tcp::TcpCommand;
|
|
||||||
pub use usb::UsbCommand;
|
|
||||||
|
|||||||
@@ -1,41 +1,29 @@
|
|||||||
use std::net::SocketAddrV4;
|
use std::net::SocketAddrV4;
|
||||||
|
|
||||||
use clap::{Parser, Subcommand};
|
use clap::Parser;
|
||||||
|
|
||||||
use super::{EmulatorCommand, HostCommand, LocalCommand, TcpCommand, UsbCommand};
|
use crate::commands::{EmuCommand, HostCommand, LocalCommand};
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
#[derive(Parser, Debug)]
|
||||||
#[clap(about, version, author)]
|
#[clap(about, version, author)]
|
||||||
pub struct Opts {
|
pub struct Opts {
|
||||||
#[clap(long = "debug")]
|
#[clap(short = 'v', long = "verbose")]
|
||||||
pub debug: bool,
|
pub verbose: bool,
|
||||||
#[clap(subcommand)]
|
|
||||||
pub command: MainCommand,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
|
||||||
pub enum MainCommand {
|
|
||||||
/// Server related commands
|
|
||||||
Host(ServerCommand<HostCommand>),
|
|
||||||
/// Device related commands using server
|
|
||||||
Local(ServerCommand<LocalCommand>),
|
|
||||||
/// Emulator related commands
|
|
||||||
Emu(EmulatorCommand),
|
|
||||||
/// USB device related commands
|
|
||||||
Usb(UsbCommand),
|
|
||||||
/// TCP device related commands
|
|
||||||
Tcp(TcpCommand),
|
|
||||||
/// MDNS discovery related commands
|
|
||||||
Mdns,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Parser)]
|
|
||||||
pub struct ServerCommand<T: Subcommand> {
|
|
||||||
#[clap(short = 'a', long = "address", default_value = "127.0.0.1:5037")]
|
#[clap(short = 'a', long = "address", default_value = "127.0.0.1:5037")]
|
||||||
pub address: SocketAddrV4,
|
pub address: SocketAddrV4,
|
||||||
/// Serial id of a specific device. Every request will be sent to this device.
|
/// Serial id of a specific device. Every request will be sent to this device.
|
||||||
#[clap(short = 's', long = "serial")]
|
#[clap(short = 's', long = "serial")]
|
||||||
pub serial: Option<String>,
|
pub serial: Option<String>,
|
||||||
#[clap(subcommand)]
|
#[clap(subcommand)]
|
||||||
pub command: T,
|
pub command: Command,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub enum Command {
|
||||||
|
#[clap(flatten)]
|
||||||
|
Local(LocalCommand),
|
||||||
|
#[clap(flatten)]
|
||||||
|
Host(HostCommand),
|
||||||
|
#[clap(flatten)]
|
||||||
|
Emu(EmuCommand),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ pub enum RebootTypeCommand {
|
|||||||
Recovery,
|
Recovery,
|
||||||
Sideload,
|
Sideload,
|
||||||
SideloadAutoReboot,
|
SideloadAutoReboot,
|
||||||
Fastboot,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<RebootTypeCommand> for RebootType {
|
impl From<RebootTypeCommand> for RebootType {
|
||||||
@@ -19,7 +18,6 @@ impl From<RebootTypeCommand> for RebootType {
|
|||||||
RebootTypeCommand::Recovery => RebootType::Recovery,
|
RebootTypeCommand::Recovery => RebootType::Recovery,
|
||||||
RebootTypeCommand::Sideload => RebootType::Sideload,
|
RebootTypeCommand::Sideload => RebootType::Sideload,
|
||||||
RebootTypeCommand::SideloadAutoReboot => RebootType::SideloadAutoReboot,
|
RebootTypeCommand::SideloadAutoReboot => RebootType::SideloadAutoReboot,
|
||||||
RebootTypeCommand::Fastboot => RebootType::Fastboot,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
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,25 +0,0 @@
|
|||||||
use std::num::ParseIntError;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use clap::Parser;
|
|
||||||
|
|
||||||
use super::DeviceCommands;
|
|
||||||
|
|
||||||
fn parse_hex_id(id: &str) -> Result<u16, ParseIntError> {
|
|
||||||
u16::from_str_radix(id, 16)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
|
||||||
pub struct UsbCommand {
|
|
||||||
/// Hexadecimal vendor id of this USB device
|
|
||||||
#[clap(short = 'v', long = "vendor-id", value_parser=parse_hex_id, value_name="VID")]
|
|
||||||
pub vendor_id: Option<u16>,
|
|
||||||
/// Hexadecimal product id of this USB device
|
|
||||||
#[clap(short = 'p', long = "product-id", value_parser=parse_hex_id, value_name="PID")]
|
|
||||||
pub product_id: Option<u16>,
|
|
||||||
/// 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 +0,0 @@
|
|||||||
use env_logger::{Builder, Env};
|
|
||||||
|
|
||||||
/// 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();
|
|
||||||
}
|
|
||||||
@@ -1,57 +1,21 @@
|
|||||||
[package]
|
[package]
|
||||||
authors.workspace = true
|
|
||||||
description = "Rust ADB (Android Debug Bridge) client library"
|
description = "Rust ADB (Android Debug Bridge) client library"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
keywords.workspace = true
|
keywords = ["adb", "android"]
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
name = "adb_client"
|
name = "adb_client"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
rust-version.workspace = true
|
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
|
||||||
all-features = true
|
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
|
||||||
|
|
||||||
[features]
|
|
||||||
default = []
|
|
||||||
mdns = ["dep:mdns-sd"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
base64 = { version = "0.22.1" }
|
|
||||||
bincode = { version = "2.0.1", features = ["serde"] }
|
|
||||||
byteorder = { version = "1.5.0" }
|
byteorder = { version = "1.5.0" }
|
||||||
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
|
chrono = { version = "0.4.38" }
|
||||||
image = { version = "0.25.9", default-features = false, features = ["png"] }
|
homedir = "0.3.3"
|
||||||
log = { version = "0.4.29" }
|
image = { version = "0.25.2" }
|
||||||
num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
|
lazy_static = { version = "1.5.0" }
|
||||||
num-traits = { version = "0.2.19" }
|
log = "0.4.22"
|
||||||
quick-protobuf = { version = "0.8.1" }
|
mio = { version = "1.0.2", features = ["os-ext", "os-poll"] }
|
||||||
rand = { version = "0.9.2" }
|
regex = { version = "1.10.6", features = ["perf", "std", "unicode"] }
|
||||||
rcgen = { version = "0.14.6" }
|
termios = { version = "0.3.3" }
|
||||||
regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
|
thiserror = { version = "1.0.63" }
|
||||||
rsa = { version = "0.9.9" }
|
|
||||||
rusb = { version = "0.9.4", features = ["vendored"] }
|
|
||||||
rustls = { version = "0.23.35" }
|
|
||||||
rustls-pki-types = { version = "1.13.2" }
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
serde_repr = { version = "0.1.20" }
|
|
||||||
sha1 = { version = "0.10.6", features = ["oid"] }
|
|
||||||
thiserror = { version = "2.0.17" }
|
|
||||||
|
|
||||||
#########
|
|
||||||
# `mdns` feature-specific dependencies
|
|
||||||
mdns-sd = { version = "0.17.1", default-features = false, features = [
|
|
||||||
"logging",
|
|
||||||
], optional = true }
|
|
||||||
#########
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
anyhow = { version = "1.0.100" }
|
|
||||||
criterion = { version = "0.7.0" } # Used for benchmarks
|
|
||||||
|
|
||||||
[[bench]]
|
|
||||||
harness = false
|
|
||||||
name = "benchmark_adb_push"
|
|
||||||
path = "../benches/benchmark_adb_push.rs"
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
# `adb_client`
|
# adb_client
|
||||||
|
|
||||||
[](./LICENSE-MIT)
|
[](./LICENSE-MIT)
|
||||||
[](https://docs.rs/adb_client)
|
[](https://docs.rs/adb_client)
|
||||||
[](https://crates.io/crates/adb_client)
|

|
||||||

|
|
||||||
|
|
||||||
Rust library implementing ADB protocol.
|
Rust library implementing ADB protocol.
|
||||||
|
|
||||||
@@ -16,38 +15,21 @@ Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
|
|||||||
adb_client = "*"
|
adb_client = "*"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Crate features
|
|
||||||
|
|
||||||
| Feature | Description | Default? |
|
|
||||||
| :-----: | :---------------------------------------------: | :------: |
|
|
||||||
| `mdns` | Enables mDNS device discovery on local network. | No |
|
|
||||||
|
|
||||||
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:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
adb_client = { version = "*", default-features = false, features = ["mdns"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Benchmarks
|
|
||||||
|
|
||||||
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
|
|
||||||
|
|
||||||
### `ADBServerDevice` push vs `adb push`
|
|
||||||
|
|
||||||
`ADBServerDevice` performs all operations by using adb server as a bridge.
|
|
||||||
|
|
||||||
| File size | Sample size | `ADBServerDevice` | `adb` | Difference |
|
|
||||||
| :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
|
|
||||||
| 10 MB | 100 | 350,79 ms | 356,30 ms | <div style="color:green">-1,57 %</div> |
|
|
||||||
| 500 MB | 50 | 15,60 s | 15,64 s | <div style="color:green">-0,25 %</div> |
|
|
||||||
| 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |
|
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
|
### Launch a command on device via ADB server
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use adb_client::ADBServer;
|
||||||
|
|
||||||
|
let mut server = ADBServer::default();
|
||||||
|
let mut device = server.get_device().expect("cannot get device");
|
||||||
|
device.shell_command(["df", "-h"]);
|
||||||
|
```
|
||||||
|
|
||||||
### Get available ADB devices
|
### Get available ADB devices
|
||||||
|
|
||||||
```rust no_run
|
```rust
|
||||||
use adb_client::ADBServer;
|
use adb_client::ADBServer;
|
||||||
use std::net::{SocketAddrV4, Ipv4Addr};
|
use std::net::{SocketAddrV4, Ipv4Addr};
|
||||||
|
|
||||||
@@ -59,21 +41,9 @@ let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
|
|||||||
server.devices();
|
server.devices();
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using ADB server as bridge
|
### Push a file to the device
|
||||||
|
|
||||||
#### Launch a command on device
|
```rust
|
||||||
|
|
||||||
```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 adb_client::ADBServer;
|
||||||
use std::net::Ipv4Addr;
|
use std::net::Ipv4Addr;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
@@ -81,45 +51,6 @@ use std::path::Path;
|
|||||||
|
|
||||||
let mut server = ADBServer::default();
|
let mut server = ADBServer::default();
|
||||||
let mut device = server.get_device().expect("cannot get device");
|
let mut device = server.get_device().expect("cannot get device");
|
||||||
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
|
let mut input = File::open(Path::new("/tmp")).unwrap();
|
||||||
device.push(&mut input, "/data/local/tmp");
|
device.send(&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()));
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
use std::io::{Cursor, Read, Write};
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use image::{ImageBuffer, ImageFormat, Rgba};
|
|
||||||
|
|
||||||
use crate::models::AdbStatResponse;
|
|
||||||
use crate::{ADBListItem, RebootType, Result};
|
|
||||||
|
|
||||||
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
|
|
||||||
pub trait ADBDeviceExt {
|
|
||||||
/// Runs command in a shell on the device, and write its output and error streams into output.
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
|
|
||||||
|
|
||||||
/// Starts an interactive shell session on the device.
|
|
||||||
/// Input data is read from reader and write to writer.
|
|
||||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()>;
|
|
||||||
|
|
||||||
/// Display the stat information for a remote file
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;
|
|
||||||
|
|
||||||
/// Pull the remote file pointed to by `source` and write its contents into `output`
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()>;
|
|
||||||
|
|
||||||
/// 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<()>;
|
|
||||||
|
|
||||||
/// Run `activity` from `package` on device. Return the command output.
|
|
||||||
fn run_activity(&mut self, package: &str, activity: &str) -> Result<Vec<u8>> {
|
|
||||||
let mut output = Vec::new();
|
|
||||||
self.shell_command(
|
|
||||||
&["am", "start", &format!("{package}/{package}.{activity}")],
|
|
||||||
&mut output,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(output)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Install an APK pointed to by `apk_path` on device.
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()>;
|
|
||||||
|
|
||||||
/// Uninstall the package `package` from device.
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()>;
|
|
||||||
|
|
||||||
/// 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`.
|
|
||||||
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()?;
|
|
||||||
Ok(img.save(path.as_ref())?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dump framebuffer of this device and return corresponding bytes.
|
|
||||||
///
|
|
||||||
/// Output data format is currently only `PNG`.
|
|
||||||
fn framebuffer_bytes(&mut self) -> Result<Vec<u8>> {
|
|
||||||
let img = self.framebuffer_inner()?;
|
|
||||||
let mut vec = Cursor::new(Vec::new());
|
|
||||||
img.write_to(&mut vec, ImageFormat::Png)?;
|
|
||||||
|
|
||||||
Ok(vec.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Return a boxed instance representing this trait
|
|
||||||
fn boxed(self) -> Box<dyn ADBDeviceExt>
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
Self: 'static,
|
|
||||||
{
|
|
||||||
Box::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "macos"))]
|
|
||||||
|
|
||||||
use std::os::unix::prelude::{AsRawFd, RawFd};
|
use std::os::unix::prelude::{AsRawFd, RawFd};
|
||||||
|
|
||||||
use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
|
use termios::{tcsetattr, Termios, TCSANOW, VMIN, VTIME};
|
||||||
|
|
||||||
use crate::models::{ADBCliError, ADBCliResult};
|
use crate::Result;
|
||||||
|
|
||||||
pub struct ADBTermios {
|
pub struct ADBTermios {
|
||||||
fd: RawFd,
|
fd: RawFd,
|
||||||
@@ -13,7 +11,7 @@ pub struct ADBTermios {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
|
||||||
let old_termios = new_termios; // Saves previous state
|
let old_termios = new_termios; // Saves previous state
|
||||||
new_termios.c_lflag = 0;
|
new_termios.c_lflag = 0;
|
||||||
@@ -27,7 +25,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)?)
|
Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,8 +33,6 @@ impl ADBTermios {
|
|||||||
impl Drop for ADBTermios {
|
impl Drop for ADBTermios {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Custom drop implementation, restores previous termios structure.
|
// Custom drop implementation, restores previous termios structure.
|
||||||
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
|
tcsetattr(self.fd, TCSANOW, &self.old_termios).unwrap();
|
||||||
log::error!("Error while dropping ADBTermios: {e}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,49 +0,0 @@
|
|||||||
use crate::{ADBDeviceExt, ADBMessageTransport, RebootType, Result, models::AdbStatResponse};
|
|
||||||
use std::{
|
|
||||||
io::{Read, Write},
|
|
||||||
path::Path,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::ADBMessageDevice;
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.shell_command(command, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
|
||||||
self.shell(reader, writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
|
||||||
self.stat(remote_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.pull(source, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
|
|
||||||
self.push(stream, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
|
|
||||||
self.reboot(reboot_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
self.install(apk_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()> {
|
|
||||||
self.uninstall(package)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,150 +0,0 @@
|
|||||||
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};
|
|
||||||
|
|
||||||
/// Represent a device reached and available over TCP.
|
|
||||||
#[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)?),
|
|
||||||
};
|
|
||||||
|
|
||||||
device.connect()?;
|
|
||||||
|
|
||||||
Ok(device)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send initial connect
|
|
||||||
pub fn connect(&mut self) -> Result<()> {
|
|
||||||
self.get_transport_mut().connect()?;
|
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
|
||||||
MessageCommand::Cnxn,
|
|
||||||
0x0100_0000,
|
|
||||||
1_048_576,
|
|
||||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
|
||||||
);
|
|
||||||
|
|
||||||
self.get_transport_mut().write_message(message)?;
|
|
||||||
|
|
||||||
let message = self.get_transport_mut().read_message()?;
|
|
||||||
|
|
||||||
// Check if a client is requesting a secure connection and upgrade it if necessary
|
|
||||||
match message.header().command() {
|
|
||||||
MessageCommand::Stls => {
|
|
||||||
self.get_transport_mut()
|
|
||||||
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
|
|
||||||
self.get_transport_mut().upgrade_connection()?;
|
|
||||||
log::debug!("Connection successfully upgraded from TCP to TLS");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
MessageCommand::Cnxn => {
|
|
||||||
log::debug!("Unencrypted connection established");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
MessageCommand::Auth => {
|
|
||||||
log::debug!("Authentication required");
|
|
||||||
self.inner.auth_handshake(message, &self.private_key)
|
|
||||||
}
|
|
||||||
_ => Err(crate::RustADBError::WrongResponseReceived(
|
|
||||||
"Expected CNXN, STLS or AUTH command".to_string(),
|
|
||||||
message.header().command().to_string(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_transport_mut(&mut self) -> &mut TcpTransport {
|
|
||||||
self.inner.get_transport_mut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBDeviceExt for ADBTcpDevice {
|
|
||||||
#[inline]
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.shell_command(command, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
|
||||||
self.inner.shell(reader, writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
|
|
||||||
self.inner.stat(remote_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.pull(source, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
|
|
||||||
self.inner.push(stream, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
|
|
||||||
self.inner.reboot(reboot_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
self.inner.install(apk_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()> {
|
|
||||||
self.inner.uninstall(package)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
|
||||||
self.inner.framebuffer_inner()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
|
||||||
self.inner.list(path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for ADBTcpDevice {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
// Best effort here
|
|
||||||
let _ = self.get_transport_mut().disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
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;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ADBTransportMessage {
|
|
||||||
header: ADBTransportMessageHeader,
|
|
||||||
payload: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
#[repr(C)]
|
|
||||||
pub struct ADBTransportMessageHeader {
|
|
||||||
command: MessageCommand, /* command identifier constant */
|
|
||||||
arg0: u32, /* first argument */
|
|
||||||
arg1: u32, /* second argument */
|
|
||||||
data_length: u32, /* length of payload (0 is allowed) */
|
|
||||||
data_crc32: u32, /* crc32 of data payload */
|
|
||||||
magic: u32, /* command ^ 0xffffffff */
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBTransportMessageHeader {
|
|
||||||
pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: &[u8]) -> Self {
|
|
||||||
Self {
|
|
||||||
command,
|
|
||||||
arg0,
|
|
||||||
arg1,
|
|
||||||
data_length: data.len() as u32,
|
|
||||||
data_crc32: Self::compute_crc32(data),
|
|
||||||
magic: Self::compute_magic(command),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn command(&self) -> MessageCommand {
|
|
||||||
self.command
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn arg0(&self) -> u32 {
|
|
||||||
self.arg0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn arg1(&self) -> u32 {
|
|
||||||
self.arg1
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn data_length(&self) -> u32 {
|
|
||||||
self.data_length
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn data_crc32(&self) -> u32 {
|
|
||||||
self.data_crc32
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
|
|
||||||
data.iter().map(|&x| u32::from(x)).sum()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compute_magic(command: MessageCommand) -> u32 {
|
|
||||||
let command_u32 = command as u32;
|
|
||||||
command_u32 ^ 0xFFFF_FFFF
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_bytes(&self) -> Result<Vec<u8>> {
|
|
||||||
adb_message_device::bincode_serialize_to_vec(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBTransportMessage {
|
|
||||||
pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: &[u8]) -> Self {
|
|
||||||
Self {
|
|
||||||
header: ADBTransportMessageHeader::new(command, arg0, arg1, data),
|
|
||||||
payload: data.to_vec(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_header_and_payload(header: ADBTransportMessageHeader, payload: Vec<u8>) -> Self {
|
|
||||||
Self { header, payload }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn check_message_integrity(&self) -> bool {
|
|
||||||
ADBTransportMessageHeader::compute_magic(self.header.command) == self.header.magic
|
|
||||||
&& ADBTransportMessageHeader::compute_crc32(&self.payload) == self.header.data_crc32
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn assert_command(&self, expected_command: MessageCommand) -> Result<()> {
|
|
||||||
let our_command = self.header().command();
|
|
||||||
if expected_command == our_command {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(RustADBError::WrongResponseReceived(
|
|
||||||
our_command.to_string(),
|
|
||||||
expected_command.to_string(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn header(&self) -> &ADBTransportMessageHeader {
|
|
||||||
&self.header
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn payload(&self) -> &Vec<u8> {
|
|
||||||
&self.payload
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn into_payload(self) -> Vec<u8> {
|
|
||||||
self.payload
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,261 +0,0 @@
|
|||||||
use rusb::Device;
|
|
||||||
use rusb::DeviceDescriptor;
|
|
||||||
use rusb::UsbContext;
|
|
||||||
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
|
|
||||||
use std::fs::read_to_string;
|
|
||||||
use std::io::Read;
|
|
||||||
use std::io::Write;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use super::adb_message_device::ADBMessageDevice;
|
|
||||||
use super::models::MessageCommand;
|
|
||||||
use super::{ADBRsaKey, ADBTransportMessage};
|
|
||||||
use crate::ADBDeviceExt;
|
|
||||||
use crate::ADBMessageTransport;
|
|
||||||
use crate::ADBTransport;
|
|
||||||
use crate::{Result, RustADBError, USBTransport};
|
|
||||||
|
|
||||||
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
|
|
||||||
// Try to read the private key file from given path
|
|
||||||
// If the file is not found, return None
|
|
||||||
// If there is another error while reading the file, return this error
|
|
||||||
// Else, return the private key content
|
|
||||||
let pk = match read_to_string(private_key_path.as_ref()) {
|
|
||||||
Ok(pk) => pk,
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
|
||||||
Err(e) => return Err(e.into()),
|
|
||||||
};
|
|
||||||
|
|
||||||
match ADBRsaKey::new_from_pkcs8(&pk) {
|
|
||||||
Ok(pk) => Ok(Some(pk)),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Search for adb devices with known interface class and subclass values
|
|
||||||
pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
|
|
||||||
let mut found_devices = vec![];
|
|
||||||
for device in rusb::devices()?.iter() {
|
|
||||||
let Ok(des) = device.device_descriptor() else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if is_adb_device(&device, &des) {
|
|
||||||
log::debug!(
|
|
||||||
"Autodetect device {:04x}:{:04x}",
|
|
||||||
des.vendor_id(),
|
|
||||||
des.product_id()
|
|
||||||
);
|
|
||||||
found_devices.push((des.vendor_id(), des.product_id()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match (found_devices.first(), found_devices.get(1)) {
|
|
||||||
(None, _) => Ok(None),
|
|
||||||
(Some(identifiers), None) => Ok(Some(*identifiers)),
|
|
||||||
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
|
|
||||||
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
|
|
||||||
))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check whether a device with given descriptor is an ADB device
|
|
||||||
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
|
|
||||||
const ADB_SUBCLASS: u8 = 0x42;
|
|
||||||
const ADB_PROTOCOL: u8 = 0x1;
|
|
||||||
|
|
||||||
// Some devices require choosing the file transfer mode
|
|
||||||
// for usb debugging to take effect.
|
|
||||||
const BULK_CLASS: u8 = 0xdc;
|
|
||||||
const BULK_ADB_SUBCLASS: u8 = 2;
|
|
||||||
|
|
||||||
for n in 0..des.num_configurations() {
|
|
||||||
let Ok(config_des) = device.config_descriptor(n) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
for interface in config_des.interfaces() {
|
|
||||||
for interface_des in interface.descriptors() {
|
|
||||||
let proto = interface_des.protocol_code();
|
|
||||||
let class = interface_des.class_code();
|
|
||||||
let subcl = interface_des.sub_class_code();
|
|
||||||
if proto == ADB_PROTOCOL
|
|
||||||
&& ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|
|
||||||
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_default_adb_key_path() -> Result<PathBuf> {
|
|
||||||
std::env::home_dir()
|
|
||||||
.map(|home| home.join(".android").join("adbkey"))
|
|
||||||
.ok_or(RustADBError::NoHomeDirectory)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represent a device reached and available over USB.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ADBUSBDevice {
|
|
||||||
private_key: ADBRsaKey,
|
|
||||||
inner: ADBMessageDevice<USBTransport>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBUSBDevice {
|
|
||||||
/// Instantiate a new [`ADBUSBDevice`]
|
|
||||||
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
|
|
||||||
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path
|
|
||||||
pub fn new_with_custom_private_key<P: AsRef<Path>>(
|
|
||||||
vendor_id: u16,
|
|
||||||
product_id: u16,
|
|
||||||
private_key_path: P,
|
|
||||||
) -> Result<Self> {
|
|
||||||
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Instantiate a new [`ADBUSBDevice`] from a [`USBTransport`] and an optional private key path.
|
|
||||||
pub fn new_from_transport(
|
|
||||||
transport: USBTransport,
|
|
||||||
private_key_path: Option<PathBuf>,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let private_key_path = match private_key_path {
|
|
||||||
Some(private_key_path) => private_key_path,
|
|
||||||
None => get_default_adb_key_path()?,
|
|
||||||
};
|
|
||||||
|
|
||||||
Self::new_from_transport_inner(transport, &private_key_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_from_transport_inner<P: AsRef<Path>>(
|
|
||||||
transport: USBTransport,
|
|
||||||
private_key_path: P,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
|
|
||||||
private_key
|
|
||||||
} else {
|
|
||||||
log::warn!(
|
|
||||||
"No private key found at path {}. Using a temporary random one.",
|
|
||||||
private_key_path.as_ref().display()
|
|
||||||
);
|
|
||||||
ADBRsaKey::new_random()?
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut s = Self {
|
|
||||||
private_key,
|
|
||||||
inner: ADBMessageDevice::new(transport),
|
|
||||||
};
|
|
||||||
|
|
||||||
s.connect()?;
|
|
||||||
|
|
||||||
Ok(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// autodetect connected ADB devices and establish a connection with the first device found
|
|
||||||
pub fn autodetect() -> Result<Self> {
|
|
||||||
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
|
|
||||||
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
|
|
||||||
match search_adb_devices()? {
|
|
||||||
Some((vendor_id, product_id)) => {
|
|
||||||
ADBUSBDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
|
|
||||||
}
|
|
||||||
_ => Err(RustADBError::DeviceNotFound(
|
|
||||||
"cannot find USB devices matching the signature of an ADB device".into(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send initial connect
|
|
||||||
pub fn connect(&mut self) -> Result<()> {
|
|
||||||
self.get_transport_mut().connect()?;
|
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
|
||||||
MessageCommand::Cnxn,
|
|
||||||
0x0100_0000,
|
|
||||||
1_048_576,
|
|
||||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
|
||||||
);
|
|
||||||
|
|
||||||
self.get_transport_mut().write_message(message)?;
|
|
||||||
|
|
||||||
let message = self.get_transport_mut().read_message()?;
|
|
||||||
// If the device returned CNXN instead of AUTH it does not require authentication,
|
|
||||||
// so we can skip the auth steps.
|
|
||||||
if message.header().command() == MessageCommand::Cnxn {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
message.assert_command(MessageCommand::Auth)?;
|
|
||||||
self.inner.auth_handshake(message, &self.private_key)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_transport_mut(&mut self) -> &mut USBTransport {
|
|
||||||
self.inner.get_transport_mut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBDeviceExt for ADBUSBDevice {
|
|
||||||
#[inline]
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.shell_command(command, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
|
||||||
self.inner.shell(reader, writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
|
|
||||||
self.inner.stat(remote_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.pull(source, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
|
|
||||||
self.inner.push(stream, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
|
|
||||||
self.inner.reboot(reboot_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
self.inner.install(apk_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()> {
|
|
||||||
self.inner.uninstall(package)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
|
||||||
self.inner.framebuffer_inner()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list(&mut self, path: &dyn AsRef<str>) -> Result<Vec<crate::ADBListItem>> {
|
|
||||||
self.inner.list(path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for ADBUSBDevice {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
// Best effort here
|
|
||||||
let _ = self.get_transport_mut().disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
use std::io::{Cursor, Read};
|
|
||||||
|
|
||||||
use byteorder::{LittleEndian, ReadBytesExt};
|
|
||||||
use image::{ImageBuffer, Rgba};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
ADBMessageTransport, Result, RustADBError,
|
|
||||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
|
||||||
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")?;
|
|
||||||
|
|
||||||
let response = self.recv_and_reply_okay(session)?;
|
|
||||||
|
|
||||||
let mut payload_cursor = Cursor::new(response.payload());
|
|
||||||
|
|
||||||
let version = payload_cursor.read_u32::<LittleEndian>()?;
|
|
||||||
|
|
||||||
let img = match version {
|
|
||||||
// RGBA_8888
|
|
||||||
1 => {
|
|
||||||
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV1>()];
|
|
||||||
|
|
||||||
payload_cursor.read_exact(&mut buf)?;
|
|
||||||
|
|
||||||
let framebuffer_info: FrameBufferInfoV1 = buf.try_into()?;
|
|
||||||
|
|
||||||
let mut framebuffer_data = Vec::new();
|
|
||||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
|
||||||
|
|
||||||
loop {
|
|
||||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let response = self.recv_and_reply_okay(session)?;
|
|
||||||
|
|
||||||
framebuffer_data.extend_from_slice(&response.into_payload());
|
|
||||||
|
|
||||||
log::debug!(
|
|
||||||
"received framebuffer data. new size {}",
|
|
||||||
framebuffer_data.len()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(
|
|
||||||
framebuffer_info.width,
|
|
||||||
framebuffer_info.height,
|
|
||||||
framebuffer_data,
|
|
||||||
)
|
|
||||||
.ok_or_else(|| RustADBError::FramebufferConversionError)?
|
|
||||||
}
|
|
||||||
// RGBX_8888
|
|
||||||
2 => {
|
|
||||||
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV2>()];
|
|
||||||
|
|
||||||
payload_cursor.read_exact(&mut buf)?;
|
|
||||||
|
|
||||||
let framebuffer_info: FrameBufferInfoV2 = buf.try_into()?;
|
|
||||||
|
|
||||||
let mut framebuffer_data = Vec::new();
|
|
||||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
|
||||||
|
|
||||||
loop {
|
|
||||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let response = self.recv_and_reply_okay(session)?;
|
|
||||||
|
|
||||||
framebuffer_data.extend_from_slice(&response.into_payload());
|
|
||||||
|
|
||||||
log::debug!(
|
|
||||||
"received framebuffer data. new size {}",
|
|
||||||
framebuffer_data.len()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(
|
|
||||||
framebuffer_info.width,
|
|
||||||
framebuffer_info.height,
|
|
||||||
framebuffer_data,
|
|
||||||
)
|
|
||||||
.ok_or_else(|| RustADBError::FramebufferConversionError)?
|
|
||||||
}
|
|
||||||
v => return Err(RustADBError::UnimplementedFramebufferImageVersion(v)),
|
|
||||||
};
|
|
||||||
|
|
||||||
self.get_transport_mut()
|
|
||||||
.read_message()
|
|
||||||
.and_then(|message| message.assert_command(MessageCommand::Clse))?;
|
|
||||||
|
|
||||||
Ok(img)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
use std::{fs::File, path::Path};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
ADBMessageTransport, Result,
|
|
||||||
device::{MessageWriter, adb_message_device::ADBMessageDevice},
|
|
||||||
utils::check_extension_is_apk,
|
|
||||||
};
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|
||||||
pub(crate) fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
let mut apk_file = File::open(apk_path)?;
|
|
||||||
|
|
||||||
check_extension_is_apk(apk_path)?;
|
|
||||||
|
|
||||||
let file_size = apk_file.metadata()?.len();
|
|
||||||
|
|
||||||
let session =
|
|
||||||
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());
|
|
||||||
|
|
||||||
std::io::copy(&mut apk_file, &mut writer)?;
|
|
||||||
|
|
||||||
let final_status = self.get_transport_mut().read_message()?;
|
|
||||||
|
|
||||||
match final_status.into_payload().as_slice() {
|
|
||||||
b"Success\n" => {
|
|
||||||
log::info!(
|
|
||||||
"APK file {} successfully installed",
|
|
||||||
apk_path.as_ref().display()
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
|
|
||||||
d.to_vec(),
|
|
||||||
)?)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,9 +0,0 @@
|
|||||||
mod framebuffer;
|
|
||||||
mod install;
|
|
||||||
mod list;
|
|
||||||
mod pull;
|
|
||||||
mod push;
|
|
||||||
mod reboot;
|
|
||||||
mod shell;
|
|
||||||
mod stat;
|
|
||||||
mod uninstall;
|
|
||||||
@@ -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,14 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
ADBMessageTransport, RebootType, Result,
|
|
||||||
device::{MessageCommand, adb_message_device::ADBMessageDevice},
|
|
||||||
};
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|
||||||
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
|
|
||||||
self.open_session(format!("reboot:{reboot_type}\0").as_bytes())?;
|
|
||||||
|
|
||||||
self.get_transport_mut()
|
|
||||||
.read_message()
|
|
||||||
.and_then(|message| message.assert_command(MessageCommand::Okay))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
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},
|
|
||||||
};
|
|
||||||
|
|
||||||
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 mut transport = self.get_transport().clone();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let message = transport.read_message()?;
|
|
||||||
let command = message.header().command();
|
|
||||||
|
|
||||||
if command == MessageCommand::Clse {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.get_transport_mut()
|
|
||||||
.write_message(ADBTransportMessage::new(
|
|
||||||
MessageCommand::Okay,
|
|
||||||
session.local_id(),
|
|
||||||
session.remote_id(),
|
|
||||||
&[],
|
|
||||||
))?;
|
|
||||||
|
|
||||||
output.write_all(&message.into_payload())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// some devices will repeat the trailing CLSE command to ensure
|
|
||||||
// the client has acknowledged it. Read them quickly if present.
|
|
||||||
while let Ok(_discard_close_message) =
|
|
||||||
transport.read_message_with_timeout(Duration::from_millis(20))
|
|
||||||
{}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Starts an interactive shell session on the device.
|
|
||||||
/// Input data is read from [reader] and write to [writer].
|
|
||||||
pub(crate) fn shell(
|
|
||||||
&mut self,
|
|
||||||
mut reader: &mut dyn Read,
|
|
||||||
mut writer: Box<dyn Write + Send>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let session = self.open_session(b"shell:\0")?;
|
|
||||||
|
|
||||||
let mut transport = self.get_transport().clone();
|
|
||||||
|
|
||||||
// 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(),
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
transport.write_message(response)?;
|
|
||||||
|
|
||||||
match message.header().command() {
|
|
||||||
MessageCommand::Write => {
|
|
||||||
writer.write_all(&message.into_payload())?;
|
|
||||||
writer.flush()?;
|
|
||||||
}
|
|
||||||
MessageCommand::Okay => {}
|
|
||||||
_ => return Err(RustADBError::ADBShellNotSupported),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let transport = self.get_transport().clone();
|
|
||||||
let mut shell_writer =
|
|
||||||
ShellMessageWriter::new(transport, session.local_id(), session.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) {
|
|
||||||
match e.kind() {
|
|
||||||
ErrorKind::BrokenPipe => return Ok(()),
|
|
||||||
_ => return Err(RustADBError::IOError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 @@
|
|||||||
use crate::{ADBMessageTransport, Result, device::adb_message_device::ADBMessageDevice};
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|
||||||
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {
|
|
||||||
self.open_session(format!("exec:cmd package 'uninstall' {package_name}\0").as_bytes())?;
|
|
||||||
|
|
||||||
let final_status = self.get_transport_mut().read_message()?;
|
|
||||||
|
|
||||||
match final_status.into_payload().as_slice() {
|
|
||||||
b"Success\n" => {
|
|
||||||
log::info!("Package {package_name} successfully uninstalled");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
|
|
||||||
d.to_vec(),
|
|
||||||
)?)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
use std::io::{Error, ErrorKind, Result, Write};
|
|
||||||
|
|
||||||
use crate::ADBMessageTransport;
|
|
||||||
|
|
||||||
use super::{ADBTransportMessage, MessageCommand};
|
|
||||||
|
|
||||||
/// [`Write`] trait implementation to hide underlying ADB protocol write logic.
|
|
||||||
///
|
|
||||||
/// Read received responses to check that message has been correctly received.
|
|
||||||
pub struct MessageWriter<T: ADBMessageTransport> {
|
|
||||||
transport: T,
|
|
||||||
local_id: u32,
|
|
||||||
remote_id: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> MessageWriter<T> {
|
|
||||||
pub fn new(transport: T, local_id: u32, remote_id: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
transport,
|
|
||||||
local_id,
|
|
||||||
remote_id,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> Write for MessageWriter<T> {
|
|
||||||
fn write(&mut self, buf: &[u8]) -> Result<usize> {
|
|
||||||
let message =
|
|
||||||
ADBTransportMessage::new(MessageCommand::Write, self.local_id, self.remote_id, buf);
|
|
||||||
self.transport
|
|
||||||
.write_message(message)
|
|
||||||
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
|
|
||||||
|
|
||||||
match self.transport.read_message() {
|
|
||||||
Ok(response) => {
|
|
||||||
response
|
|
||||||
.assert_command(MessageCommand::Okay)
|
|
||||||
.map_err(Error::other)?;
|
|
||||||
Ok(buf.len())
|
|
||||||
}
|
|
||||||
Err(e) => Err(Error::other(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flush(&mut self) -> Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,176 +0,0 @@
|
|||||||
use crate::{Result, RustADBError};
|
|
||||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
|
||||||
use num_bigint::{BigUint, ModInverse};
|
|
||||||
use num_traits::FromPrimitive;
|
|
||||||
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;
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
/// Internal ADB representation of a public key
|
|
||||||
struct ADBRsaInternalPublicKey {
|
|
||||||
pub modulus_size_words: u32,
|
|
||||||
pub n0inv: u32,
|
|
||||||
pub modulus: BigUint,
|
|
||||||
pub rr: Vec<u8>,
|
|
||||||
pub exponent: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBRsaInternalPublicKey {
|
|
||||||
pub fn new(exponent: &BigUint, modulus: &BigUint) -> Result<Self> {
|
|
||||||
Ok(Self {
|
|
||||||
modulus_size_words: ANDROID_PUBKEY_MODULUS_SIZE_WORDS,
|
|
||||||
exponent: exponent.to_u32().ok_or(RustADBError::ConversionError)?,
|
|
||||||
modulus: modulus.clone(),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn into_bytes(mut self) -> Vec<u8> {
|
|
||||||
let mut bytes: Vec<u8> = Vec::new();
|
|
||||||
bytes.append(&mut self.modulus_size_words.to_le_bytes().to_vec());
|
|
||||||
bytes.append(&mut self.n0inv.to_le_bytes().to_vec());
|
|
||||||
bytes.append(&mut self.modulus.to_bytes_le());
|
|
||||||
bytes.append(&mut self.rr);
|
|
||||||
bytes.append(&mut self.exponent.to_le_bytes().to_vec());
|
|
||||||
|
|
||||||
bytes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ADBRsaKey {
|
|
||||||
private_key: RsaPrivateKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBRsaKey {
|
|
||||||
pub fn new_random() -> Result<Self> {
|
|
||||||
Ok(Self {
|
|
||||||
private_key: RsaPrivateKey::new(&mut rsa::rand_core::OsRng, ADB_PRIVATE_KEY_SIZE)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_from_pkcs8(pkcs8_content: &str) -> Result<Self> {
|
|
||||||
Ok(ADBRsaKey {
|
|
||||||
private_key: RsaPrivateKey::from_pkcs8_pem(pkcs8_content)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn android_pubkey_encode(&self) -> Result<String> {
|
|
||||||
// Helped from project: https://github.com/hajifkd/webadb
|
|
||||||
// Source code: https://android.googlesource.com/platform/system/core/+/refs/heads/main/libcrypto_utils/android_pubkey.cpp
|
|
||||||
// Useful function `android_pubkey_encode()`
|
|
||||||
let mut adb_rsa_pubkey =
|
|
||||||
ADBRsaInternalPublicKey::new(self.private_key.e(), self.private_key.n())?;
|
|
||||||
|
|
||||||
// r32 = 2 ^ 32
|
|
||||||
let r32 = BigUint::from_u64(1 << 32).ok_or(RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
// r = 2 ^ rsa_size = 2 ^ 2048
|
|
||||||
let r = set_bit(ADB_PRIVATE_KEY_SIZE)?;
|
|
||||||
|
|
||||||
// rr = r ^ 2 mod N
|
|
||||||
let rr = r.modpow(&BigUint::from(2u32), &adb_rsa_pubkey.modulus);
|
|
||||||
adb_rsa_pubkey.rr = rr.to_bytes_le();
|
|
||||||
|
|
||||||
// rem = N[0]
|
|
||||||
let rem = &adb_rsa_pubkey.modulus % &r32;
|
|
||||||
|
|
||||||
// n0inv = -1 / rem mod r32
|
|
||||||
let n0inv = rem
|
|
||||||
.mod_inverse(&r32)
|
|
||||||
.and_then(|v| v.to_biguint())
|
|
||||||
.ok_or(RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
// BN_sub(n0inv, r32, n0inv)
|
|
||||||
adb_rsa_pubkey.n0inv = (r32 - n0inv)
|
|
||||||
.to_u32()
|
|
||||||
.ok_or(RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
Self::encode_public_key(adb_rsa_pubkey.into_bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn encode_public_key(pub_key: Vec<u8>) -> Result<String> {
|
|
||||||
let mut encoded = STANDARD.encode(pub_key);
|
|
||||||
encoded.push(' ');
|
|
||||||
write!(encoded, "adb_client@{}", env!("CARGO_PKG_VERSION"))
|
|
||||||
.map_err(|_| RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
Ok(encoded)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
|
||||||
Ok(self
|
|
||||||
.private_key
|
|
||||||
.sign(Pkcs1v15Sign::new::<sha1::Sha1>(), msg.as_ref())?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_bit(n: usize) -> Result<BigUint> {
|
|
||||||
BigUint::parse_bytes(
|
|
||||||
&{
|
|
||||||
let mut bits = vec![b'1'];
|
|
||||||
bits.append(&mut vec![b'0'; n]);
|
|
||||||
bits
|
|
||||||
}[..],
|
|
||||||
2,
|
|
||||||
)
|
|
||||||
.ok_or(RustADBError::ConversionError)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_pubkey_gen() {
|
|
||||||
const DEFAULT_PRIV_KEY: &'static str = r"-----BEGIN PRIVATE KEY-----
|
|
||||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4Dyn85cxDJnjM
|
|
||||||
uYXQl/w469MDKdlGdviLfmFMWeYLVfL2Mz1AVyvKqscrtlhbbgMQ/M+3lDvEdHS0
|
|
||||||
14RIGAwWRtrlTTmhLvM2/IO+eSKSYeCrCVc4KLG3E3WRryUXbs2ynA29xjTJVw+Z
|
|
||||||
xYxDyn/tAYPEyMm4v+HIJHcOtRzxtO2vjMJ2vBT/ywYxjhncXbFSO09q2E4XrHli
|
|
||||||
SIPyO82hZgCkpzTZRp+nyA17TYuV9++mvUr9lWH9RbC+o8EF3yitlBsE2uXr97EV
|
|
||||||
i2Qy8CE7FIxsihXlukppwKRuz+1rJrvmZPTn49ZS+sIS99WE9GoCpsyQvTpvehrM
|
|
||||||
SIDRsVZPAgMBAAECggEAWNXAzzXeS36zCSR1yILCknqHotw86Pyc4z7BGUe+dzQp
|
|
||||||
itiaNIaeNTgN3zQoGyDSzA0o+BLMcfo/JdVrHBy3IL1cAxYtvXTaoGxp7bGrlPk2
|
|
||||||
pXZhqVJCy/jRYtokzdWF5DHbk/+pFJA3kGE/XKzM54g2n/DFI61A/QdUiz2w1ZtI
|
|
||||||
vc5cM08EM8B/TSI3SeWB8zkh5SlIuLsFO2J2+tCak6PdFfKOVIrFv9dKJYLxx+59
|
|
||||||
+edZamw2EvNlnl/sewgUk0gaZvQKVf4ivHyM+KSHuV4RFfiLvGuVcyA6XhSjztsG
|
|
||||||
EA++jDHP5ib/Izes7UK09v9y7kow+z6vUtnDDQOvgQKBgQD8WWAn7FQt9aziCw19
|
|
||||||
gZynzHG1bXI7uuEVSneuA3UwJImmDu8W+Qb9YL9Dc2nV0M5pGGdXKi2jzq8gPar6
|
|
||||||
GPAmy7TOlov6Nm0pbMXTAfuovG+gIXxelp3US3FvyRupi0/7UQRRwvetFYbDFwJX
|
|
||||||
ydF5uEtZdGSHAjPeU5FLq6tBwQKBgQC6uN0JwwZn+eaxguyKOXvp0KykhFI0HI1A
|
|
||||||
MBDZ1uuKt6OW5+r9NeQtTLctGlNKVQ8wz+Wr0C/nLGIIv4lySS9WFyc5/FnFhDdy
|
|
||||||
LsEi6whcca4vq3jsMOukvQGFnERsou4LqBEI1Es7jjeeEq+/8WnNTi6Y1flZ6UAp
|
|
||||||
YAOeFI98DwKBgQDvyfHgHeajwZalOQF5qGb24AOQ9c4dyefGNnvhA/IgbCfMftZc
|
|
||||||
iwhETuGQM6R3A7KQFRtlrXOu+2BYD6Ffg8D37IwD3vRmL7+tJGoapwC/B0g+7nLi
|
|
||||||
4tZY+9Nv+LbrdbDry8GB+/UkKJdk3IFicCk4M5KOD1bTH5mwAtLHB/p1QQKBgDHi
|
|
||||||
k8M45GxA+p4wMUvYgb987bLiWyfq/N3KOaZJYhJkb4MwoLpXfIeRuFqHbvsr8GwF
|
|
||||||
DwIxE6s6U1KtAWaUIN5qPyOhxMYdRcbusNDIZCp2gKfhsuO/SiVwDYkJr8oqWVip
|
|
||||||
5SsrtJHLtBY6PdQVBkRAf/h7KiwYQfkL2suQCKmHAoGBAJAkYImBYPHuRcnSXikn
|
|
||||||
xGDK/moPvzs0CjdPlRcEN+Myy/G0FUrOaC0FcpNoJOdQSYz3F6URA4nX+zj6Ie7G
|
|
||||||
CNkECiepaGyquQaffwR1CAi8dH6biJjlTQWQPFcCLA0hvernWo3eaSfiL7fHyym+
|
|
||||||
ile69MHFENUePSpuRSiF3Z02
|
|
||||||
-----END PRIVATE KEY-----";
|
|
||||||
let priv_key =
|
|
||||||
ADBRsaKey::new_from_pkcs8(DEFAULT_PRIV_KEY).expect("cannot create rsa key from data");
|
|
||||||
let pub_key = priv_key
|
|
||||||
.android_pubkey_encode()
|
|
||||||
.expect("cannot encode public key");
|
|
||||||
let pub_key_adb = "\
|
|
||||||
QAAAAFH/pU9PVrHRgEjMGnpvOr2QzKYCavSE1fcSwvpS1uPn9GTmuyZr7c9up\
|
|
||||||
MBpSrrlFYpsjBQ7IfAyZIsVsffr5doEG5StKN8FwaO+sEX9YZX9Sr2m7/eVi0\
|
|
||||||
17Dcinn0bZNKekAGahzTvyg0hieawXTthqTztSsV3cGY4xBsv/FLx2woyv7bT\
|
|
||||||
xHLUOdyTI4b+4ycjEgwHtf8pDjMWZD1fJNMa9DZyyzW4XJa+RdRO3sSg4Vwmr\
|
|
||||||
4GGSInm+g/w28y6hOU3l2kYWDBhIhNe0dHTEO5S3z/wQA25bWLYrx6rKK1dAP\
|
|
||||||
TP28lUL5llMYX6L+HZG2SkD0+s4/JfQhbnMeCZDzOX8KQ+4ThLy/gDTqCSTjj\
|
|
||||||
ic8BykdUIqYPwAjBMgQwLOLY5WNJMpjGlFINRcCGhvFFZ73sJTLerECuV/Oae\
|
|
||||||
nFRcORwnGIRgMrYXj4tjmxJC7sq3cfNX96YIcSCDE9SZFdlKXVK8Jc4YMLGF3\
|
|
||||||
MI8k1KoTby34uaIyxPJvwM1WR4Rdj60fwMyikFXNaOR2fPteZ3UMBA7CMrOEm\
|
|
||||||
9iYjntyEppA4hQXIO1TWTzkA/Kfl1i67k5NuLIQdhPFEc5ox5IYVHusauPQ7d\
|
|
||||||
Awu6BlgK37TUn0JdK0Z6Z4RaEIaNiEI0d5CoP6zQKV2QQnlscYpdsaUW5t9/F\
|
|
||||||
LioVXPwrz0tx35JyIUZPPYwEAAQA= ";
|
|
||||||
assert_eq!(&pub_key[..pub_key_adb.len()], pub_key_adb);
|
|
||||||
}
|
|
||||||
@@ -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,64 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_repr::{Deserialize_repr, Serialize_repr};
|
|
||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize_repr, Deserialize_repr)]
|
|
||||||
#[repr(u32)]
|
|
||||||
pub enum MessageCommand {
|
|
||||||
/// Connect to a device
|
|
||||||
Cnxn = 0x4E58_4E43,
|
|
||||||
/// Close connection to a device
|
|
||||||
Clse = 0x4553_4C43,
|
|
||||||
/// Device ask for authentication
|
|
||||||
Auth = 0x4854_5541,
|
|
||||||
/// Open a data connection
|
|
||||||
Open = 0x4E45_504F,
|
|
||||||
/// Write data to connection
|
|
||||||
Write = 0x4554_5257,
|
|
||||||
/// Server understood the message
|
|
||||||
Okay = 0x5941_4B4F,
|
|
||||||
/// Start a connection using TLS
|
|
||||||
Stls = 0x534C_5453,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
pub struct SubcommandWithArg {
|
|
||||||
subcommand: MessageSubcommand,
|
|
||||||
arg: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MessageSubcommand {
|
|
||||||
pub fn with_arg(self, arg: u32) -> SubcommandWithArg {
|
|
||||||
SubcommandWithArg {
|
|
||||||
subcommand: self,
|
|
||||||
arg,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for MessageCommand {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
MessageCommand::Cnxn => write!(f, "CNXN"),
|
|
||||||
MessageCommand::Clse => write!(f, "CLSE"),
|
|
||||||
MessageCommand::Auth => write!(f, "AUTH"),
|
|
||||||
MessageCommand::Open => write!(f, "OPEN"),
|
|
||||||
MessageCommand::Write => write!(f, "WRTE"),
|
|
||||||
MessageCommand::Okay => write!(f, "OKAY"),
|
|
||||||
MessageCommand::Stls => write!(f, "STLS"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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};
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
use std::io::Write;
|
|
||||||
|
|
||||||
use crate::ADBMessageTransport;
|
|
||||||
|
|
||||||
use super::{ADBTransportMessage, models::MessageCommand};
|
|
||||||
|
|
||||||
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
|
|
||||||
pub struct ShellMessageWriter<T: ADBMessageTransport> {
|
|
||||||
transport: T,
|
|
||||||
local_id: u32,
|
|
||||||
remote_id: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ShellMessageWriter<T> {
|
|
||||||
pub fn new(transport: T, local_id: u32, remote_id: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
transport,
|
|
||||||
local_id,
|
|
||||||
remote_id,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> Write for ShellMessageWriter<T> {
|
|
||||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
|
||||||
let message =
|
|
||||||
ADBTransportMessage::new(MessageCommand::Write, self.local_id, self.remote_id, buf);
|
|
||||||
self.transport
|
|
||||||
.write_message(message)
|
|
||||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
|
||||||
Ok(buf.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flush(&mut self) -> std::io::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
10
adb_client/src/emulator/rotate.rs
Normal file
10
adb_client/src/emulator/rotate.rs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
use crate::{models::ADBEmulatorCommand, ADBEmulatorDevice, Result};
|
||||||
|
|
||||||
|
impl ADBEmulatorDevice {
|
||||||
|
/// Send a SMS to this emulator with given content with given phone number
|
||||||
|
pub fn rotate(&mut self) -> Result<()> {
|
||||||
|
let transport = self.connect()?;
|
||||||
|
transport.send_command(ADBEmulatorCommand::Rotate)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
use crate::{models::ADBEmulatorCommand, ADBEmulatorDevice, Result};
|
||||||
|
|
||||||
impl ADBEmulatorDevice {
|
impl ADBEmulatorDevice {
|
||||||
/// Send a SMS to this emulator with given content with given phone number
|
/// Send a SMS to this emulator with given content with given phone number
|
||||||
pub fn send_sms(&mut self, phone_number: &str, content: &str) -> Result<()> {
|
pub fn send_sms(&mut self, phone_number: &str, content: &str) -> Result<()> {
|
||||||
self.connect()?.send_command(&ADBEmulatorCommand::Sms(
|
let transport = self.connect()?;
|
||||||
|
transport.send_command(ADBEmulatorCommand::Sms(
|
||||||
phone_number.to_string(),
|
phone_number.to_string(),
|
||||||
content.to_string(),
|
content.to_string(),
|
||||||
))
|
))?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
|
|
||||||
|
|
||||||
impl ADBEmulatorDevice {
|
|
||||||
/// Send a SMS to this emulator with given content with given phone number
|
|
||||||
pub fn rotate(&mut self) -> Result<()> {
|
|
||||||
self.connect()?.send_command(&ADBEmulatorCommand::Rotate)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
mod adb_emulator_device;
|
|
||||||
mod commands;
|
|
||||||
mod models;
|
|
||||||
pub use adb_emulator_device::ADBEmulatorDevice;
|
|
||||||
pub(crate) use models::ADBEmulatorCommand;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
mod adb_emulator_command;
|
|
||||||
pub use adb_emulator_command::ADBEmulatorCommand;
|
|
||||||
@@ -15,9 +15,6 @@ pub enum RustADBError {
|
|||||||
/// Indicates that ADB server responded an unknown response type.
|
/// Indicates that ADB server responded an unknown response type.
|
||||||
#[error("Unknown response type {0}")]
|
#[error("Unknown response type {0}")]
|
||||||
UnknownResponseType(String),
|
UnknownResponseType(String),
|
||||||
/// Indicated that an unexpected command has been received
|
|
||||||
#[error("Wrong response command received: {0}. Expected {1}")]
|
|
||||||
WrongResponseReceived(String, String),
|
|
||||||
/// Indicates that ADB server responses an unknown device state.
|
/// Indicates that ADB server responses an unknown device state.
|
||||||
#[error("Unknown device state {0}")]
|
#[error("Unknown device state {0}")]
|
||||||
UnknownDeviceState(String),
|
UnknownDeviceState(String),
|
||||||
@@ -42,9 +39,6 @@ pub enum RustADBError {
|
|||||||
/// Indicates that an error occurred when converting a value.
|
/// Indicates that an error occurred when converting a value.
|
||||||
#[error("Conversion error")]
|
#[error("Conversion error")]
|
||||||
ConversionError,
|
ConversionError,
|
||||||
/// Indicates an error with the integer conversion.
|
|
||||||
#[error(transparent)]
|
|
||||||
IntegerConversionError(#[from] std::num::TryFromIntError),
|
|
||||||
/// Remote ADB server does not support shell feature.
|
/// Remote ADB server does not support shell feature.
|
||||||
#[error("Remote ADB server does not support shell feature")]
|
#[error("Remote ADB server does not support shell feature")]
|
||||||
ADBShellNotSupported,
|
ADBShellNotSupported,
|
||||||
@@ -60,78 +54,7 @@ pub enum RustADBError {
|
|||||||
/// An error occurred when converting framebuffer content
|
/// An error occurred when converting framebuffer content
|
||||||
#[error("Cannot convert framebuffer into image")]
|
#[error("Cannot convert framebuffer into image")]
|
||||||
FramebufferConversionError,
|
FramebufferConversionError,
|
||||||
/// Unimplemented framebuffer image version
|
|
||||||
#[error("Unimplemented framebuffer image version: {0}")]
|
|
||||||
UnimplementedFramebufferImageVersion(u32),
|
|
||||||
/// An error occurred while getting user's home directory
|
/// An error occurred while getting user's home directory
|
||||||
#[error("Cannot get user home directory")]
|
|
||||||
HomeError,
|
|
||||||
/// Cannot get home directory
|
|
||||||
#[error("Cannot get home directory")]
|
|
||||||
NoHomeDirectory,
|
|
||||||
/// Generic USB error
|
|
||||||
#[error("USB Error: {0}")]
|
|
||||||
UsbError(#[from] rusb::Error),
|
|
||||||
/// USB device not found
|
|
||||||
#[error("USB Device not found: {0} {1}")]
|
|
||||||
USBDeviceNotFound(u16, u16),
|
|
||||||
/// No descriptor found
|
|
||||||
#[error("No USB descriptor found")]
|
|
||||||
USBNoDescriptorFound,
|
|
||||||
/// Integrity of the received message cannot be validated
|
|
||||||
#[error("Invalid integrity. Expected CRC32 {0}, got {1}")]
|
|
||||||
InvalidIntegrity(u32, u32),
|
|
||||||
/// Error while decoding base64 data
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Base64DecodeError(#[from] base64::DecodeError),
|
HomeError(#[from] homedir::GetHomeError),
|
||||||
/// Error while encoding base64 data
|
|
||||||
#[error(transparent)]
|
|
||||||
Base64EncodeError(#[from] base64::EncodeSliceError),
|
|
||||||
/// An error occurred with RSA engine
|
|
||||||
#[error(transparent)]
|
|
||||||
RSAError(#[from] rsa::errors::Error),
|
|
||||||
/// Cannot convert given data from slice
|
|
||||||
#[error(transparent)]
|
|
||||||
TryFromSliceError(#[from] std::array::TryFromSliceError),
|
|
||||||
/// Given path does not represent an APK
|
|
||||||
#[error("wrong file extension: {0}")]
|
|
||||||
WrongFileExtension(String),
|
|
||||||
/// An error occurred with PKCS8 data
|
|
||||||
#[error("error with pkcs8: {0}")]
|
|
||||||
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
|
|
||||||
/// Error during certificate generation
|
|
||||||
#[error(transparent)]
|
|
||||||
CertificateGenerationError(#[from] rcgen::Error),
|
|
||||||
/// TLS Error
|
|
||||||
#[error(transparent)]
|
|
||||||
TLSError(#[from] rustls::Error),
|
|
||||||
/// PEM certificate error
|
|
||||||
#[error(transparent)]
|
|
||||||
PemCertError(#[from] rustls_pki_types::pem::Error),
|
|
||||||
/// Error while locking mutex
|
|
||||||
#[error("error while locking data")]
|
|
||||||
PoisonError,
|
|
||||||
/// Cannot upgrade connection from TCP to TLS
|
|
||||||
#[error("upgrade error: {0}")]
|
|
||||||
UpgradeError(String),
|
|
||||||
/// An error occurred while getting mdns devices
|
|
||||||
#[cfg(feature = "mdns")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
|
|
||||||
#[error(transparent)]
|
|
||||||
MDNSError(#[from] mdns_sd::Error),
|
|
||||||
/// An error occurred while sending data to channel
|
|
||||||
#[error("error sending data to channel")]
|
|
||||||
SendError,
|
|
||||||
/// 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 {
|
|
||||||
fn from(_err: std::sync::PoisonError<T>) -> Self {
|
|
||||||
Self::PoisonError
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,34 +3,16 @@
|
|||||||
#![forbid(missing_debug_implementations)]
|
#![forbid(missing_debug_implementations)]
|
||||||
#![forbid(missing_docs)]
|
#![forbid(missing_docs)]
|
||||||
#![doc = include_str!("../README.md")]
|
#![doc = include_str!("../README.md")]
|
||||||
// Feature `doc_cfg` is currently only available on nightly builds.
|
|
||||||
// It is activated when cfg `docsrs` is enabled.
|
|
||||||
// Documentation can be build locally using:
|
|
||||||
// `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features`
|
|
||||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
|
||||||
|
|
||||||
mod adb_device_ext;
|
mod adb_termios;
|
||||||
mod constants;
|
mod emulator;
|
||||||
mod device;
|
|
||||||
mod emulator_device;
|
|
||||||
mod error;
|
mod error;
|
||||||
|
|
||||||
/// MDNS-related definitions
|
|
||||||
#[cfg(feature = "mdns")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
|
|
||||||
pub mod mdns;
|
|
||||||
|
|
||||||
mod models;
|
mod models;
|
||||||
mod server;
|
mod server;
|
||||||
mod server_device;
|
|
||||||
mod transports;
|
mod transports;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
pub use adb_device_ext::ADBDeviceExt;
|
|
||||||
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
|
|
||||||
pub use emulator_device::ADBEmulatorDevice;
|
|
||||||
pub use error::{Result, RustADBError};
|
pub use error::{Result, RustADBError};
|
||||||
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
|
pub use models::{AdbVersion, DeviceLong, DeviceShort, DeviceState, RebootType};
|
||||||
pub use server::*;
|
pub use server::*;
|
||||||
pub use server_device::ADBServerDevice;
|
|
||||||
pub use transports::*;
|
pub use transports::*;
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
use std::{
|
|
||||||
collections::HashSet,
|
|
||||||
fmt::Display,
|
|
||||||
net::{IpAddr, Ipv4Addr, Ipv6Addr},
|
|
||||||
};
|
|
||||||
|
|
||||||
use mdns_sd::{ResolvedService, ScopedIp};
|
|
||||||
|
|
||||||
/// Represent a device found from mdns search
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct MDNSDevice {
|
|
||||||
/// Full device address when resolved
|
|
||||||
pub fullname: String,
|
|
||||||
/// Device IP addresses
|
|
||||||
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 {
|
|
||||||
Self {
|
|
||||||
fullname: value.fullname,
|
|
||||||
addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,78 +0,0 @@
|
|||||||
use mdns_sd::{ServiceDaemon, ServiceEvent};
|
|
||||||
use std::{sync::mpsc::Sender, thread::JoinHandle};
|
|
||||||
|
|
||||||
use super::MDNSDevice;
|
|
||||||
use crate::{Result, RustADBError};
|
|
||||||
|
|
||||||
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
|
|
||||||
|
|
||||||
/// Structure holding responsibility over mdns discovery
|
|
||||||
pub struct MDNSDiscoveryService {
|
|
||||||
daemon: ServiceDaemon,
|
|
||||||
thread_handle: Option<JoinHandle<Result<()>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for MDNSDiscoveryService {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("MDNSDiscoveryService")
|
|
||||||
.field("daemon", &self.daemon.get_metrics())
|
|
||||||
.field("handle", &self.thread_handle)
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MDNSDiscoveryService {
|
|
||||||
/// Instantiate a new discovery service to find devices over mdns
|
|
||||||
pub fn new() -> Result<Self> {
|
|
||||||
Ok(MDNSDiscoveryService {
|
|
||||||
daemon: ServiceDaemon::new()?,
|
|
||||||
thread_handle: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start discovery by spawning a new background thread responsible of getting events.
|
|
||||||
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
|
|
||||||
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
|
|
||||||
|
|
||||||
let handle: JoinHandle<Result<()>> = std::thread::spawn(move || {
|
|
||||||
loop {
|
|
||||||
while let Ok(event) = receiver.recv() {
|
|
||||||
match event {
|
|
||||||
ServiceEvent::SearchStarted(_)
|
|
||||||
| ServiceEvent::ServiceRemoved(_, _)
|
|
||||||
| ServiceEvent::ServiceFound(_, _)
|
|
||||||
| ServiceEvent::SearchStopped(_) => {
|
|
||||||
// Ignoring these events. We are only interesting in found devices
|
|
||||||
}
|
|
||||||
ServiceEvent::ServiceResolved(service_info) => {
|
|
||||||
sender
|
|
||||||
.send(MDNSDevice::from(service_info))
|
|
||||||
.map_err(|_| RustADBError::SendError)?;
|
|
||||||
}
|
|
||||||
e => {
|
|
||||||
log::warn!("received unknown event type {e:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
self.thread_handle = Some(handle);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shutdown discovery engines.
|
|
||||||
pub fn shutdown(&mut self) -> Result<()> {
|
|
||||||
match self.daemon.shutdown() {
|
|
||||||
Ok(_) => Ok(()),
|
|
||||||
Err(e) => match e {
|
|
||||||
mdns_sd::Error::Again => {
|
|
||||||
self.daemon.shutdown()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
e => Err(RustADBError::MDNSError(e)),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
mod mdns_device;
|
|
||||||
mod mdns_discovery;
|
|
||||||
|
|
||||||
pub use mdns_device::MDNSDevice;
|
|
||||||
pub use mdns_discovery::MDNSDiscoveryService;
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
pub enum ADBEmulatorCommand {
|
pub(crate) enum ADBEmulatorCommand {
|
||||||
Authenticate(String),
|
Authenticate(String),
|
||||||
Sms(String, String),
|
Sms(String, String),
|
||||||
Rotate,
|
Rotate,
|
||||||
@@ -24,7 +24,8 @@ impl ADBEmulatorCommand {
|
|||||||
pub(crate) fn skip_response_lines(&self) -> u8 {
|
pub(crate) fn skip_response_lines(&self) -> u8 {
|
||||||
match self {
|
match self {
|
||||||
ADBEmulatorCommand::Authenticate(_) => 1,
|
ADBEmulatorCommand::Authenticate(_) => 1,
|
||||||
ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
|
ADBEmulatorCommand::Sms(_, _) => 0,
|
||||||
|
ADBEmulatorCommand::Rotate => 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
use crate::{WaitForDeviceState, WaitForDeviceTransport};
|
|
||||||
|
|
||||||
use super::RebootType;
|
use super::RebootType;
|
||||||
use std::net::SocketAddrV4;
|
use std::net::SocketAddrV4;
|
||||||
|
|
||||||
@@ -15,29 +13,15 @@ pub(crate) enum AdbServerCommand {
|
|||||||
HostFeatures,
|
HostFeatures,
|
||||||
Connect(SocketAddrV4),
|
Connect(SocketAddrV4),
|
||||||
Disconnect(SocketAddrV4),
|
Disconnect(SocketAddrV4),
|
||||||
Pair(SocketAddrV4, String),
|
Pair(SocketAddrV4, u32),
|
||||||
TransportAny,
|
TransportAny,
|
||||||
TransportSerial(String),
|
TransportSerial(String),
|
||||||
MDNSCheck,
|
|
||||||
MDNSServices,
|
|
||||||
ServerStatus,
|
|
||||||
ReconnectOffline,
|
|
||||||
Uninstall(String),
|
|
||||||
Install(u64),
|
|
||||||
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
|
|
||||||
// Local commands
|
// Local commands
|
||||||
ShellCommand(String, Vec<String>),
|
ShellCommand(String),
|
||||||
Shell,
|
Shell,
|
||||||
FrameBuffer,
|
FrameBuffer,
|
||||||
Sync,
|
Sync,
|
||||||
Reboot(RebootType),
|
Reboot(RebootType),
|
||||||
Forward(String, String),
|
|
||||||
ForwardRemoveAll,
|
|
||||||
Reverse(String, String),
|
|
||||||
ReverseRemoveAll,
|
|
||||||
Reconnect,
|
|
||||||
TcpIp(u16),
|
|
||||||
Usb,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for AdbServerCommand {
|
impl Display for AdbServerCommand {
|
||||||
@@ -51,14 +35,10 @@ impl Display for AdbServerCommand {
|
|||||||
AdbServerCommand::TrackDevices => write!(f, "host:track-devices"),
|
AdbServerCommand::TrackDevices => write!(f, "host:track-devices"),
|
||||||
AdbServerCommand::TransportAny => write!(f, "host:transport-any"),
|
AdbServerCommand::TransportAny => write!(f, "host:transport-any"),
|
||||||
AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"),
|
AdbServerCommand::TransportSerial(serial) => write!(f, "host:transport:{serial}"),
|
||||||
AdbServerCommand::ShellCommand(command, args) => {
|
AdbServerCommand::ShellCommand(command) => match std::env::var("TERM") {
|
||||||
let args_s = args.join(",");
|
Ok(term) => write!(f, "shell,TERM={term},raw:{command}"),
|
||||||
write!(
|
Err(_) => write!(f, "shell,raw:{command}"),
|
||||||
f,
|
},
|
||||||
"shell{}{args_s},raw:{command}",
|
|
||||||
if args.is_empty() { "" } else { "," }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
AdbServerCommand::Shell => match std::env::var("TERM") {
|
AdbServerCommand::Shell => match std::env::var("TERM") {
|
||||||
Ok(term) => write!(f, "shell,TERM={term},raw:"),
|
Ok(term) => write!(f, "shell,TERM={term},raw:"),
|
||||||
Err(_) => write!(f, "shell,raw:"),
|
Err(_) => write!(f, "shell,raw:"),
|
||||||
@@ -67,50 +47,12 @@ impl Display for AdbServerCommand {
|
|||||||
AdbServerCommand::Reboot(reboot_type) => {
|
AdbServerCommand::Reboot(reboot_type) => {
|
||||||
write!(f, "reboot:{reboot_type}")
|
write!(f, "reboot:{reboot_type}")
|
||||||
}
|
}
|
||||||
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{addr}"),
|
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{}", addr),
|
||||||
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{addr}"),
|
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{}", addr),
|
||||||
AdbServerCommand::Pair(addr, code) => {
|
AdbServerCommand::Pair(addr, code) => {
|
||||||
write!(f, "host:pair:{code}:{addr}")
|
write!(f, "host:pair:{code}:{}", addr)
|
||||||
}
|
}
|
||||||
AdbServerCommand::FrameBuffer => write!(f, "framebuffer:"),
|
AdbServerCommand::FrameBuffer => write!(f, "framebuffer:"),
|
||||||
AdbServerCommand::Forward(remote, local) => {
|
|
||||||
write!(f, "host:forward:{local};{remote}")
|
|
||||||
}
|
|
||||||
AdbServerCommand::ForwardRemoveAll => write!(f, "host:killforward-all"),
|
|
||||||
AdbServerCommand::Reverse(remote, local) => {
|
|
||||||
write!(f, "reverse:forward:{remote};{local}")
|
|
||||||
}
|
|
||||||
AdbServerCommand::ReverseRemoveAll => write!(f, "reverse:killforward-all"),
|
|
||||||
AdbServerCommand::MDNSCheck => write!(f, "host:mdns:check"),
|
|
||||||
AdbServerCommand::MDNSServices => write!(f, "host:mdns:services"),
|
|
||||||
AdbServerCommand::ServerStatus => write!(f, "host:server-status"),
|
|
||||||
AdbServerCommand::Reconnect => write!(f, "reconnect"),
|
|
||||||
AdbServerCommand::ReconnectOffline => write!(f, "host:reconnect-offline"),
|
|
||||||
AdbServerCommand::TcpIp(port) => {
|
|
||||||
write!(f, "tcpip:{port}")
|
|
||||||
}
|
|
||||||
AdbServerCommand::Usb => write!(f, "usb:"),
|
|
||||||
AdbServerCommand::Install(size) => write!(f, "exec:cmd package 'install' -S {size}"),
|
|
||||||
AdbServerCommand::Uninstall(package) => {
|
|
||||||
write!(f, "exec:cmd package 'uninstall' {package}")
|
|
||||||
}
|
|
||||||
AdbServerCommand::WaitForDevice(wait_for_device_state, wait_for_device_transport) => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"host:wait-for-{wait_for_device_transport}-{wait_for_device_state}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_pair_command() {
|
|
||||||
let host = "192.168.0.197:34783";
|
|
||||||
let code = "091102";
|
|
||||||
let code_u32 = code.parse::<u32>().expect("cannot parse u32");
|
|
||||||
let pair = AdbServerCommand::Pair(host.parse().expect("cannot parse host"), code.into());
|
|
||||||
|
|
||||||
assert_eq!(pair.to_string(), format!("host:pair:{code}:{host}"));
|
|
||||||
assert_ne!(pair.to_string(), format!("host:pair:{code_u32}:{host}"))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
use byteorder::ByteOrder;
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use std::{
|
|
||||||
fmt::Display,
|
|
||||||
time::{Duration, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Represents a `stat` response
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
|
||||||
pub struct AdbStatResponse {
|
|
||||||
/// File permissions
|
|
||||||
pub file_perm: u32,
|
|
||||||
/// File size, in bytes
|
|
||||||
pub file_size: u32,
|
|
||||||
/// File modification time
|
|
||||||
pub mod_time: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<[u8; 12]> for AdbStatResponse {
|
|
||||||
fn from(value: [u8; 12]) -> Self {
|
|
||||||
Self {
|
|
||||||
file_perm: LittleEndian::read_u32(&value[0..4]),
|
|
||||||
file_size: LittleEndian::read_u32(&value[4..8]),
|
|
||||||
mod_time: LittleEndian::read_u32(&value[8..]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for AdbStatResponse {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
let d = UNIX_EPOCH + Duration::from_secs(self.mod_time.into());
|
|
||||||
// Create DateTime from SystemTime
|
|
||||||
let datetime = DateTime::<Utc>::from(d);
|
|
||||||
|
|
||||||
writeln!(f, "File permissions: {}", self.file_perm)?;
|
|
||||||
writeln!(f, "File size: {} bytes", self.file_size)?;
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"Modification time: {}",
|
|
||||||
datetime.format("%Y-%m-%d %H:%M:%S.%f %Z")
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,8 +15,7 @@ pub struct AdbVersion {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AdbVersion {
|
impl AdbVersion {
|
||||||
/// Instantiates a new [`AdbVersion`].
|
/// Instantiates a new [AdbVersion].
|
||||||
#[must_use]
|
|
||||||
pub fn new(minor: u32, revision: u32) -> Self {
|
pub fn new(minor: u32, revision: u32) -> Self {
|
||||||
Self {
|
Self {
|
||||||
major: 1,
|
major: 1,
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
|
use lazy_static::lazy_static;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::sync::LazyLock;
|
|
||||||
use std::{fmt::Display, str};
|
use std::{fmt::Display, str};
|
||||||
|
|
||||||
use crate::{DeviceState, RustADBError};
|
use crate::{DeviceState, RustADBError};
|
||||||
use regex::bytes::Regex;
|
use regex::bytes::Regex;
|
||||||
|
|
||||||
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
lazy_static! {
|
||||||
Regex::new(r"^(?P<identifier>\S+)\s+(?P<state>\w+)\s+(usb:(?P<usb1>\S+)|(?P<usb2>\S+))?\s*(product:(?P<product>\S+)\s+model:(?P<model>\w+)\s+device:(?P<device>\S+)\s+)?transport_id:(?P<transport_id>\d+)$").expect("cannot build devices long regex")
|
static ref DEVICES_LONG_REGEX: Regex = Regex::new("^(?P<identifier>\\S+)\\s+(?P<state>\\w+) ((usb:(?P<usb1>.*)|(?P<usb2>\\d-\\d)) )?(product:(?P<product>\\w+) model:(?P<model>\\w+) device:(?P<device>\\w+) )?transport_id:(?P<transport_id>\\d+)$").expect("cannot build devices long regex");
|
||||||
});
|
|
||||||
|
|
||||||
/// Represents a new device with more informations.
|
}
|
||||||
|
|
||||||
|
/// Represents a new device with more informations helded.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct DeviceLong {
|
pub struct DeviceLong {
|
||||||
/// Unique device identifier.
|
/// Unique device identifier.
|
||||||
@@ -44,12 +45,12 @@ impl Display for DeviceLong {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<&[u8]> for DeviceLong {
|
impl TryFrom<Vec<u8>> for DeviceLong {
|
||||||
type Error = RustADBError;
|
type Error = RustADBError;
|
||||||
|
|
||||||
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
|
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
||||||
let groups = DEVICES_LONG_REGEX
|
let groups = DEVICES_LONG_REGEX
|
||||||
.captures(value)
|
.captures(&value)
|
||||||
.ok_or(RustADBError::RegexParsingError)?;
|
.ok_or(RustADBError::RegexParsingError)?;
|
||||||
|
|
||||||
Ok(DeviceLong {
|
Ok(DeviceLong {
|
||||||
@@ -67,13 +68,14 @@ impl TryFrom<&[u8]> for DeviceLong {
|
|||||||
.as_bytes()
|
.as_bytes()
|
||||||
.to_vec(),
|
.to_vec(),
|
||||||
)?)?,
|
)?)?,
|
||||||
usb: match groups.name("usb1") {
|
usb: String::from_utf8(
|
||||||
None => match groups.name("usb2") {
|
groups
|
||||||
None => "Unk".to_string(),
|
.name("usb1")
|
||||||
Some(usb) => String::from_utf8(usb.as_bytes().to_vec())?,
|
.or_else(|| groups.name("usb2"))
|
||||||
},
|
.ok_or(RustADBError::RegexParsingError)?
|
||||||
Some(usb) => String::from_utf8(usb.as_bytes().to_vec())?,
|
.as_bytes()
|
||||||
},
|
.to_vec(),
|
||||||
|
)?,
|
||||||
product: match groups.name("product") {
|
product: match groups.name("product") {
|
||||||
None => "Unk".to_string(),
|
None => "Unk".to_string(),
|
||||||
Some(product) => String::from_utf8(product.as_bytes().to_vec())?,
|
Some(product) => String::from_utf8(product.as_bytes().to_vec())?,
|
||||||
@@ -86,27 +88,15 @@ impl TryFrom<&[u8]> for DeviceLong {
|
|||||||
None => "Unk".to_string(),
|
None => "Unk".to_string(),
|
||||||
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
||||||
},
|
},
|
||||||
transport_id: (str::from_utf8(
|
transport_id: u32::from_str_radix(
|
||||||
groups
|
str::from_utf8(
|
||||||
.name("transport_id")
|
groups
|
||||||
.ok_or(RustADBError::RegexParsingError)?
|
.name("transport_id")
|
||||||
.as_bytes(),
|
.ok_or(RustADBError::RegexParsingError)?
|
||||||
)?)
|
.as_bytes(),
|
||||||
.parse::<u32>()?,
|
)?,
|
||||||
|
16,
|
||||||
|
)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_static_devices_long() {
|
|
||||||
let inputs = [
|
|
||||||
"7a5158f05122195aa device 1-5 product:gts210vewifixx model:SM_T813 device:gts210vewifi transport_id:4",
|
|
||||||
"n311r05e device usb:0-1.5 product:alioth model:M2012K11AC device:alioth transport_id:58",
|
|
||||||
"192.168.100.192:5555 device product:alioth model:M2012K11AC device:alioth transport_id:97",
|
|
||||||
"emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:101",
|
|
||||||
"QQ20131020250511 device 20-4 product:NOH-AN00 model:NOH_AN00 device:HWNOH transport_id:3",
|
|
||||||
];
|
|
||||||
for input in inputs {
|
|
||||||
DeviceLong::try_from(input.as_bytes()).expect(&format!("cannot parse input: '{input}'"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
|
use lazy_static::lazy_static;
|
||||||
use regex::bytes::Regex;
|
use regex::bytes::Regex;
|
||||||
use std::{fmt::Display, str::FromStr, sync::LazyLock};
|
use std::{fmt::Display, str::FromStr};
|
||||||
|
|
||||||
use crate::{DeviceState, RustADBError};
|
use crate::{DeviceState, RustADBError};
|
||||||
|
|
||||||
static DEVICES_REGEX: LazyLock<Regex> =
|
lazy_static! {
|
||||||
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));
|
static ref DEVICES_REGEX: Regex = Regex::new("^(\\S+)\t(\\w+)\n?$").unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
/// Represents a device connected to the ADB server.
|
/// Represents a device connected to the ADB server.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -26,9 +28,7 @@ impl TryFrom<Vec<u8>> for DeviceShort {
|
|||||||
|
|
||||||
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
||||||
// Optional final '\n' is used to match TrackDevices inputs
|
// Optional final '\n' is used to match TrackDevices inputs
|
||||||
let groups = DEVICES_REGEX
|
let groups = DEVICES_REGEX.captures(&value).unwrap();
|
||||||
.captures(&value)
|
|
||||||
.ok_or(RustADBError::RegexParsingError)?;
|
|
||||||
Ok(DeviceShort {
|
Ok(DeviceShort {
|
||||||
identifier: String::from_utf8(
|
identifier: String::from_utf8(
|
||||||
groups
|
groups
|
||||||
@@ -15,22 +15,6 @@ pub enum DeviceState {
|
|||||||
Authorizing,
|
Authorizing,
|
||||||
/// The device is unauthorized.
|
/// The device is unauthorized.
|
||||||
Unauthorized,
|
Unauthorized,
|
||||||
/// Haven't received a response from the device yet.
|
|
||||||
Connecting,
|
|
||||||
/// Insufficient permissions to communicate with the device.
|
|
||||||
NoPerm,
|
|
||||||
/// USB device detached from the adb server (known but not opened/claimed).
|
|
||||||
Detached,
|
|
||||||
/// Device running fastboot OS (fastboot) or userspace fastboot (fastbootd).
|
|
||||||
Bootloader,
|
|
||||||
/// What a device sees from its end of a Transport (adb host).
|
|
||||||
Host,
|
|
||||||
/// Device with bootloader loaded but no ROM OS loaded (adbd).
|
|
||||||
Recovery,
|
|
||||||
/// Device running Android OS Sideload mode (minadbd sideload mode).
|
|
||||||
Sideload,
|
|
||||||
/// Device running Android OS Rescue mode (minadbd rescue mode).
|
|
||||||
Rescue,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for DeviceState {
|
impl Display for DeviceState {
|
||||||
@@ -41,14 +25,6 @@ impl Display for DeviceState {
|
|||||||
DeviceState::NoDevice => write!(f, "no device"),
|
DeviceState::NoDevice => write!(f, "no device"),
|
||||||
DeviceState::Authorizing => write!(f, "authorizing"),
|
DeviceState::Authorizing => write!(f, "authorizing"),
|
||||||
DeviceState::Unauthorized => write!(f, "unauthorized"),
|
DeviceState::Unauthorized => write!(f, "unauthorized"),
|
||||||
DeviceState::Connecting => write!(f, "connecting"),
|
|
||||||
DeviceState::NoPerm => write!(f, "noperm"),
|
|
||||||
DeviceState::Detached => write!(f, "detached"),
|
|
||||||
DeviceState::Bootloader => write!(f, "bootloader"),
|
|
||||||
DeviceState::Host => write!(f, "host"),
|
|
||||||
DeviceState::Recovery => write!(f, "recovery"),
|
|
||||||
DeviceState::Sideload => write!(f, "sideload"),
|
|
||||||
DeviceState::Rescue => write!(f, "rescue"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,14 +40,6 @@ impl FromStr for DeviceState {
|
|||||||
"no device" => Ok(Self::NoDevice),
|
"no device" => Ok(Self::NoDevice),
|
||||||
"authorizing" => Ok(Self::Authorizing),
|
"authorizing" => Ok(Self::Authorizing),
|
||||||
"unauthorized" => Ok(Self::Unauthorized),
|
"unauthorized" => Ok(Self::Unauthorized),
|
||||||
"connecting" => Ok(Self::Connecting),
|
|
||||||
"noperm" => Ok(Self::NoPerm),
|
|
||||||
"detached" => Ok(Self::Detached),
|
|
||||||
"bootloader" => Ok(Self::Bootloader),
|
|
||||||
"host" => Ok(Self::Host),
|
|
||||||
"recovery" => Ok(Self::Recovery),
|
|
||||||
"sideload" => Ok(Self::Sideload),
|
|
||||||
"rescue" => Ok(Self::Rescue),
|
|
||||||
_ => Err(RustADBError::UnknownDeviceState(lowercased)),
|
_ => Err(RustADBError::UnknownDeviceState(lowercased)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
use std::{iter::Map, slice::ChunksExact};
|
|
||||||
|
|
||||||
use byteorder::{ByteOrder, LittleEndian};
|
|
||||||
|
|
||||||
use crate::{Result, RustADBError};
|
|
||||||
|
|
||||||
type U32ChunkIter<'a> = Map<ChunksExact<'a, u8>, fn(&[u8]) -> Result<u32>>;
|
|
||||||
|
|
||||||
fn read_next(chunks: &mut U32ChunkIter) -> Result<u32> {
|
|
||||||
chunks
|
|
||||||
.next()
|
|
||||||
.ok_or(RustADBError::FramebufferConversionError)?
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) struct FrameBufferInfoV1 {
|
|
||||||
pub _bpp: u32,
|
|
||||||
pub size: u32,
|
|
||||||
pub width: u32,
|
|
||||||
pub height: u32,
|
|
||||||
pub _red_offset: u32,
|
|
||||||
pub _red_length: u32,
|
|
||||||
pub _blue_offset: u32,
|
|
||||||
pub _blue_length: u32,
|
|
||||||
pub _green_offset: u32,
|
|
||||||
pub _green_length: u32,
|
|
||||||
pub _alpha_offset: u32,
|
|
||||||
pub _alpha_length: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<[u8; std::mem::size_of::<Self>()]> for FrameBufferInfoV1 {
|
|
||||||
type Error = RustADBError;
|
|
||||||
|
|
||||||
fn try_from(
|
|
||||||
value: [u8; std::mem::size_of::<Self>()],
|
|
||||||
) -> std::result::Result<Self, Self::Error> {
|
|
||||||
let mut chunks: U32ChunkIter = value.chunks_exact(4).map(|v| Ok(LittleEndian::read_u32(v)));
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
_bpp: read_next(&mut chunks)?,
|
|
||||||
size: read_next(&mut chunks)?,
|
|
||||||
width: read_next(&mut chunks)?,
|
|
||||||
height: read_next(&mut chunks)?,
|
|
||||||
_red_offset: read_next(&mut chunks)?,
|
|
||||||
_red_length: read_next(&mut chunks)?,
|
|
||||||
_blue_offset: read_next(&mut chunks)?,
|
|
||||||
_blue_length: read_next(&mut chunks)?,
|
|
||||||
_green_offset: read_next(&mut chunks)?,
|
|
||||||
_green_length: read_next(&mut chunks)?,
|
|
||||||
_alpha_offset: read_next(&mut chunks)?,
|
|
||||||
_alpha_length: read_next(&mut chunks)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) struct FrameBufferInfoV2 {
|
|
||||||
pub _bpp: u32,
|
|
||||||
pub _color_space: u32,
|
|
||||||
pub size: u32,
|
|
||||||
pub width: u32,
|
|
||||||
pub height: u32,
|
|
||||||
pub _red_offset: u32,
|
|
||||||
pub _red_length: u32,
|
|
||||||
pub _blue_offset: u32,
|
|
||||||
pub _blue_length: u32,
|
|
||||||
pub _green_offset: u32,
|
|
||||||
pub _green_length: u32,
|
|
||||||
pub _alpha_offset: u32,
|
|
||||||
pub _alpha_length: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<[u8; std::mem::size_of::<Self>()]> for FrameBufferInfoV2 {
|
|
||||||
type Error = RustADBError;
|
|
||||||
|
|
||||||
fn try_from(
|
|
||||||
value: [u8; std::mem::size_of::<Self>()],
|
|
||||||
) -> std::result::Result<Self, Self::Error> {
|
|
||||||
let mut chunks: U32ChunkIter = value.chunks_exact(4).map(|v| Ok(LittleEndian::read_u32(v)));
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
_bpp: read_next(&mut chunks)?,
|
|
||||||
_color_space: read_next(&mut chunks)?,
|
|
||||||
size: read_next(&mut chunks)?,
|
|
||||||
width: read_next(&mut chunks)?,
|
|
||||||
height: read_next(&mut chunks)?,
|
|
||||||
_red_offset: read_next(&mut chunks)?,
|
|
||||||
_red_length: read_next(&mut chunks)?,
|
|
||||||
_blue_offset: read_next(&mut chunks)?,
|
|
||||||
_blue_length: read_next(&mut chunks)?,
|
|
||||||
_green_offset: read_next(&mut chunks)?,
|
|
||||||
_green_length: read_next(&mut chunks)?,
|
|
||||||
_alpha_offset: read_next(&mut chunks)?,
|
|
||||||
_alpha_length: read_next(&mut chunks)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,21 @@
|
|||||||
|
mod adb_emulator_command;
|
||||||
mod adb_request_status;
|
mod adb_request_status;
|
||||||
mod adb_server_command;
|
mod adb_server_command;
|
||||||
mod adb_stat_response;
|
mod adb_version;
|
||||||
mod framebuffer_info;
|
mod device_long;
|
||||||
|
mod device_short;
|
||||||
|
mod device_state;
|
||||||
mod host_features;
|
mod host_features;
|
||||||
mod list_info;
|
|
||||||
mod reboot_type;
|
mod reboot_type;
|
||||||
mod sync_command;
|
mod sync_command;
|
||||||
|
|
||||||
|
pub(crate) use adb_emulator_command::ADBEmulatorCommand;
|
||||||
pub use adb_request_status::AdbRequestStatus;
|
pub use adb_request_status::AdbRequestStatus;
|
||||||
pub(crate) use adb_server_command::AdbServerCommand;
|
pub(crate) use adb_server_command::AdbServerCommand;
|
||||||
pub use adb_stat_response::AdbStatResponse;
|
pub use adb_version::AdbVersion;
|
||||||
pub(crate) use framebuffer_info::{FrameBufferInfoV1, FrameBufferInfoV2};
|
pub use device_long::DeviceLong;
|
||||||
|
pub use device_short::DeviceShort;
|
||||||
|
pub use device_state::DeviceState;
|
||||||
pub use host_features::HostFeatures;
|
pub use host_features::HostFeatures;
|
||||||
pub use list_info::{ADBListItem, ADBListItemType};
|
|
||||||
pub use reboot_type::RebootType;
|
pub use reboot_type::RebootType;
|
||||||
pub use sync_command::SyncCommand;
|
pub use sync_command::SyncCommand;
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ pub enum RebootType {
|
|||||||
Sideload,
|
Sideload,
|
||||||
/// Same as `Sideload` but reboots after sideloading
|
/// Same as `Sideload` but reboots after sideloading
|
||||||
SideloadAutoReboot,
|
SideloadAutoReboot,
|
||||||
/// Reboots to fastboot
|
|
||||||
Fastboot,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for RebootType {
|
impl Display for RebootType {
|
||||||
@@ -25,7 +23,6 @@ impl Display for RebootType {
|
|||||||
RebootType::Recovery => write!(f, "recovery"),
|
RebootType::Recovery => write!(f, "recovery"),
|
||||||
RebootType::Sideload => write!(f, "sideload"),
|
RebootType::Sideload => write!(f, "sideload"),
|
||||||
RebootType::SideloadAutoReboot => write!(f, "sideload-auto-reboot"),
|
RebootType::SideloadAutoReboot => write!(f, "sideload-auto-reboot"),
|
||||||
RebootType::Fastboot => write!(f, "fastboot"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,38 @@
|
|||||||
use std::{
|
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||||
net::{Ipv4Addr, SocketAddrV4},
|
|
||||||
sync::LazyLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
|
use crate::{ADBTransport, Result, RustADBError, TCPEmulatorTransport};
|
||||||
|
use lazy_static::lazy_static;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
|
||||||
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
use super::ADBServerDevice;
|
||||||
Regex::new("^emulator-(?P<port>\\d+)$").expect("wrong syntax for emulator regex")
|
|
||||||
});
|
lazy_static! {
|
||||||
|
pub static ref EMULATOR_REGEX: Regex =
|
||||||
|
Regex::new("^emulator-(?P<port>\\d+)$").expect("wrong syntax for emulator regex");
|
||||||
|
}
|
||||||
|
|
||||||
/// Represents an emulator connected to the ADB server.
|
/// Represents an emulator connected to the ADB server.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ADBEmulatorDevice {
|
pub struct ADBEmulatorDevice {
|
||||||
/// Unique device identifier.
|
/// Unique device identifier.
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
/// Internal [`TCPEmulatorTransport`]
|
/// Internal [TCPEmulatorTransport]
|
||||||
transport: TCPEmulatorTransport,
|
transport: TCPEmulatorTransport,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBEmulatorDevice {
|
impl ADBEmulatorDevice {
|
||||||
/// Instantiates a new [`ADBEmulatorDevice`]
|
/// Instantiates a new [ADBEmulatorDevice]
|
||||||
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
|
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
|
||||||
let ip_address = match ip_address {
|
let ip_address = match ip_address {
|
||||||
Some(ip_address) => ip_address,
|
Some(ip_address) => ip_address,
|
||||||
None => Ipv4Addr::LOCALHOST,
|
None => Ipv4Addr::new(127, 0, 0, 1),
|
||||||
};
|
};
|
||||||
|
|
||||||
let groups = EMULATOR_REGEX
|
let groups = EMULATOR_REGEX
|
||||||
.captures(&identifier)
|
.captures(&identifier)
|
||||||
.ok_or(RustADBError::DeviceNotFound(format!(
|
.ok_or(RustADBError::DeviceNotFound(format!(
|
||||||
"Device {identifier} is likely not an emulator"
|
"Device {} is likely not an emulator",
|
||||||
|
identifier
|
||||||
)))?;
|
)))?;
|
||||||
|
|
||||||
let port = groups
|
let port = groups
|
||||||
@@ -64,15 +66,10 @@ impl TryFrom<ADBServerDevice> for ADBEmulatorDevice {
|
|||||||
type Error = RustADBError;
|
type Error = RustADBError;
|
||||||
|
|
||||||
fn try_from(value: ADBServerDevice) -> std::result::Result<Self, Self::Error> {
|
fn try_from(value: ADBServerDevice) -> std::result::Result<Self, Self::Error> {
|
||||||
match &value.identifier {
|
ADBEmulatorDevice::new(
|
||||||
Some(device_identifier) => ADBEmulatorDevice::new(
|
value.identifier.clone(),
|
||||||
device_identifier.clone(),
|
Some(*value.get_transport().get_socketaddr().ip()),
|
||||||
Some(*value.transport.get_socketaddr().ip()),
|
)
|
||||||
),
|
|
||||||
None => Err(RustADBError::DeviceNotFound(
|
|
||||||
"cannot connect to an emulator device without knowing its identifier".to_string(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2,71 +2,24 @@ use crate::ADBTransport;
|
|||||||
use crate::Result;
|
use crate::Result;
|
||||||
use crate::RustADBError;
|
use crate::RustADBError;
|
||||||
use crate::TCPServerTransport;
|
use crate::TCPServerTransport;
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::net::SocketAddrV4;
|
use std::net::SocketAddrV4;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
/// Represents an ADB Server
|
/// Represents an ADB Server
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct ADBServer {
|
pub struct ADBServer {
|
||||||
/// Internal [`TcpStream`], lazily initialized
|
/// Internal [TcpStream], lazily initialized
|
||||||
pub(crate) transport: Option<TCPServerTransport>,
|
pub(crate) transport: Option<TCPServerTransport>,
|
||||||
/// Address to connect to
|
/// Address to connect to
|
||||||
pub(crate) socket_addr: Option<SocketAddrV4>,
|
pub(crate) socket_addr: Option<SocketAddrV4>,
|
||||||
/// adb-server start envs
|
|
||||||
pub(crate) envs: HashMap<String, String>,
|
|
||||||
/// Path to adb binary
|
|
||||||
/// If not set, will use adb from PATH
|
|
||||||
pub(crate) adb_path: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBServer {
|
impl ADBServer {
|
||||||
/// Instantiates a new [`ADBServer`]
|
/// Instantiates a new [ADBServer]
|
||||||
#[must_use]
|
|
||||||
pub fn new(address: SocketAddrV4) -> Self {
|
pub fn new(address: SocketAddrV4) -> Self {
|
||||||
Self {
|
Self {
|
||||||
transport: None,
|
transport: None,
|
||||||
socket_addr: Some(address),
|
socket_addr: Some(address),
|
||||||
envs: HashMap::new(),
|
|
||||||
adb_path: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Instantiates a new [`ADBServer`] with a custom adb path
|
|
||||||
#[must_use]
|
|
||||||
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
|
|
||||||
Self {
|
|
||||||
transport: None,
|
|
||||||
socket_addr: Some(address),
|
|
||||||
envs: HashMap::new(),
|
|
||||||
adb_path,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start an instance of `adb-server`
|
|
||||||
pub fn start(envs: &HashMap<String, String>, adb_path: &Option<String>) {
|
|
||||||
// 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 {
|
|
||||||
command.env(env_k, env_v);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
{
|
|
||||||
use std::os::windows::process::CommandExt;
|
|
||||||
// Do not show a prompt on Windows
|
|
||||||
command.creation_flags(0x08000000);
|
|
||||||
}
|
|
||||||
|
|
||||||
let child = command.spawn();
|
|
||||||
match child {
|
|
||||||
Ok(mut child) => {
|
|
||||||
if let Err(e) = child.wait() {
|
|
||||||
log::error!("error while starting adb server: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => log::error!("error while starting adb server: {e}"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +48,16 @@ impl ADBServer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if is_local_ip {
|
if is_local_ip {
|
||||||
Self::start(&self.envs, &self.adb_path);
|
// ADB Server is local, we start it if not already running
|
||||||
|
let child = Command::new("adb").arg("start-server").spawn();
|
||||||
|
match child {
|
||||||
|
Ok(mut child) => {
|
||||||
|
if let Err(e) = child.wait() {
|
||||||
|
log::error!("error while starting adb server: {e}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => log::error!("error while starting adb server: {e}"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
transport.connect()?;
|
transport.connect()?;
|
||||||
@@ -107,7 +69,7 @@ impl ADBServer {
|
|||||||
|
|
||||||
impl Drop for ADBServer {
|
impl Drop for ADBServer {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if let Some(transport) = &mut self.transport {
|
if let Some(ref mut transport) = &mut self.transport {
|
||||||
let _ = transport.disconnect();
|
let _ = transport.disconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
49
adb_client/src/server/adb_server_device.rs
Normal file
49
adb_client/src/server/adb_server_device.rs
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
use crate::{ADBTransport, Result, TCPServerTransport};
|
||||||
|
use std::net::SocketAddrV4;
|
||||||
|
|
||||||
|
/// Represents a device connected to the ADB server.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ADBServerDevice {
|
||||||
|
/// Unique device identifier.
|
||||||
|
pub identifier: String,
|
||||||
|
/// Internal [TCPServerTransport]
|
||||||
|
transport: TCPServerTransport,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Instantiates a new [ADBServerDevice]
|
||||||
|
pub fn new(identifier: String, socket_addr: Option<SocketAddrV4>) -> Self {
|
||||||
|
let transport = if let Some(addr) = socket_addr {
|
||||||
|
TCPServerTransport::new(addr)
|
||||||
|
} else {
|
||||||
|
TCPServerTransport::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
Self {
|
||||||
|
identifier,
|
||||||
|
transport,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_transport(&self) -> &TCPServerTransport {
|
||||||
|
&self.transport
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_transport_mut(&mut self) -> &mut TCPServerTransport {
|
||||||
|
&mut self.transport
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connect to underlying transport
|
||||||
|
pub(crate) fn connect(&mut self) -> Result<&mut TCPServerTransport> {
|
||||||
|
self.transport.connect()?;
|
||||||
|
|
||||||
|
Ok(self.get_transport_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ADBServerDevice {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Best effort here
|
||||||
|
let _ = self.transport.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
use std::io::BufRead;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
ADBServer, MDNSServices, Result, models::AdbServerCommand, server::models::MDNSBackend,
|
|
||||||
};
|
|
||||||
|
|
||||||
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";
|
|
||||||
|
|
||||||
impl ADBServer {
|
|
||||||
/// Check if mdns discovery is available
|
|
||||||
pub fn mdns_check(&mut self) -> Result<bool> {
|
|
||||||
let response = self
|
|
||||||
.connect()?
|
|
||||||
.proxy_connection(AdbServerCommand::MDNSCheck, true)?;
|
|
||||||
|
|
||||||
match String::from_utf8(response) {
|
|
||||||
Ok(s) if s.starts_with("mdns daemon version") => Ok(true),
|
|
||||||
Ok(_) => Ok(false),
|
|
||||||
Err(e) => Err(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// List all discovered mdns services
|
|
||||||
pub fn mdns_services(&mut self) -> Result<Vec<MDNSServices>> {
|
|
||||||
let services = self
|
|
||||||
.connect()?
|
|
||||||
.proxy_connection(AdbServerCommand::MDNSServices, true)?;
|
|
||||||
|
|
||||||
let mut vec_services: Vec<MDNSServices> = vec![];
|
|
||||||
for service in services.lines() {
|
|
||||||
match service {
|
|
||||||
Ok(service) => {
|
|
||||||
vec_services.push(MDNSServices::try_from(service.as_bytes())?);
|
|
||||||
}
|
|
||||||
Err(e) => log::error!("{e}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(vec_services)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if specified backend mdns service is used, otherwise restart adb server with envs
|
|
||||||
pub fn mdns_force_backend(&mut self, backend: MDNSBackend) -> Result<()> {
|
|
||||||
let server_status = self.server_status()?;
|
|
||||||
if server_status.mdns_backend != backend {
|
|
||||||
self.kill()?;
|
|
||||||
self.envs.insert(
|
|
||||||
OPENSCREEN_MDNS_BACKEND.to_string(),
|
|
||||||
(if backend == MDNSBackend::OpenScreen {
|
|
||||||
"1"
|
|
||||||
} else {
|
|
||||||
"0"
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
);
|
|
||||||
self.connect()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
use crate::{ADBServer, Result, models::AdbServerCommand};
|
|
||||||
|
|
||||||
impl ADBServer {
|
|
||||||
/// Reconnect the device
|
|
||||||
pub fn reconnect_offline(&mut self) -> Result<()> {
|
|
||||||
self.connect()?
|
|
||||||
.proxy_connection(AdbServerCommand::ReconnectOffline, false)
|
|
||||||
.map(|_| ())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
use crate::{ADBServer, Result, models::AdbServerCommand, server::models::ServerStatus};
|
|
||||||
|
|
||||||
impl ADBServer {
|
|
||||||
/// Check ADB server status
|
|
||||||
pub fn server_status(&mut self) -> Result<ServerStatus> {
|
|
||||||
let status = self
|
|
||||||
.connect()?
|
|
||||||
.proxy_connection(AdbServerCommand::ServerStatus, true)?;
|
|
||||||
|
|
||||||
ServerStatus::try_from(status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
ADBServer, Result, WaitForDeviceState, WaitForDeviceTransport, models::AdbServerCommand,
|
|
||||||
};
|
|
||||||
|
|
||||||
impl ADBServer {
|
|
||||||
/// Wait for a device in a given state to be connected
|
|
||||||
pub fn wait_for_device(
|
|
||||||
&mut self,
|
|
||||||
state: WaitForDeviceState,
|
|
||||||
transport: Option<WaitForDeviceTransport>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let transport = transport.unwrap_or_default();
|
|
||||||
|
|
||||||
self.connect()?
|
|
||||||
.send_adb_request(AdbServerCommand::WaitForDevice(state, transport))?;
|
|
||||||
|
|
||||||
// Server should respond with an "OKAY" response
|
|
||||||
self.get_transport()?.read_adb_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
176
adb_client/src/server/device_commands/framebuffer.rs
Normal file
176
adb_client/src/server/device_commands/framebuffer.rs
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
use std::{io::Read, iter::Map, path::Path, slice::ChunksExact};
|
||||||
|
|
||||||
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
|
use image::{ImageBuffer, Rgba};
|
||||||
|
|
||||||
|
use crate::{models::AdbServerCommand, utils, ADBServerDevice, Result, RustADBError};
|
||||||
|
|
||||||
|
type U32ChunkIter<'a> = Map<ChunksExact<'a, u8>, fn(&[u8]) -> Result<u32>>;
|
||||||
|
|
||||||
|
fn read_next(chunks: &mut U32ChunkIter) -> Result<u32> {
|
||||||
|
chunks
|
||||||
|
.next()
|
||||||
|
.ok_or(RustADBError::FramebufferConversionError)?
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct FrameBufferInfoV1 {
|
||||||
|
pub _bpp: u32,
|
||||||
|
pub size: u32,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub _red_offset: u32,
|
||||||
|
pub _red_length: u32,
|
||||||
|
pub _blue_offset: u32,
|
||||||
|
pub _blue_length: u32,
|
||||||
|
pub _green_offset: u32,
|
||||||
|
pub _green_length: u32,
|
||||||
|
pub _alpha_offset: u32,
|
||||||
|
pub _alpha_length: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<[u8; std::mem::size_of::<Self>()]> for FrameBufferInfoV1 {
|
||||||
|
type Error = RustADBError;
|
||||||
|
|
||||||
|
fn try_from(
|
||||||
|
value: [u8; std::mem::size_of::<Self>()],
|
||||||
|
) -> std::result::Result<Self, Self::Error> {
|
||||||
|
let mut chunks: U32ChunkIter = value.chunks_exact(4).map(utils::u32_from_le);
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
_bpp: read_next(&mut chunks)?,
|
||||||
|
size: read_next(&mut chunks)?,
|
||||||
|
width: read_next(&mut chunks)?,
|
||||||
|
height: read_next(&mut chunks)?,
|
||||||
|
_red_offset: read_next(&mut chunks)?,
|
||||||
|
_red_length: read_next(&mut chunks)?,
|
||||||
|
_blue_offset: read_next(&mut chunks)?,
|
||||||
|
_blue_length: read_next(&mut chunks)?,
|
||||||
|
_green_offset: read_next(&mut chunks)?,
|
||||||
|
_green_length: read_next(&mut chunks)?,
|
||||||
|
_alpha_offset: read_next(&mut chunks)?,
|
||||||
|
_alpha_length: read_next(&mut chunks)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct FrameBufferInfoV2 {
|
||||||
|
pub _bpp: u32,
|
||||||
|
pub _color_space: u32,
|
||||||
|
pub size: u32,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub _red_offset: u32,
|
||||||
|
pub _red_length: u32,
|
||||||
|
pub _blue_offset: u32,
|
||||||
|
pub _blue_length: u32,
|
||||||
|
pub _green_offset: u32,
|
||||||
|
pub _green_length: u32,
|
||||||
|
pub _alpha_offset: u32,
|
||||||
|
pub _alpha_length: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<[u8; std::mem::size_of::<Self>()]> for FrameBufferInfoV2 {
|
||||||
|
type Error = RustADBError;
|
||||||
|
|
||||||
|
fn try_from(
|
||||||
|
value: [u8; std::mem::size_of::<Self>()],
|
||||||
|
) -> std::result::Result<Self, Self::Error> {
|
||||||
|
let mut chunks: U32ChunkIter = value.chunks_exact(4).map(utils::u32_from_le);
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
_bpp: read_next(&mut chunks)?,
|
||||||
|
_color_space: read_next(&mut chunks)?,
|
||||||
|
size: read_next(&mut chunks)?,
|
||||||
|
width: read_next(&mut chunks)?,
|
||||||
|
height: read_next(&mut chunks)?,
|
||||||
|
_red_offset: read_next(&mut chunks)?,
|
||||||
|
_red_length: read_next(&mut chunks)?,
|
||||||
|
_blue_offset: read_next(&mut chunks)?,
|
||||||
|
_blue_length: read_next(&mut chunks)?,
|
||||||
|
_green_offset: read_next(&mut chunks)?,
|
||||||
|
_green_length: read_next(&mut chunks)?,
|
||||||
|
_alpha_offset: read_next(&mut chunks)?,
|
||||||
|
_alpha_length: read_next(&mut chunks)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Dump framebuffer of this device
|
||||||
|
/// Big help from source code (https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp)
|
||||||
|
pub fn framebuffer<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
|
||||||
|
let img = self.framebuffer_inner()?;
|
||||||
|
Ok(img.save(path.as_ref())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inner method requesting framebuffer from Android device
|
||||||
|
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
|
||||||
|
let serial: String = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::FrameBuffer)?;
|
||||||
|
|
||||||
|
let version = self
|
||||||
|
.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_u32::<LittleEndian>()?;
|
||||||
|
|
||||||
|
match version {
|
||||||
|
// RGBA_8888
|
||||||
|
1 => {
|
||||||
|
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV1>()];
|
||||||
|
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut buf)?;
|
||||||
|
|
||||||
|
let h: FrameBufferInfoV1 = buf.try_into()?;
|
||||||
|
|
||||||
|
let mut data = vec![
|
||||||
|
0_u8;
|
||||||
|
h.size
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| RustADBError::ConversionError)?
|
||||||
|
];
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut data)?;
|
||||||
|
|
||||||
|
Ok(
|
||||||
|
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(h.width, h.height, data)
|
||||||
|
.ok_or_else(|| RustADBError::FramebufferConversionError)?,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// RGBX_8888
|
||||||
|
2 => {
|
||||||
|
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV2>()];
|
||||||
|
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut buf)?;
|
||||||
|
|
||||||
|
let h: FrameBufferInfoV2 = buf.try_into()?;
|
||||||
|
|
||||||
|
let mut data = vec![
|
||||||
|
0_u8;
|
||||||
|
h.size
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| RustADBError::ConversionError)?
|
||||||
|
];
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut data)?;
|
||||||
|
|
||||||
|
Ok(
|
||||||
|
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(h.width, h.height, data)
|
||||||
|
.ok_or_else(|| RustADBError::FramebufferConversionError)?,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
v => unimplemented!("Version {} not implemented", v),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
ADBServerDevice, Result,
|
|
||||||
models::{AdbServerCommand, HostFeatures},
|
models::{AdbServerCommand, HostFeatures},
|
||||||
|
ADBServerDevice, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
impl ADBServerDevice {
|
impl ADBServerDevice {
|
||||||
/// Lists available ADB server features.
|
/// Lists available ADB server features.
|
||||||
pub fn host_features(&mut self) -> Result<Vec<HostFeatures>> {
|
pub fn host_features(&mut self) -> Result<Vec<HostFeatures>> {
|
||||||
self.set_serial_transport()?;
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
let features = self
|
let features = self
|
||||||
.transport
|
.get_transport_mut()
|
||||||
.proxy_connection(AdbServerCommand::HostFeatures, true)?;
|
.proxy_connection(AdbServerCommand::HostFeatures, true)?;
|
||||||
|
|
||||||
Ok(features
|
Ok(features
|
||||||
77
adb_client/src/server/device_commands/list.rs
Normal file
77
adb_client/src/server/device_commands/list.rs
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
use crate::{
|
||||||
|
models::{AdbServerCommand, SyncCommand},
|
||||||
|
ADBServerDevice, Result,
|
||||||
|
};
|
||||||
|
use byteorder::{ByteOrder, LittleEndian};
|
||||||
|
use std::{
|
||||||
|
io::{Read, Write},
|
||||||
|
str,
|
||||||
|
};
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Lists files in [path] on the device.
|
||||||
|
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<()> {
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
|
// Set device in SYNC mode
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::Sync)?;
|
||||||
|
|
||||||
|
// Send a list command
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_sync_request(SyncCommand::List)?;
|
||||||
|
|
||||||
|
self.handle_list_command(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// This command does not seem to work correctly. The devices I test it on just resturn
|
||||||
|
// 'DONE' directly without listing anything.
|
||||||
|
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> {
|
||||||
|
let mut len_buf = [0_u8; 4];
|
||||||
|
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
|
||||||
|
|
||||||
|
// 4 bytes of command name is already sent by send_sync_request
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&len_buf)?;
|
||||||
|
|
||||||
|
// List send the string of the directory to list, and then the server send a list of files
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(path.as_ref().to_string().as_bytes())?;
|
||||||
|
|
||||||
|
// Reads returned status code from ADB server
|
||||||
|
let mut response = [0_u8; 4];
|
||||||
|
loop {
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut response)?;
|
||||||
|
match str::from_utf8(response.as_ref())? {
|
||||||
|
"DENT" => {
|
||||||
|
// TODO: Move this to a struct that extract this data, but as the device
|
||||||
|
// I test this on does not return anything, I can't test it.
|
||||||
|
let mut file_mod = [0_u8; 4];
|
||||||
|
let mut file_size = [0_u8; 4];
|
||||||
|
let mut mod_time = [0_u8; 4];
|
||||||
|
let mut name_len = [0_u8; 4];
|
||||||
|
|
||||||
|
let mut connection = self.get_transport_mut().get_raw_connection()?;
|
||||||
|
connection.read_exact(&mut file_mod)?;
|
||||||
|
connection.read_exact(&mut file_size)?;
|
||||||
|
connection.read_exact(&mut mod_time)?;
|
||||||
|
connection.read_exact(&mut name_len)?;
|
||||||
|
|
||||||
|
let name_len = LittleEndian::read_u32(&name_len);
|
||||||
|
let mut name_buf = vec![0_u8; name_len as usize];
|
||||||
|
connection.read_exact(&mut name_buf)?;
|
||||||
|
}
|
||||||
|
"DONE" => {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
x => log::error!("Got an unknown response {}", x),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
56
adb_client/src/server/device_commands/logcat.rs
Normal file
56
adb_client/src/server/device_commands/logcat.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
use std::io::{self, Write};
|
||||||
|
|
||||||
|
use crate::{ADBServerDevice, Result};
|
||||||
|
|
||||||
|
struct LogFilter<W: Write> {
|
||||||
|
writer: W,
|
||||||
|
buffer: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Write> LogFilter<W> {
|
||||||
|
pub fn new(writer: W) -> Self {
|
||||||
|
LogFilter {
|
||||||
|
writer,
|
||||||
|
buffer: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn should_write(&self, _line: &[u8]) -> bool {
|
||||||
|
// Can implement checks here to ensure if logs have to be written
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Write> Write for LogFilter<W> {
|
||||||
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
|
self.buffer.extend_from_slice(buf);
|
||||||
|
|
||||||
|
let buf_clone = self.buffer.clone();
|
||||||
|
let mut lines = buf_clone.split_inclusive(|&byte| byte == b'\n').peekable();
|
||||||
|
|
||||||
|
while let Some(line) = lines.next() {
|
||||||
|
if lines.peek().is_some() {
|
||||||
|
if self.should_write(line) {
|
||||||
|
self.writer.write_all(line)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// This is the last (unfinished) element, we keep it for next round
|
||||||
|
self.buffer = line.to_vec();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(buf.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
self.writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Get logs from device
|
||||||
|
pub fn get_logs<W: Write>(&mut self, output: W) -> Result<()> {
|
||||||
|
self.shell_command(["exec logcat"], LogFilter::new(output))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,10 @@
|
|||||||
mod forward;
|
|
||||||
mod framebuffer;
|
mod framebuffer;
|
||||||
mod host_features;
|
mod host_features;
|
||||||
mod install;
|
|
||||||
mod list;
|
mod list;
|
||||||
mod logcat;
|
mod logcat;
|
||||||
mod reboot;
|
mod reboot;
|
||||||
mod reconnect;
|
|
||||||
mod recv;
|
mod recv;
|
||||||
mod reverse;
|
|
||||||
mod send;
|
mod send;
|
||||||
|
mod shell;
|
||||||
mod stat;
|
mod stat;
|
||||||
mod tcpip;
|
|
||||||
mod transport;
|
mod transport;
|
||||||
mod uninstall;
|
|
||||||
mod usb;
|
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
ADBServerDevice, Result,
|
|
||||||
models::{AdbServerCommand, RebootType},
|
models::{AdbServerCommand, RebootType},
|
||||||
|
ADBServerDevice, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
impl ADBServerDevice {
|
impl ADBServerDevice {
|
||||||
/// Reboots the device
|
/// Reboots the device
|
||||||
pub fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
|
pub fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
|
||||||
self.set_serial_transport()?;
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
self.transport
|
self.get_transport_mut()
|
||||||
.proxy_connection(AdbServerCommand::Reboot(reboot_type), false)
|
.proxy_connection(AdbServerCommand::Reboot(reboot_type), false)
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
85
adb_client/src/server/device_commands/recv.rs
Normal file
85
adb_client/src/server/device_commands/recv.rs
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
use crate::{
|
||||||
|
models::{AdbServerCommand, SyncCommand},
|
||||||
|
ADBServerDevice, Result, RustADBError,
|
||||||
|
};
|
||||||
|
use byteorder::{ByteOrder, LittleEndian};
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Receives [path] to [stream] from the device.
|
||||||
|
pub fn recv<A: AsRef<str>>(&mut self, path: A, stream: &mut dyn Write) -> Result<()> {
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
|
// Set device in SYNC mode
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::Sync)?;
|
||||||
|
|
||||||
|
// Send a recv command
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_sync_request(SyncCommand::Recv)?;
|
||||||
|
|
||||||
|
self.handle_recv_command(path, stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_recv_command<S: AsRef<str>>(
|
||||||
|
&mut self,
|
||||||
|
from: S,
|
||||||
|
output: &mut dyn Write,
|
||||||
|
) -> Result<()> {
|
||||||
|
// First send 8 byte common header
|
||||||
|
let mut len_buf = [0_u8; 4];
|
||||||
|
LittleEndian::write_u32(&mut len_buf, from.as_ref().len() as u32);
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&len_buf)?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(from.as_ref().as_bytes())?;
|
||||||
|
|
||||||
|
// Then we receive the byte data in chunks of up to 64k
|
||||||
|
// Chunk looks like 'DATA' <length> <data>
|
||||||
|
let mut buffer = [0_u8; 64 * 1024]; // Should this be Boxed?
|
||||||
|
let mut data_header = [0_u8; 4]; // DATA
|
||||||
|
loop {
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut data_header)?;
|
||||||
|
// Check if data_header is DATA or DONE or FAIL
|
||||||
|
match &data_header {
|
||||||
|
b"DATA" => {
|
||||||
|
// Handle received data
|
||||||
|
let length: usize = self
|
||||||
|
.get_transport_mut()
|
||||||
|
.get_body_length()?
|
||||||
|
.try_into()
|
||||||
|
.unwrap();
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut buffer[..length])?;
|
||||||
|
output.write_all(&buffer[..length])?;
|
||||||
|
}
|
||||||
|
b"DONE" => break, // We're done here
|
||||||
|
b"FAIL" => {
|
||||||
|
// Handle fail
|
||||||
|
let length: usize = self
|
||||||
|
.get_transport_mut()
|
||||||
|
.get_body_length()?
|
||||||
|
.try_into()
|
||||||
|
.unwrap();
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut buffer[..length])?;
|
||||||
|
Err(RustADBError::ADBRequestFailed(String::from_utf8(
|
||||||
|
buffer[..length].to_vec(),
|
||||||
|
)?))?;
|
||||||
|
}
|
||||||
|
_ => panic!("Unknown response from device {:#?}", data_header),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connection should've left SYNC by now
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
110
adb_client/src/server/device_commands/send.rs
Normal file
110
adb_client/src/server/device_commands/send.rs
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
use crate::{
|
||||||
|
models::{AdbRequestStatus, AdbServerCommand, SyncCommand},
|
||||||
|
ADBServerDevice, Result, RustADBError,
|
||||||
|
};
|
||||||
|
use byteorder::{ByteOrder, LittleEndian};
|
||||||
|
use std::{
|
||||||
|
convert::TryInto,
|
||||||
|
io::{Read, Write},
|
||||||
|
str::{self, FromStr},
|
||||||
|
time::SystemTime,
|
||||||
|
};
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Send [stream] to [path] on the device.
|
||||||
|
pub fn send<A: AsRef<str>>(&mut self, stream: &mut dyn Read, path: A) -> Result<()> {
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
|
// Set device in SYNC mode
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::Sync)?;
|
||||||
|
|
||||||
|
// Send a send command
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_sync_request(SyncCommand::Send)?;
|
||||||
|
|
||||||
|
self.handle_send_command(stream, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_send_command<S: AsRef<str>>(&mut self, input: &mut dyn Read, to: S) -> Result<()> {
|
||||||
|
// Append the permission flags to the filename
|
||||||
|
let to = to.as_ref().to_string() + ",0777";
|
||||||
|
|
||||||
|
// The name of command is already sent by get_transport()?.send_sync_request
|
||||||
|
let mut len_buf = [0_u8; 4];
|
||||||
|
LittleEndian::write_u32(&mut len_buf, to.len() as u32);
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&len_buf)?;
|
||||||
|
|
||||||
|
// Send appends the filemode to the string sent
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(to.as_bytes())?;
|
||||||
|
|
||||||
|
// Then we send the byte data in chunks of up to 64k
|
||||||
|
// Chunk looks like 'DATA' <length> <data>
|
||||||
|
let mut buffer = [0_u8; 64 * 1024];
|
||||||
|
loop {
|
||||||
|
let bytes_read = input.read(&mut buffer)?;
|
||||||
|
if bytes_read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let mut chunk_len_buf = [0_u8; 4];
|
||||||
|
LittleEndian::write_u32(&mut chunk_len_buf, bytes_read as u32);
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(b"DATA")?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&chunk_len_buf)?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&buffer[..bytes_read])?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// When we are done sending, we send 'DONE' <last modified time>
|
||||||
|
// Re-use len_buf to send the last modified time
|
||||||
|
let last_modified = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
|
||||||
|
Ok(n) => n,
|
||||||
|
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
|
||||||
|
};
|
||||||
|
LittleEndian::write_u32(&mut len_buf, last_modified.as_secs() as u32);
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(b"DONE")?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&len_buf)?;
|
||||||
|
|
||||||
|
// We expect 'OKAY' response from this
|
||||||
|
let mut request_status = [0; 4];
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut request_status)?;
|
||||||
|
|
||||||
|
match AdbRequestStatus::from_str(str::from_utf8(request_status.as_ref())?)? {
|
||||||
|
AdbRequestStatus::Fail => {
|
||||||
|
// We can keep reading to get further details
|
||||||
|
let length = self.get_transport_mut().get_body_length()?;
|
||||||
|
|
||||||
|
let mut body = vec![
|
||||||
|
0;
|
||||||
|
length
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| RustADBError::ConversionError)?
|
||||||
|
];
|
||||||
|
if length > 0 {
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut body)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(RustADBError::ADBRequestFailed(String::from_utf8(body)?))
|
||||||
|
}
|
||||||
|
AdbRequestStatus::Okay => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
155
adb_client/src/server/device_commands/shell.rs
Normal file
155
adb_client/src/server/device_commands/shell.rs
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
use std::{
|
||||||
|
io::{self, Read, Write},
|
||||||
|
sync::mpsc,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
adb_termios::ADBTermios,
|
||||||
|
models::{AdbServerCommand, HostFeatures},
|
||||||
|
ADBServerDevice, Result, RustADBError,
|
||||||
|
};
|
||||||
|
|
||||||
|
const STDIN: Token = Token(0);
|
||||||
|
const BUFFER_SIZE: usize = 512;
|
||||||
|
const POLL_DURATION: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
fn setup_poll_stdin() -> std::result::Result<Poll, io::Error> {
|
||||||
|
let poll = Poll::new()?;
|
||||||
|
let stdin_fd = 0;
|
||||||
|
poll.registry()
|
||||||
|
.register(&mut SourceFd(&stdin_fd), STDIN, Interest::READABLE)?;
|
||||||
|
|
||||||
|
Ok(poll)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
/// Runs 'command' in a shell on the device, and write its output and error streams into [`output`].
|
||||||
|
pub fn shell_command<S: ToString, W: Write>(
|
||||||
|
&mut self,
|
||||||
|
command: impl IntoIterator<Item = S>,
|
||||||
|
mut output: W,
|
||||||
|
) -> Result<()> {
|
||||||
|
let supported_features = self.host_features()?;
|
||||||
|
if !supported_features.contains(&HostFeatures::ShellV2)
|
||||||
|
&& !supported_features.contains(&HostFeatures::Cmd)
|
||||||
|
{
|
||||||
|
return Err(RustADBError::ADBShellNotSupported);
|
||||||
|
}
|
||||||
|
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::ShellCommand(
|
||||||
|
command
|
||||||
|
.into_iter()
|
||||||
|
.map(|v| v.to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" "),
|
||||||
|
))?;
|
||||||
|
|
||||||
|
const BUFFER_SIZE: usize = 4096;
|
||||||
|
loop {
|
||||||
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
|
match self
|
||||||
|
.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read(&mut buffer)
|
||||||
|
{
|
||||||
|
Ok(size) => {
|
||||||
|
if size == 0 {
|
||||||
|
return Ok(());
|
||||||
|
} else {
|
||||||
|
output.write_all(&buffer[..size])?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(RustADBError::IOError(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts an interactive shell session on the device. Redirects stdin/stdout/stderr as appropriate.
|
||||||
|
pub fn shell(&mut self) -> Result<()> {
|
||||||
|
let mut adb_termios = ADBTermios::new(std::io::stdin())?;
|
||||||
|
adb_termios.set_adb_termios()?;
|
||||||
|
|
||||||
|
self.connect()?.get_raw_connection()?.set_nodelay(true)?;
|
||||||
|
|
||||||
|
// TODO: FORWARD CTRL+C !!
|
||||||
|
|
||||||
|
let supported_features = self.host_features()?;
|
||||||
|
if !supported_features.contains(&HostFeatures::ShellV2)
|
||||||
|
&& !supported_features.contains(&HostFeatures::Cmd)
|
||||||
|
{
|
||||||
|
return Err(RustADBError::ADBShellNotSupported);
|
||||||
|
}
|
||||||
|
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::Shell)?;
|
||||||
|
|
||||||
|
// let read_stream = Arc::new(self.tcp_stream);
|
||||||
|
let mut read_stream = self.get_transport_mut().get_raw_connection()?.try_clone()?;
|
||||||
|
|
||||||
|
let (tx, rx) = mpsc::channel::<bool>();
|
||||||
|
|
||||||
|
let mut write_stream = read_stream.try_clone()?;
|
||||||
|
|
||||||
|
// Reading thread
|
||||||
|
std::thread::spawn(move || -> Result<()> {
|
||||||
|
loop {
|
||||||
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
|
match read_stream.read(&mut buffer) {
|
||||||
|
Ok(0) => {
|
||||||
|
let _ = tx.send(true);
|
||||||
|
read_stream.shutdown(std::net::Shutdown::Both)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(size) => {
|
||||||
|
std::io::stdout().write_all(&buffer[..size])?;
|
||||||
|
std::io::stdout().flush()?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Err(RustADBError::IOError(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut buf = [0; BUFFER_SIZE];
|
||||||
|
let mut events = Events::with_capacity(1);
|
||||||
|
|
||||||
|
let mut poll = setup_poll_stdin()?;
|
||||||
|
|
||||||
|
// Polling either by checking that reading socket hasn't been closed, and if is there is something to read on stdin.
|
||||||
|
loop {
|
||||||
|
poll.poll(&mut events, Some(POLL_DURATION))?;
|
||||||
|
match rx.try_recv() {
|
||||||
|
Ok(_) | Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
|
||||||
|
Err(mpsc::TryRecvError::Empty) => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
for event in events.iter() {
|
||||||
|
match event.token() {
|
||||||
|
STDIN => {
|
||||||
|
let size = match std::io::stdin().read(&mut buf) {
|
||||||
|
Ok(0) => return Ok(()),
|
||||||
|
Ok(size) => size,
|
||||||
|
Err(_) => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
write_stream.write_all(&buf[0..size])?;
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
99
adb_client/src/server/device_commands/stat.rs
Normal file
99
adb_client/src/server/device_commands/stat.rs
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
use std::{
|
||||||
|
fmt::Display,
|
||||||
|
io::{Read, Write},
|
||||||
|
time::{Duration, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
|
use byteorder::{ByteOrder, LittleEndian};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
models::{AdbServerCommand, SyncCommand},
|
||||||
|
ADBServerDevice, Result, RustADBError,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct AdbStatResponse {
|
||||||
|
pub file_perm: u32,
|
||||||
|
pub file_size: u32,
|
||||||
|
pub mod_time: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<[u8; 12]> for AdbStatResponse {
|
||||||
|
fn from(value: [u8; 12]) -> Self {
|
||||||
|
Self {
|
||||||
|
file_perm: LittleEndian::read_u32(&value[0..4]),
|
||||||
|
file_size: LittleEndian::read_u32(&value[4..8]),
|
||||||
|
mod_time: LittleEndian::read_u32(&value[8..]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for AdbStatResponse {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let d = UNIX_EPOCH + Duration::from_secs(self.mod_time.into());
|
||||||
|
// Create DateTime from SystemTime
|
||||||
|
let datetime = DateTime::<Utc>::from(d);
|
||||||
|
|
||||||
|
writeln!(f, "File permissions: {}", self.file_perm)?;
|
||||||
|
writeln!(f, "File size: {} bytes", self.file_size)?;
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"Modification time: {}",
|
||||||
|
datetime.format("%Y-%m-%d %H:%M:%S.%f %Z")
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBServerDevice {
|
||||||
|
fn handle_stat_command<S: AsRef<str>>(&mut self, path: S) -> Result<AdbStatResponse> {
|
||||||
|
let mut len_buf = [0_u8; 4];
|
||||||
|
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
|
||||||
|
|
||||||
|
// 4 bytes of command name is already sent by send_sync_request
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(&len_buf)?;
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.write_all(path.as_ref().to_string().as_bytes())?;
|
||||||
|
|
||||||
|
// Reads returned status code from ADB server
|
||||||
|
let mut response = [0_u8; 4];
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut response)?;
|
||||||
|
match std::str::from_utf8(response.as_ref())? {
|
||||||
|
"STAT" => {
|
||||||
|
let mut data = [0_u8; 12];
|
||||||
|
self.get_transport_mut()
|
||||||
|
.get_raw_connection()?
|
||||||
|
.read_exact(&mut data)?;
|
||||||
|
|
||||||
|
Ok(data.into())
|
||||||
|
}
|
||||||
|
x => Err(RustADBError::UnknownResponseType(format!(
|
||||||
|
"Unknown response {}",
|
||||||
|
x
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stat file given as [path] on the device.
|
||||||
|
pub fn stat<A: AsRef<str>>(&mut self, path: A) -> Result<AdbStatResponse> {
|
||||||
|
let serial = self.identifier.clone();
|
||||||
|
self.connect()?
|
||||||
|
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
|
||||||
|
|
||||||
|
// Set device in SYNC mode
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_adb_request(AdbServerCommand::Sync)?;
|
||||||
|
|
||||||
|
// Send a "Stat" command
|
||||||
|
self.get_transport_mut()
|
||||||
|
.send_sync_request(SyncCommand::Stat)?;
|
||||||
|
|
||||||
|
self.handle_stat_command(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{ADBServerDevice, Result, models::AdbServerCommand};
|
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
|
||||||
|
|
||||||
impl ADBServerDevice {
|
impl ADBServerDevice {
|
||||||
/// Asks ADB server to switch the connection to either the device or emulator connect to/running on the host. Will fail if there is more than one such device/emulator available.
|
/// Asks ADB server to switch the connection to either the device or emulator connect to/running on the host. Will fail if there is more than one such device/emulator available.
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
|
mod adb_emulator_device;
|
||||||
mod adb_server;
|
mod adb_server;
|
||||||
mod commands;
|
mod adb_server_device;
|
||||||
mod models;
|
mod device_commands;
|
||||||
|
mod server_commands;
|
||||||
|
|
||||||
|
pub use adb_emulator_device::ADBEmulatorDevice;
|
||||||
pub use adb_server::ADBServer;
|
pub use adb_server::ADBServer;
|
||||||
pub use models::*;
|
pub use adb_server_device::ADBServerDevice;
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
use regex::bytes::Regex;
|
|
||||||
use std::net::SocketAddrV4;
|
|
||||||
use std::sync::LazyLock;
|
|
||||||
use std::{fmt::Display, str::FromStr};
|
|
||||||
|
|
||||||
use crate::RustADBError;
|
|
||||||
|
|
||||||
static MDNS_SERVICES_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
|
||||||
Regex::new("^(\\S+)\t(\\S+)\t([\\d\\.]+:\\d+)\n?$").expect("Cannot build mdns services regex")
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Represents MDNS Services
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct MDNSServices {
|
|
||||||
/// Service name
|
|
||||||
pub service_name: String,
|
|
||||||
/// Reg type
|
|
||||||
pub reg_type: String,
|
|
||||||
/// IP addr with port
|
|
||||||
pub socket_v4: SocketAddrV4,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for MDNSServices {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"{}\t{}\t{}",
|
|
||||||
self.service_name, self.reg_type, self.socket_v4
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<&[u8]> for MDNSServices {
|
|
||||||
type Error = RustADBError;
|
|
||||||
|
|
||||||
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
|
|
||||||
let groups = MDNS_SERVICES_REGEX
|
|
||||||
.captures(value)
|
|
||||||
.ok_or(RustADBError::RegexParsingError)?;
|
|
||||||
Ok(MDNSServices {
|
|
||||||
service_name: String::from_utf8(
|
|
||||||
groups
|
|
||||||
.get(1)
|
|
||||||
.ok_or(RustADBError::RegexParsingError)?
|
|
||||||
.as_bytes()
|
|
||||||
.to_vec(),
|
|
||||||
)?,
|
|
||||||
reg_type: String::from_utf8(
|
|
||||||
groups
|
|
||||||
.get(2)
|
|
||||||
.ok_or(RustADBError::RegexParsingError)?
|
|
||||||
.as_bytes()
|
|
||||||
.to_vec(),
|
|
||||||
)?,
|
|
||||||
socket_v4: SocketAddrV4::from_str(&String::from_utf8(
|
|
||||||
groups
|
|
||||||
.get(3)
|
|
||||||
.ok_or(RustADBError::RegexParsingError)?
|
|
||||||
.as_bytes()
|
|
||||||
.to_vec(),
|
|
||||||
)?)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
mod adb_version;
|
|
||||||
mod device_long;
|
|
||||||
mod device_short;
|
|
||||||
mod device_state;
|
|
||||||
mod mdns_services;
|
|
||||||
mod server_status;
|
|
||||||
mod wait_for_device;
|
|
||||||
|
|
||||||
pub use adb_version::AdbVersion;
|
|
||||||
pub use device_long::DeviceLong;
|
|
||||||
pub use device_short::DeviceShort;
|
|
||||||
pub use device_state::DeviceState;
|
|
||||||
pub use mdns_services::MDNSServices;
|
|
||||||
pub use server_status::{MDNSBackend, ServerStatus};
|
|
||||||
pub use wait_for_device::{WaitForDeviceState, WaitForDeviceTransport};
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user