107 Commits

Author SHA1 Message Date
Corentin LIAUD
e111d03e4d chore(gh_actions): add build template jobs 2025-12-27 10:33:18 +01:00
Corentin LIAUD
0e24117678 fix(clippy): clippy warnings in tests 2025-12-27 10:05:52 +01:00
Corentin LIAUD
8e89aa0d6e chore(gh_actions): use own template 2025-12-26 17:00:46 +01:00
Corentin LIAUD
f0ed96cbd5 feat(gh): add pyadb_client build on arm64 2025-12-26 12:45:11 +01:00
cocool97
e2e1ae1202 Merge pull request #156 from cocool97/mdns-feature
feat(mdns): add feature flag + example
2025-12-26 12:24:00 +01:00
Corentin LIAUD
4f26ebfe29 fix: improve workflow 2025-12-26 12:19:44 +01:00
Corentin LIAUD
2a7c9bdc57 feat(mdns): add feature flag + example 2025-12-26 12:09:02 +01:00
Corentin LIAUD
d06b157255 chore: clippy improvements 2025-12-26 11:19:46 +01:00
Corentin LIAUD
947964163b fix(adb_client): image crate had no output format by default 2025-12-26 11:12:32 +01:00
Corentin LIAUD
5075e09d0e chore(adb_cli): improve error message in case of error 2025-12-26 11:12:08 +01:00
cocool97
f1d3f8d5f2 Merge pull request #155 from cocool97/sessions
feat: Track individual sessions (local and remote id) for each operation
2025-12-26 10:57:31 +01:00
Corentin LIAUD
9016b7fab4 chore: minor code improvements 2025-12-26 10:53:26 +01:00
Corentin LIAUD
558ef4df7f Track individual sessions (local and remote id) for each operation
This allows multiple operations to be performed simultaneously

Co-authored-by: gaykitty
2025-12-26 10:41:21 +01:00
Corentin LIAUD
989ba34a20 chore: clippy lints + v2.1.19 2025-12-23 21:14:21 +01:00
cocool97
da3423bc4a Merge pull request #116 from wxitcode/feat/115
feat: add Shell v2 protocol when the host supports Shell v2.
2025-12-23 21:09:20 +01:00
Corentin LIAUD
44742ada24 chore: add shell_v2 logging 2025-12-23 21:03:19 +01:00
LIAUD Corentin
dc05e85147 fix: inverted command & args 2025-12-23 20:56:24 +01:00
wxitcode
3f1a529c2b Refactor shell command handling to support v2 2025-12-23 20:54:59 +01:00
wxitcode
c3e4ea9eb8 feat: add Shell v2 protocol when the host supports Shell v2. 2025-12-23 20:54:57 +01:00
cocool97
22ceceb26a Merge pull request #103 from J05HM0N5TER/adb-list
feat: adb list
2025-12-23 20:53:26 +01:00
Corentin LIAUD
ed242808aa feat: rebase from main branch 2025-12-23 20:48:09 +01:00
J05HM0N5TER
c49378182e feat: adb list fixes 2025-12-23 20:38:41 +01:00
LIAUD Corentin
7fbea238c0 fix: remove duplicate list command 2025-12-23 20:38:39 +01:00
J05HM0N5TER
757b0f9523 feat: adb list
ADB List (ls) for both direct device communication and for communication though the adb server.
2025-12-23 20:38:31 +01:00
Himadri Bhattacharjee
d7dbc76727 Acknowledge shell_command response with OKAY messages for long responses (#154)
* fix: acknowledge write commands to continue partial data streams

* fix: read spurious close messages with a small timeout

* fix: clippy in CI not erro'ing on warnings

* breaking: bump msrv to 1.91.0

* fix: handle as many spurious CLSE messages as possible

---------

Co-authored-by: Corentin LIAUD <corentinliaud26@gmail.com>
2025-12-23 09:16:12 +01:00
Corentin LIAUD
739b3e1cee breaking: bump msrv to 1.91.0 2025-12-22 20:20:21 +01:00
Corentin LIAUD
4193779cd4 fix: clippy in CI not erro'ing on warnings 2025-12-22 19:32:22 +01:00
Corentin LIAUD
1564e99aa7 feat: improve error management in adb_cli
- adds an explicit error message when error needs to be filled with an
  issue
- remove anyhow dependency in adb_cli
- update deps
2025-12-12 19:30:05 +01:00
Pieter
c9d5df55d4 doc: adb_tcp_device.rs usb to tcp 2025-11-15 05:36:46 +01:00
Corentin LIAUD
36097fdc07 fix: windows release build 2025-11-07 14:41:09 +01:00
Corentin LIAUD
4ab0b01e37 chore: v2.1.18 2025-11-07 14:33:19 +01:00
Corentin LIAUD
ee3d879744 chore: v2.1.18 2025-11-07 14:20:17 +01:00
Corentin LIAUD
31d5388ffa feat(pyadb_client): bump min python version to 3.10 2025-11-07 14:18:37 +01:00
Corentin LIAUD
f108b5ed5f chore(bincode): bump 2025-11-06 08:55:41 +01:00
Corentin LIAUD
46c8c54751 chore(deps): updates 2025-11-06 08:15:11 +01:00
Koji AGAWA
f616373ae2 refactor(adb_client): Simplify command handling in adb_tcp_device.rs by reducing explicit return statements 2025-11-06 08:00:43 +01:00
Koji AGAWA
c83df4309f refactor(adb_client): Extract common AUTH handshake logic to a reusable method in adb_message_device.rs 2025-11-06 08:00:43 +01:00
Koji AGAWA
88526aa943 feat(adb_client): Add support for AUTH in the TCP device 2025-11-06 08:00:43 +01:00
Koji AGAWA
8cce59193c deps(adb_client): use ring rather than aws_lc_rs in rcgen 2025-11-06 07:47:59 +01:00
Corentin LIAUD
e0b6bb0139 chore: cargo clippy -- -W clippy::pedantic 2025-10-19 14:58:35 +02:00
Corentin LIAUD
373a5265a0 chore: v2.1.17 2025-09-21 11:42:58 +02:00
yohane
060e43590d Fix:Regex expression parsing transport incorrectly 2025-09-21 11:37:37 +02:00
Corentin LIAUD
f51ba984ca impr: further improve LogFilter by removing split_inclusive 2025-09-21 11:29:05 +02:00
0vercl0k
66ebc8a030 Reword logic in LogFilter::write to avoid cloning the internal buffer 2025-09-21 11:29:05 +02:00
LIAUD Corentin
d39e98695d fix: wrong msrv badges url 2025-08-03 17:38:11 +02:00
LIAUD Corentin
34d5811420 chore: version 2.1.16 2025-08-03 17:32:50 +02:00
LIAUD Corentin
86e28a6e25 chore: add msrv badges 2025-08-03 17:31:24 +02:00
LIAUD Corentin
9f113bdb93 chore: add msrv + fix clippy lints 2025-08-03 17:27:54 +02:00
cocool97
8670d6db58 fix: use random adb key if not existing (#130) 2025-08-03 17:08:15 +02:00
LIAUD Corentin
0732a0bbad chore: v2.1.15 2025-07-27 20:20:57 +02:00
cocool97
b5673001ca feat: make search_adb_devices and is_adb_device public (#129) 2025-07-27 20:19:03 +02:00
LIAUD Corentin
81829c1523 chore: v2.1.14 2025-07-07 08:21:22 +02:00
LIAUD Corentin
b9d2b8374f dep(homedir): fix to 0.3.4 to fix windows build 2025-07-06 20:00:24 +02:00
LIAUD Corentin
5716784f5d deps(homedir): fix version 0.3.5 because of hard rust 1.88 dep 2025-07-06 19:42:15 +02:00
LIAUD Corentin
b6ddc720d8 chore(clippy): run linter 2025-07-06 19:41:58 +02:00
Sashanoraa
5438e53361 Support devices that don't do auth (#124) 2025-07-06 19:34:34 +02:00
cocool97
39a7f0a8cf chore: bump criterion + pyo3 (#122) 2025-05-24 14:56:34 +02:00
LIAUD Corentin
4129d9d218 chore: v2.1.13 2025-05-12 19:48:19 +02:00
alesharik
c23dca61d7 feat: add fastboot reboot type (#119)
* feat: add fastboot reboot type

* feat: add fastboot command to cli

---------

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

* test: add device_long unit tests

* fix: prevent copy when parsing DeviceLong

---------

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

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2025-03-12 17:26:13 +01:00
LIAUD Corentin
cdf062c3e1 bump: version 2.1.9 2025-03-09 19:43:54 +01:00
cocool97
b8e3d02311 feat: do not show prompt on Windows (#98) 2025-03-09 19:42:39 +01:00
cocool97
1b7efc1cc6 feat: ADBServerDevice without serial (#97)
* feat: ADBServerDevice without serial

* chore: bump deps

* actions: improve build
2025-03-09 19:33:20 +01:00
cli
ad064a9f41 feat: add wait-for-device command (#96) 2025-03-07 17:01:26 +01:00
LIAUD Corentin
d0e0f46571 chore: version v2.1.8 2025-02-27 10:04:00 +01:00
Yohane
727f3a3eb4 Fix:Regex expression parsing usb incorrectly (#94) 2025-02-27 10:02:49 +01:00
Otto Zell
ab77db5cc8 Fix for android clients that do not expect encrypted connections (#93)
* Fix for adb clients that do not want encrypted connections

---------

Co-authored-by: Otto Zell <otto.zell@drivec.se>
Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2025-02-27 09:54:04 +01:00
cocool97
1255f2b5d6 feat: improve python-build.yml (#92) 2025-02-11 15:26:19 +01:00
LIAUD Corentin
eb04f9064c chore: v2.1.7 2025-02-11 14:39:14 +01:00
LIAUD Corentin
69107e2333 fix(pyadb_client): add adb_client as a path dependency 2025-02-11 14:38:20 +01:00
LIAUD Corentin
17bb77a472 chore: v2.1.6 2025-02-11 14:12:28 +01:00
cocool97
f211023b24 feat: do not include rust files in python package (#91) 2025-02-11 14:03:24 +01:00
cli
728d9603dc fix(python): improve modules path (#88) 2025-02-06 16:53:29 +01:00
cocool97
00c387d85c feat: pyo3 stub generation (#87) 2025-02-06 11:25:07 +01:00
Andreas Tzionis
79d96d4c76 Implemented uninstall command (#86)
* implemented uninstall command
2025-01-29 20:17:28 +01:00
LIAUD Corentin
dc909ceda6 chore: v2.1.5 2025-01-24 15:06:24 +01:00
cocool97
cbba912483 fix: improve python package build (#85) 2025-01-24 15:00:36 +01:00
LIAUD Corentin
38d8384b98 fix: maturin non-interactive 2025-01-24 10:18:55 +01:00
cocool97
39591b6a0a ci: build python wheels (#84) 2025-01-24 10:11:51 +01:00
LIAUD Corentin
775b2421ec chore(ci): improve python build 2025-01-22 15:57:02 +01:00
LIAUD Corentin
62d16b70fb chore: version 2.1.0 2025-01-22 15:25:03 +01:00
cli
466d00e68a feat: Python package (#80)
* feat: create pyadb_client python package

* feat: add push / pull methods

* feat: add shell_command for USB

* feat(ci): add python package build
2025-01-22 15:22:36 +01:00
KFBI1706
144072ba1b fix: track_devices support multiple devices (#83) 2025-01-21 07:31:39 +01:00
LIAUD Corentin
331ef95530 chore: fix deps for adb_cli 2024-12-18 11:24:52 +01:00
LIAUD Corentin
61408cb470 chore: version 2.1.0 2024-12-18 11:12:56 +01:00
cli
c54942f25d feat: improve USB performances by storing endpoints (#79) 2024-12-18 10:55:40 +01:00
cli
3feda38cc3 core: bump deps + update README.md (#78) 2024-12-18 08:34:31 +01:00
cli
9002ecc0c8 chore: internal updates (#74)
* chore: update adb_client README.md

* chore(internal): add assert_command() method on ADBTransportMessage

* chore: minor internal changes

* chore: add server-only models
2024-12-13 14:08:48 +01:00
Stone
5a3ac68fce feat: do not detach kernel driver (#72) 2024-12-10 17:17:41 +01:00
cli
5dfd30cc5b breaking: make ADBDeviceExt dyn-compatible (#70)
* feat: make ADBDeviceExt dyn-compatible

* feat: clean CLI code
2024-12-06 17:47:38 +01:00
cli
66d124475d feat: add framebuffer method to USB/TCP direct devices (#69)
* feat: store local_id and remote_id in ADBMessageDevice
2024-12-03 13:55:12 +01:00
129 changed files with 3025 additions and 1844 deletions

65
.github/workflows/python-build.yml vendored Normal file
View File

@@ -0,0 +1,65 @@
name: Python - Build packages & Release
on:
push:
branches:
- main
pull_request:
release:
types: [created]
jobs:
# ============================
# BUILD (multi-architecture)
# ============================
build-python-packages:
strategy:
fail-fast: false
matrix:
arch: [x86_64, arm64]
runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }}
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: Upload wheels as artifacts
uses: actions/upload-artifact@v4
with:
name: wheels-${{ matrix.arch }}
path: target/wheels/*
if-no-files-found: error
# ================================
# PUBLISH (release creation only)
# ================================
publish:
name: Publish to PyPI & GitHub Release
if: github.event_name == 'release' && github.event.action == 'created'
needs: build-python-packages
runs-on: ubuntu-latest
steps:
- name: Download all wheels
uses: actions/download-artifact@v4
with:
path: wheels
- name: Publish Python packages to PyPI
run: maturin publish wheels/**/*.whl --non-interactive
env:
MATURIN_PYPI_TOKEN: ${{ secrets.MATURIN_PYPI_TOKEN }}
- name: Publish GitHub release artifacts
uses: softprops/action-gh-release@v2
with:
files: wheels/**/*.*

View File

@@ -1,15 +1,11 @@
name: Rust - Build name: Rust - Build
on: [push, pull_request] on:
push:
env: branches:
CARGO_TERM_COLOR: always - main
pull_request:
jobs: jobs:
build-release: build-release:
name: "build-release" uses: cocool97/action_templates/.github/workflows/rust-build.yml@main
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build project
run: cargo build --release --all-features

View File

@@ -1,42 +1,11 @@
name: Rust - Quality name: Rust - Quality
on: [push, pull_request] on:
push:
env: branches:
CARGO_TERM_COLOR: always - main
pull_request:
jobs: jobs:
clippy: quality:
name: "clippy" uses: cocool97/action_templates/.github/workflows/rust-quality.yml@main
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: rustup component add clippy
- name: Run clippy
run: cargo clippy --all-features
fmt:
name: "fmt"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run formatter
run: cargo fmt --all --check
doc:
name: "doc"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run doc
run: cargo doc --all-features --no-deps
env:
RUSTDOCFLAGS: "-D warnings"
tests:
name: "tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: cargo test --verbose --all-features

View File

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

@@ -1,3 +1,6 @@
target target
Cargo.lock /Cargo.lock
.vscode /.vscode
venv
/.mypy_cache
pyadb_client/pyadb_client.pyi

View File

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

View File

@@ -8,6 +8,9 @@
<a href="https://crates.io/crates/adb_client"> <a href="https://crates.io/crates/adb_client">
<img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/> <img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/>
</a> </a>
<a href="https://crates.io/crates/adb_client">
<img alt="msrv" src="https://img.shields.io/crates/msrv/adb_client"/>
</a>
<a href="https://github.com/cocool97/adb_client/actions"> <a href="https://github.com/cocool97/adb_client/actions">
<img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/> <img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/>
</a> </a>
@@ -30,6 +33,7 @@ Main features of this library:
- Over **TCP/IP** - Over **TCP/IP**
- Implements hidden `adb` features, like `framebuffer` - 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
@@ -38,15 +42,28 @@ Rust library implementing both ADB protocols (server and end-devices) and provid
Improved documentation available [here](./adb_client/README.md). Improved documentation available [here](./adb_client/README.md).
## examples
Some examples showing of to use this library are available in the `examples` directory:
- `examples/mdns`: mDNS device discovery
## adb_cli ## 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 Google's official `adb` CLI, by using `adb_client` library.
Provides 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 available [here](./adb_cli/README.md).
## pyadb_client
Python wrapper using `adb_client` library to export classes usable directly from a Python environment.
Improved documentation available [here](./pyadb_client/README.md)
## Related publications ## 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 (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 ! Some features may still be missing, all pull requests are welcome !

View File

@@ -7,14 +7,14 @@ license.workspace = true
name = "adb_cli" name = "adb_cli"
readme = "README.md" readme = "README.md"
repository.workspace = true repository.workspace = true
rust-version.workspace = true
version.workspace = true version.workspace = true
[dependencies] [dependencies]
adb_client = { version = "2.0.5" } adb_client = { version = "^2.1.19", features = ["mdns"] }
anyhow = { version = "1.0.89" } clap = { version = "4.5.53", features = ["derive"] }
clap = { version = "4.5.18", features = ["derive"] } env_logger = { version = "0.11.8" }
env_logger = { version = "0.11.5" } log = { version = "0.4.29" }
log = { version = "0.4.22" }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
termios = { version = "0.3.3" } termios = { version = "0.3.3" }

View File

@@ -1,7 +1,8 @@
# adb_cli # `adb_cli`
[![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli) ![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli)
![MSRV](https://img.shields.io/crates/msrv/adb_cli)
Rust binary providing an improved version of `adb` CLI. Rust binary providing an improved version of `adb` CLI.
@@ -18,38 +19,29 @@ Usage is quite simple, and tends to look like `adb`:
- To use ADB server as a proxy: - To use ADB server as a proxy:
```bash ```bash
user@laptop ~/adb_client (main)> adb_cli --help user@laptop ~/adb_client (main)> adb_cli local --help
Rust ADB (Android Debug Bridge) CLI Device related commands using server
Usage: adb_cli [OPTIONS] <COMMAND> Usage: adb_cli local [OPTIONS] <COMMAND>
Commands: Commands:
host-features List available server features
push Push a file on device
pull Pull a file from 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 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 reboot Reboot the device
install Install an APK on device
framebuffer Dump framebuffer of device framebuffer Dump framebuffer of device
host-features List available server features
list List a directory on 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 - To interact directly with end devices

View File

@@ -2,9 +2,9 @@
use std::os::unix::prelude::{AsRawFd, RawFd}; use std::os::unix::prelude::{AsRawFd, RawFd};
use termios::{tcsetattr, Termios, TCSANOW, VMIN, VTIME}; use termios::{TCSANOW, Termios, VMIN, VTIME, tcsetattr};
use crate::Result; use crate::models::{ADBCliError, ADBCliResult};
pub struct ADBTermios { pub struct ADBTermios {
fd: RawFd, fd: RawFd,
@@ -13,7 +13,7 @@ pub struct ADBTermios {
} }
impl ADBTermios { impl ADBTermios {
pub fn new(fd: impl AsRawFd) -> Result<Self> { pub fn new(fd: &impl AsRawFd) -> Result<Self, ADBCliError> {
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 +27,7 @@ impl ADBTermios {
}) })
} }
pub fn set_adb_termios(&mut self) -> Result<()> { pub fn set_adb_termios(&mut self) -> ADBCliResult<()> {
Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?) Ok(tcsetattr(self.fd, TCSANOW, &self.new_termios)?)
} }
} }
@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
fn drop(&mut self) { fn drop(&mut self) {
// Custom drop implementation, restores previous termios structure. // Custom drop implementation, restores previous termios structure.
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) { if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
log::error!("Error while droping ADBTermios: {e}") log::error!("Error while dropping ADBTermios: {e}");
} }
} }
} }

View File

@@ -1,12 +0,0 @@
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,
}

View File

@@ -1,46 +0,0 @@
use clap::Parser;
use std::path::PathBuf;
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 { commands: Vec<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,
},
/// Dump framebuffer of device
Framebuffer { path: String },
/// Get logs of device
Logcat {
/// Path to output file (created if not exists)
path: Option<String>,
},
/// Install an APK on device
Install {
/// Path to APK file. Extension must be ".apk"
path: PathBuf,
},
}

View File

@@ -1,11 +0,0 @@
mod emu;
mod host;
mod local;
mod tcp;
mod usb;
pub use emu::EmuCommand;
pub use host::{HostCommand, MdnsCommand};
pub use local::LocalCommand;
pub use tcp::{TcpCommand, TcpCommands};
pub use usb::{UsbCommand, UsbCommands};

View File

@@ -1,56 +0,0 @@
use std::num::ParseIntError;
use std::path::PathBuf;
use clap::Parser;
use crate::models::RebootTypeCommand;
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: UsbCommands,
}
#[derive(Parser, Debug)]
pub enum UsbCommands {
/// 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,
},
}

View File

@@ -0,0 +1,20 @@
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(())
}

View File

@@ -0,0 +1,85 @@
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(())
}

View File

@@ -0,0 +1,33 @@
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)?)
}
}
}

View File

@@ -0,0 +1,7 @@
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;

View File

@@ -3,334 +3,179 @@
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
mod adb_termios; mod adb_termios;
mod commands; mod handlers;
mod models; mod models;
mod utils;
use adb_client::{ use adb_client::{
ADBDeviceExt, ADBEmulatorDevice, ADBServer, ADBTcpDevice, ADBUSBDevice, DeviceShort, ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
MDNSBackend, MDNSDiscoveryService, mdns::MDNSDiscoveryService,
}; };
use anyhow::{anyhow, Result};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use adb_termios::ADBTermios;
use clap::Parser; use clap::Parser;
use commands::{EmuCommand, HostCommand, LocalCommand, MdnsCommand, TcpCommands, UsbCommands}; use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
use models::{Command, Opts}; use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
use std::collections::HashMap;
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;
fn main() -> Result<()> { use crate::models::{ADBCliError, ADBCliResult};
let opts = Opts::parse();
// RUST_LOG variable has more priority then "--debug" flag fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> ADBCliResult<()> {
if std::env::var("RUST_LOG").is_err() { match command {
let level = match opts.debug { DeviceCommands::Shell { commands } => {
true => "trace",
false => "info",
};
std::env::set_var("RUST_LOG", level);
}
// Setting default log level as "info" if not set
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
env_logger::init();
match opts.command {
Command::Local(local) => {
let mut adb_server = ADBServer::new(opts.address);
let mut device = match opts.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.pull(&path, &mut output)?;
log::info!("Downloaded {path} as {filename}");
}
LocalCommand::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
LocalCommand::List { path } => {
device.list(path)?;
}
LocalCommand::Stat { path } => {
let stat_response = device.stat(path)?;
println!("{}", stat_response);
}
LocalCommand::Shell { commands } => {
if commands.is_empty() { if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state. // Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early.. // Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
{ {
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?; let mut adb_termios = ADBTermios::new(&std::io::stdin())?;
adb_termios.set_adb_termios()?; adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?; device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
} }
#[cfg(not(any(target_os = "linux", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "macos")))]
{ {
device.shell(std::io::stdin(), std::io::stdout())?; device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
} }
} else { } else {
device.shell_command(commands, std::io::stdout())?; let commands: Vec<&str> = commands.iter().map(String::as_str).collect();
device.shell_command(&commands, &mut std::io::stdout())?;
} }
} }
LocalCommand::Run { package, activity } => { 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)?; let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?; std::io::stdout().write_all(&output)?;
} }
LocalCommand::HostFeatures => { DeviceCommands::Install { path } => {
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 { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.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)?;
}
LocalCommand::Install { path } => {
log::info!("Starting installation of APK {}...", path.display()); log::info!("Starting installation of APK {}...", path.display());
device.install(path)?; 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
);
} }
} }
} }
Command::Host(host) => {
let mut adb_server = ADBServer::new(opts.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(()) Ok(())
}; }
log::info!("Live list of devices attached");
adb_server.track_devices(callback)?; fn main() -> ExitCode {
if let Err(err) = inner_main() {
log::error!("{err}");
return ExitCode::FAILURE;
} }
HostCommand::Pair { address, code } => {
adb_server.pair(address, code)?; ExitCode::SUCCESS
log::info!("Paired device {address}"); }
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);
} }
HostCommand::Connect { address } => {
adb_server.connect_device(address)?; let device = match server_command.serial {
log::info!("Connected to {address}"); Some(serial) => ADBServerDevice::new(serial, Some(server_command.address)),
} None => ADBServerDevice::autodetect(Some(server_command.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 => match check {
true => log::info!("mdns daemon version [Bonjour]"),
false => log::info!("ERROR: mdns daemon unavailable"),
},
MDNSBackend::OpenScreen => {
log::info!("mdns daemon version [Openscreen discovery 0.0.0]")
}
}
}
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()?);
}
}
}
Command::Emu(emu) => {
let mut emulator = match opts.serial {
Some(serial) => ADBEmulatorDevice::new(serial, None)?,
None => return Err(anyhow!("Serial must be set to use emulators !")),
}; };
match emu { match server_command.command {
EmuCommand::Sms { LocalCommand::DeviceCommands(device_commands) => (device.boxed(), device_commands),
phone_number, LocalCommand::LocalDeviceCommand(local_device_command) => {
content, return handle_local_commands(device, local_device_command);
} => {
emulator.send_sms(&phone_number, &content)?;
log::info!("SMS sent to {phone_number}");
}
EmuCommand::Rotate => emulator.rotate()?,
} }
} }
Command::Usb(usb) => { }
let mut device = match (usb.vendor_id, usb.product_id) { MainCommand::Usb(usb_command) => {
(Some(vid), Some(pid)) => match usb.path_to_private_key { 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)?, Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBUSBDevice::new(vid, pid)?, None => ADBUSBDevice::new(vid, pid)?,
}, },
(None, None) => match usb_command.path_to_private_key {
(None, None) => match usb.path_to_private_key {
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?, Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
None => ADBUSBDevice::autodetect()?, None => ADBUSBDevice::autodetect()?,
}, },
_ => { _ => {
anyhow::bail!("please either supply values for both the --vendor-id and --product-id flags or none."); return Err(ADBCliError::Standard(
"cannot specify flags --vendor-id without --product-id or vice versa"
.into(),
));
} }
}; };
(device.boxed(), usb_command.commands)
match usb.commands {
UsbCommands::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?;
} }
MainCommand::Tcp(tcp_command) => {
#[cfg(not(any(target_os = "linux", target_os = "macos")))] let device = match tcp_command.path_to_private_key {
{ Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
device.shell(std::io::stdin(), std::io::stdout())?; None => ADBTcpDevice::new(tcp_command.address)?,
};
(device.boxed(), tcp_command.commands)
} }
} else { MainCommand::Mdns => {
device.shell_command(commands, std::io::stdout())?;
}
}
UsbCommands::Pull {
source,
destination,
} => {
let mut output = File::create(Path::new(&destination))?;
device.pull(&source, &mut output)?;
log::info!("Downloaded {source} as {destination}");
}
UsbCommands::Stat { path } => {
let stat_response = device.stat(&path)?;
println!("{}", stat_response);
}
UsbCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.into())?
}
UsbCommands::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
UsbCommands::Run { package, activity } => {
let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?;
}
UsbCommands::Install { path } => {
log::info!("Starting installation of APK {}...", path.display());
device.install(path)?;
}
}
}
Command::Tcp(tcp) => {
let mut device = ADBTcpDevice::new(tcp.address)?;
match tcp.commands {
TcpCommands::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?;
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
device.shell(std::io::stdin(), std::io::stdout())?;
}
} else {
device.shell_command(commands, std::io::stdout())?;
}
}
TcpCommands::Pull {
source,
destination,
} => {
let mut output = File::create(Path::new(&destination))?;
device.pull(&source, &mut output)?;
log::info!("Downloaded {source} as {destination}");
}
TcpCommands::Stat { path } => {
let stat_response = device.stat(&path)?;
println!("{}", stat_response);
}
TcpCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.into())?
}
TcpCommands::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
TcpCommands::Run { package, activity } => {
let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?;
}
TcpCommands::Install { path } => {
log::info!("Starting installation of APK {}...", path.display());
device.install(path)?;
}
}
}
Command::MdnsDiscovery => {
let mut service = MDNSDiscoveryService::new()?; let mut service = MDNSDiscoveryService::new()?;
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
@@ -339,15 +184,18 @@ fn main() -> Result<()> {
log::info!("Starting mdns discovery..."); log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() { while let Ok(device) = rx.recv() {
log::info!( log::info!(
"Found device {} with addresses {:?}", "Found device fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
device.fullname, device.fullname,
device.addresses device.ipv4_addresses(),
) device.ipv6_addresses()
);
} }
service.shutdown()?; return Ok(service.shutdown()?);
}
} }
};
run_command(device, commands)?;
Ok(()) Ok(())
} }

View File

@@ -0,0 +1,84 @@
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),
}
}
}

View File

@@ -1,19 +1,11 @@
use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
use clap::Parser; use clap::Parser;
use crate::models::RebootTypeCommand; use super::RebootTypeCommand;
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
pub struct TcpCommand { pub enum DeviceCommands {
pub address: SocketAddr,
#[clap(subcommand)]
pub commands: TcpCommands,
}
#[derive(Parser, Debug)]
pub enum TcpCommands {
/// Spawn an interactive shell or run a list of commands on the device /// Spawn an interactive shell or run a list of commands on the device
Shell { commands: Vec<String> }, Shell { commands: Vec<String> },
/// Pull a file from device /// Pull a file from device
@@ -27,7 +19,7 @@ pub enum TcpCommands {
/// The package whose activity is to be invoked /// The package whose activity is to be invoked
#[clap(short = 'p', long = "package")] #[clap(short = 'p', long = "package")]
package: String, package: String,
/// The activity to be invoked itself, Usually it is MainActivity /// The activity to be invoked itself, Usually it is `MainActivity`
#[clap(short = 'a', long = "activity")] #[clap(short = 'a', long = "activity")]
activity: String, activity: String,
}, },
@@ -41,4 +33,19 @@ pub enum TcpCommands {
/// Path to APK file. Extension must be ".apk" /// Path to APK file. Extension must be ".apk"
path: PathBuf, 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,
},
} }

20
adb_cli/src/models/emu.rs Normal file
View File

@@ -0,0 +1,20 @@
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,
}

View File

@@ -1,7 +1,14 @@
use std::net::SocketAddrV4; use std::{net::SocketAddrV4, str::FromStr};
use adb_client::{RustADBError, WaitForDeviceTransport};
use clap::Parser; use clap::Parser;
fn parse_wait_for_device_device_transport(
value: &str,
) -> Result<WaitForDeviceTransport, RustADBError> {
WaitForDeviceTransport::from_str(value)
}
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
pub enum HostCommand { pub enum HostCommand {
/// Print current ADB version. /// Print current ADB version.
@@ -28,6 +35,12 @@ pub enum HostCommand {
}, },
/// Display server status /// Display server status
ServerStatus, 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)] #[derive(Parser, Debug)]

View File

@@ -0,0 +1,22 @@
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>,
},
}

View File

@@ -1,5 +1,19 @@
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 opts::{Command, Opts}; pub use adb_cli_error::{ADBCliError, ADBCliResult};
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;

View File

@@ -1,36 +1,41 @@
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
use clap::Parser; use clap::{Parser, Subcommand};
use crate::commands::{EmuCommand, HostCommand, LocalCommand, TcpCommand, UsbCommand}; use super::{EmulatorCommand, HostCommand, LocalCommand, TcpCommand, UsbCommand};
#[derive(Parser, Debug)] #[derive(Debug, Parser)]
#[clap(about, version, author)] #[clap(about, version, author)]
pub struct Opts { pub struct Opts {
#[clap(long = "debug")] #[clap(long = "debug")]
pub debug: bool, pub debug: 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: Command, pub command: T,
}
#[derive(Parser, Debug)]
pub enum Command {
#[clap(flatten)]
Local(LocalCommand),
#[clap(flatten)]
Host(HostCommand),
/// Emulator specific commands
#[clap(subcommand)]
Emu(EmuCommand),
/// Device commands via USB, no server needed
Usb(UsbCommand),
/// Device commands via TCP, no server needed
Tcp(TcpCommand),
/// Discover devices over MDNS without using adb-server
MdnsDiscovery,
} }

View File

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

15
adb_cli/src/models/tcp.rs Normal file
View File

@@ -0,0 +1,15 @@
use clap::Parser;
use std::net::SocketAddr;
use std::path::PathBuf;
use super::DeviceCommands;
#[derive(Parser, Debug)]
pub struct TcpCommand {
pub address: SocketAddr,
/// Path to a custom private key to use for authentication
#[clap(short = 'k', long = "private-key")]
pub path_to_private_key: Option<PathBuf>,
#[clap(subcommand)]
pub commands: DeviceCommands,
}

25
adb_cli/src/models/usb.rs Normal file
View File

@@ -0,0 +1,25 @@
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,
}

9
adb_cli/src/utils.rs Normal file
View File

@@ -0,0 +1,9 @@
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();
}

View File

@@ -7,36 +7,49 @@ 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" } base64 = { version = "0.22.1" }
bincode = { version = "1.3.3" } bincode = { version = "2.0.1", features = ["serde"] }
byteorder = { version = "1.5.0" } byteorder = { version = "1.5.0" }
chrono = { version = "0.4.38" } chrono = { version = "0.4.42", default-features = false, features = ["std"] }
homedir = { version = "0.3.4" } image = { version = "0.25.9", default-features = false, features = ["png"] }
image = { version = "0.25.5" } log = { version = "0.4.29" }
lazy_static = { version = "1.5.0" } num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
log = { version = "0.4.22" }
mdns-sd = { version = "0.12.0" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" } num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" } quick-protobuf = { version = "0.8.1" }
rand = { version = "0.8.5" } rand = { version = "0.9.2" }
rcgen = { version = "0.13.1" } rcgen = { version = "0.14.6" }
regex = { version = "1.11.0", features = ["perf", "std", "unicode"] } regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
rsa = { version = "0.9.7" } rsa = { version = "0.9.9" }
rusb = { version = "0.9.4", features = ["vendored"] } rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.18" } rustls = { version = "0.23.35" }
rustls-pki-types = "1.10.0" rustls-pki-types = { version = "1.13.2" }
serde = { version = "1.0.210", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_repr = { version = "0.1.19" } serde_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] } sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.1" } thiserror = { version = "2.0.17" }
#########
# `mdns` feature-specific dependencies
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
], optional = true }
#########
[dev-dependencies] [dev-dependencies]
anyhow = { version = "1.0.93" } anyhow = { version = "1.0.100" }
criterion = { version = "0.5.1" } # Used for benchmarks criterion = { version = "0.7.0" } # Used for benchmarks
[[bench]] [[bench]]
harness = false harness = false

View File

@@ -1,8 +1,9 @@
# adb_client # `adb_client`
[![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT) [![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT)
[![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client) [![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_client) [![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_client)](https://crates.io/crates/adb_client)
![MSRV](https://img.shields.io/crates/msrv/adb_client)
Rust library implementing ADB protocol. Rust library implementing ADB protocol.
@@ -15,6 +16,33 @@ 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
### Get available ADB devices ### Get available ADB devices
@@ -40,7 +68,7 @@ use adb_client::{ADBServer, ADBDeviceExt};
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");
device.shell_command(["df", "-h"],std::io::stdout()); device.shell_command(&["df", "-h"], &mut std::io::stdout());
``` ```
#### Push a file to the device #### Push a file to the device
@@ -67,7 +95,7 @@ use adb_client::{ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8; let vendor_id = 0x04e8;
let product_id = 0x6860; let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device"); let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(["df", "-h"],std::io::stdout()); device.shell_command(&["df", "-h"], &mut std::io::stdout());
``` ```
#### (USB) Push a file to the device #### (USB) Push a file to the device
@@ -81,10 +109,10 @@ let vendor_id = 0x04e8;
let product_id = 0x6860; let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device"); 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"); let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp"); device.push(&mut input, &"/data/local/tmp");
``` ```
### (TCP) Get a shell from device #### (TCP) Get a shell from device
```rust no_run ```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::net::{SocketAddr, IpAddr, Ipv4Addr};
@@ -93,5 +121,5 @@ use adb_client::{ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10)); let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210; let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device"); let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(std::io::stdin(), std::io::stdout()); device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()));
``` ```

View File

@@ -1,31 +1,31 @@
use std::io::{Read, Write}; use std::io::{Cursor, Read, Write};
use std::path::Path; use std::path::Path;
use image::{ImageBuffer, ImageFormat, Rgba};
use crate::models::AdbStatResponse; use crate::models::AdbStatResponse;
use crate::{RebootType, Result}; use crate::{ADBListItem, RebootType, Result};
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`] /// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
pub trait ADBDeviceExt { pub trait ADBDeviceExt {
/// Runs command in a shell on the device, and write its output and error streams into output. /// Runs command in a shell on the device, and write its output and error streams into output.
fn shell_command<S: ToString, W: Write>( fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()>;
/// Starts an interactive shell session on the device. /// Starts an interactive shell session on the device.
/// Input data is read from reader and write to writer. /// Input data is read from reader and write to writer.
/// W has a 'static bound as it is internally used in a thread. fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()>;
fn shell<R: Read, W: Write + Send + 'static>(&mut self, reader: R, writer: W) -> Result<()>;
/// Display the stat information for a remote file /// Display the stat information for a remote file
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>; fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;
/// Pull the remote file pointed to by `source` and write its contents into `output` /// Pull the remote file pointed to by `source` and write its contents into `output`
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()>; fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()>;
/// Push `stream` to `path` on the device. /// Push `stream` to `path` on the device.
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()>; 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 /// Reboot the device using given reboot type
fn reboot(&mut self, reboot_type: RebootType) -> Result<()>; fn reboot(&mut self, reboot_type: RebootType) -> Result<()>;
@@ -34,7 +34,7 @@ pub trait ADBDeviceExt {
fn run_activity(&mut self, package: &str, activity: &str) -> Result<Vec<u8>> { fn run_activity(&mut self, package: &str, activity: &str) -> Result<Vec<u8>> {
let mut output = Vec::new(); let mut output = Vec::new();
self.shell_command( self.shell_command(
["am", "start", &format!("{package}/{package}.{activity}")], &["am", "start", &format!("{package}/{package}.{activity}")],
&mut output, &mut output,
)?; )?;
@@ -42,5 +42,40 @@ pub trait ADBDeviceExt {
} }
/// Install an APK pointed to by `apk_path` on device. /// Install an APK pointed to by `apk_path` on device.
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()>; 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)
}
} }

View File

@@ -1,10 +1,27 @@
use byteorder::{LittleEndian, ReadBytesExt}; 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 rand::Rng;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{Cursor, Read, Seek}; use std::io::{Cursor, Read, Seek};
use std::time::Duration;
use crate::{constants::BUFFER_SIZE, ADBMessageTransport, AdbStatResponse, Result, RustADBError}; const BINCODE_CONFIG: Configuration<LittleEndian, Fixint, NoLimit> = bincode::config::legacy();
use super::{models::MessageSubcommand, ADBTransportMessage, MessageCommand}; pub(crate) fn bincode_serialize_to_vec<E: Serialize>(val: E) -> Result<Vec<u8>> {
bincode::serde::encode_to_vec(val, BINCODE_CONFIG).map_err(|_e| RustADBError::ConversionError)
}
pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -> Result<D> {
let (response, _) = bincode::serde::decode_from_slice(data, BINCODE_CONFIG)
.map_err(|_e| RustADBError::ConversionError)?;
Ok(response)
}
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`]. /// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
/// Structure is totally agnostic over which transport is truly used. /// Structure is totally agnostic over which transport is truly used.
@@ -27,18 +44,77 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
&mut self.transport &mut self.transport
} }
pub(crate) fn auth_handshake(
&mut self,
message: ADBTransportMessage,
private_key: &ADBRsaKey,
) -> Result<()> {
match message.header().command() {
MessageCommand::Auth => {
log::debug!("Authentication required");
}
_ => return Ok(()),
}
// At this point, we should have received an AUTH message with arg0 == 1
let auth_message = match message.header().arg0() {
AUTH_TOKEN => message,
v => {
return Err(RustADBError::ADBRequestFailed(format!(
"Received AUTH message with type != 1 ({v})"
)));
}
};
let sign = private_key.sign(auth_message.into_payload())?;
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, &sign);
self.get_transport_mut().write_message(message)?;
let received_response = self.get_transport_mut().read_message()?;
if received_response.header().command() == MessageCommand::Cnxn {
log::info!(
"Authentication OK, device info {}",
String::from_utf8(received_response.into_payload())?
);
return Ok(());
}
let mut pubkey = private_key.android_pubkey_encode()?.into_bytes();
pubkey.push(b'\0');
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_RSAPUBLICKEY, 0, &pubkey);
self.get_transport_mut().write_message(message)?;
let response = self
.get_transport_mut()
.read_message_with_timeout(Duration::from_secs(10))
.and_then(|message| {
message.assert_command(MessageCommand::Cnxn)?;
Ok(message)
})?;
log::info!(
"Authentication OK, device info {}",
String::from_utf8(response.into_payload())?
);
Ok(())
}
/// Receive a message and acknowledge it by replying with an `OKAY` command /// Receive a message and acknowledge it by replying with an `OKAY` command
pub(crate) fn recv_and_reply_okay( pub(crate) fn recv_and_reply_okay(
&mut self, &mut self,
local_id: u32, session: ADBSession,
remote_id: u32,
) -> Result<ADBTransportMessage> { ) -> Result<ADBTransportMessage> {
let message = self.transport.read_message()?; let message = self.transport.read_message()?;
self.transport.write_message(ADBTransportMessage::new( self.transport.write_message(ADBTransportMessage::new(
MessageCommand::Okay, MessageCommand::Okay,
local_id, session.local_id(),
remote_id, session.remote_id(),
"".into(), &[],
))?; ))?;
Ok(message) Ok(message)
} }
@@ -49,34 +125,27 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
message: ADBTransportMessage, message: ADBTransportMessage,
) -> Result<ADBTransportMessage> { ) -> Result<ADBTransportMessage> {
self.transport.write_message(message)?; self.transport.write_message(message)?;
let message = self.transport.read_message()?;
let received_command = message.header().command(); self.transport.read_message().and_then(|message| {
if received_command != MessageCommand::Okay { message.assert_command(MessageCommand::Okay)?;
return Err(RustADBError::ADBRequestFailed(format!(
"expected command OKAY after message, got {}",
received_command
)));
}
Ok(message) Ok(message)
})
} }
pub(crate) fn recv_file<W: std::io::Write>( pub(crate) fn recv_file<W: std::io::Write>(
&mut self, &mut self,
local_id: u32, session: ADBSession,
remote_id: u32,
mut output: W, mut output: W,
) -> std::result::Result<(), RustADBError> { ) -> std::result::Result<(), RustADBError> {
let mut len: Option<u64> = None; let mut len: Option<u64> = None;
loop { loop {
let payload = self let payload = self.recv_and_reply_okay(session)?.into_payload();
.recv_and_reply_okay(local_id, remote_id)?
.into_payload();
let mut rdr = Cursor::new(&payload); let mut rdr = Cursor::new(&payload);
while rdr.position() != payload.len() as u64 { while rdr.position() != payload.len() as u64 {
match len.take() { match len.take() {
Some(0) | None => { Some(0) | None => {
rdr.seek_relative(4)?; rdr.seek_relative(4)?;
len.replace(rdr.read_u32::<LittleEndian>()? as u64); len.replace(u64::from(rdr.read_u32::<byteorder::LittleEndian>()?));
} }
Some(length) => { Some(length) => {
let remaining_bytes = payload.len() as u64 - rdr.position(); let remaining_bytes = payload.len() as u64 - rdr.position();
@@ -92,7 +161,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
} }
} }
if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)]) if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
.read_u32::<LittleEndian>()? .read_u32::<byteorder::LittleEndian>()?
== MessageSubcommand::Done as u32 == MessageSubcommand::Done as u32
{ {
break; break;
@@ -103,43 +172,39 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push_file<R: std::io::Read>( pub(crate) fn push_file<R: std::io::Read>(
&mut self, &mut self,
local_id: u32, session: ADBSession,
remote_id: u32,
mut reader: R, mut reader: R,
) -> std::result::Result<(), RustADBError> { ) -> std::result::Result<(), RustADBError> {
let mut buffer = [0; BUFFER_SIZE]; let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
let amount_read = reader.read(&mut buffer)?; let amount_read = reader.read(&mut buffer)?;
let subcommand_data = MessageSubcommand::Data.with_arg(amount_read as u32); let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(amount_read)?);
let mut serialized_message = let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
bincode::serialize(&subcommand_data).map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..amount_read].to_vec()); serialized_message.append(&mut buffer[..amount_read].to_vec());
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
serialized_message, &serialized_message,
); );
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
loop { loop {
let mut buffer = [0; BUFFER_SIZE]; let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
match reader.read(&mut buffer) { match reader.read(&mut buffer) {
Ok(0) => { Ok(0) => {
// Currently file mtime is not forwarded // Currently file mtime is not forwarded
let subcommand_data = MessageSubcommand::Done.with_arg(0); let subcommand_data = MessageSubcommand::Done.with_arg(0);
let serialized_message = bincode::serialize(&subcommand_data) let serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
.map_err(|_e| RustADBError::ConversionError)?;
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
serialized_message, &serialized_message,
); );
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
@@ -150,24 +215,22 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
MessageCommand::Write => return Ok(()), MessageCommand::Write => return Ok(()),
c => { c => {
return Err(RustADBError::ADBRequestFailed(format!( return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}", "Wrong command received {c}"
c )));
)))
} }
} }
} }
Ok(size) => { Ok(size) => {
let subcommand_data = MessageSubcommand::Data.with_arg(size as u32); let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(size)?);
let mut serialized_message = bincode::serialize(&subcommand_data) let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
.map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..size].to_vec()); serialized_message.append(&mut buffer[..size].to_vec());
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
serialized_message, &serialized_message,
); );
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
@@ -179,58 +242,76 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
} }
} }
pub(crate) fn begin_synchronization(&mut self) -> Result<(u32, u32)> { pub(crate) fn begin_synchronization(&mut self) -> Result<ADBSession> {
let sync_directive = "sync:\0"; self.open_session(b"sync:\0")
let mut rng = rand::thread_rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), /* Our 'local-id' */
0,
sync_directive.into(),
);
let message = self.send_and_expect_okay(message)?;
let local_id = message.header().arg1();
let remote_id = message.header().arg0();
Ok((local_id, remote_id))
} }
pub(crate) fn stat_with_explicit_ids( pub(crate) fn stat_with_explicit_ids(
&mut self, &mut self,
session: ADBSession,
remote_path: &str, remote_path: &str,
local_id: u32,
remote_id: u32,
) -> Result<AdbStatResponse> { ) -> Result<AdbStatResponse> {
let stat_buffer = MessageSubcommand::Stat.with_arg(remote_path.len() as u32); let stat_buffer = MessageSubcommand::Stat.with_arg(u32::try_from(remote_path.len())?);
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
bincode::serialize(&stat_buffer).map_err(|_e| RustADBError::ConversionError)?, &bincode_serialize_to_vec(&stat_buffer)?,
); );
self.send_and_expect_okay(message)?; self.send_and_expect_okay(message)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
remote_path.into(), remote_path.as_bytes(),
))?; ))?;
let response = self.transport.read_message()?; let response = self.transport.read_message()?;
// Skip first 4 bytes as this is the literal "STAT". // Skip first 4 bytes as this is the literal "STAT".
// Interesting part starts right after // Interesting part starts right after
bincode::deserialize(&response.into_payload()[4..])
.map_err(|_e| RustADBError::ConversionError) bincode_deserialize_from_slice(&response.into_payload()[4..])
} }
pub(crate) fn end_transaction(&mut self, local_id: u32, remote_id: u32) -> Result<()> { pub(crate) fn end_transaction(&mut self, session: ADBSession) -> Result<()> {
let quit_buffer = MessageSubcommand::Quit.with_arg(0u32); let quit_buffer = MessageSubcommand::Quit.with_arg(0u32);
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
bincode::serialize(&quit_buffer).map_err(|_e| RustADBError::ConversionError)?, &bincode_serialize_to_vec(&quit_buffer)?,
))?; ))?;
let _discard_close = self.transport.read_message()?; let _discard_close = self.transport.read_message()?;
Ok(()) Ok(())
} }
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<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()))
}
} }

View File

@@ -1,18 +1,17 @@
use crate::{models::AdbStatResponse, ADBDeviceExt, ADBMessageTransport, RebootType, Result}; use crate::{ADBDeviceExt, ADBMessageTransport, RebootType, Result, models::AdbStatResponse};
use std::io::{Read, Write}; use std::{
io::{Read, Write},
path::Path,
};
use super::ADBMessageDevice; use super::ADBMessageDevice;
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn shell_command<S: ToString, W: Write>( fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.shell_command(command, output) self.shell_command(command, output)
} }
fn shell<R: Read, W: Write + Send + 'static>(&mut self, reader: R, writer: W) -> Result<()> { fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
self.shell(reader, writer) self.shell(reader, writer)
} }
@@ -20,11 +19,11 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
self.stat(remote_path) self.stat(remote_path)
} }
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> { fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.pull(source, output) self.pull(source, output)
} }
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.push(stream, path) self.push(stream, path)
} }
@@ -32,7 +31,19 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
self.reboot(reboot_type) self.reboot(reboot_type)
} }
fn install<P: AsRef<std::path::Path>>(&mut self, apk_path: P) -> Result<()> { fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.install(apk_path) 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)
}
} }

View File

@@ -1,21 +1,43 @@
use std::net::SocketAddr; use std::io::Write;
use std::path::Path; use std::path::Path;
use std::{io::Read, net::SocketAddr};
use super::adb_message_device::ADBMessageDevice; use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand; use super::models::MessageCommand;
use super::ADBTransportMessage; use super::{ADBRsaKey, ADBTransportMessage, get_default_adb_key_path};
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, RustADBError, TcpTransport}; use crate::device::adb_usb_device::read_adb_private_key;
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, TcpTransport};
/// Represent a device reached and available over USB. /// Represent a device reached and available over TCP.
#[derive(Debug)] #[derive(Debug)]
pub struct ADBTcpDevice { pub struct ADBTcpDevice {
private_key: ADBRsaKey,
inner: ADBMessageDevice<TcpTransport>, inner: ADBMessageDevice<TcpTransport>,
} }
impl ADBTcpDevice { impl ADBTcpDevice {
/// Instantiate a new [`ADBTcpDevice`] /// Instantiate a new [`ADBTcpDevice`]
pub fn new(address: SocketAddr) -> Result<Self> { pub fn new(address: SocketAddr) -> Result<Self> {
Self::new_with_custom_private_key(address, get_default_adb_key_path()?)
}
/// Instantiate a new [`ADBTcpDevice`] using a custom private key path
pub fn new_with_custom_private_key<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 { let mut device = Self {
private_key,
inner: ADBMessageDevice::new(TcpTransport::new(address)?), inner: ADBMessageDevice::new(TcpTransport::new(address)?),
}; };
@@ -30,78 +52,94 @@ impl ADBTcpDevice {
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Cnxn, MessageCommand::Cnxn,
0x01000000, 0x0100_0000,
1048576, 1_048_576,
format!("host::{}\0", env!("CARGO_PKG_NAME")) format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
.as_bytes()
.to_vec(),
); );
self.get_transport_mut().write_message(message)?; self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?; let message = self.get_transport_mut().read_message()?;
// At this point, we should have received a STLS message // Check if a client is requesting a secure connection and upgrade it if necessary
if message.header().command() != MessageCommand::Stls { match message.header().command() {
return Err(RustADBError::ADBRequestFailed(format!( MessageCommand::Stls => {
"Wrong command received {}", self.get_transport_mut()
message.header().command() .write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
)));
};
let message = ADBTransportMessage::new(MessageCommand::Stls, 1, 0, vec![]);
self.get_transport_mut().write_message(message)?;
// Upgrade TCP connection to TLS
self.get_transport_mut().upgrade_connection()?; self.get_transport_mut().upgrade_connection()?;
log::debug!("Connection successfully upgraded from TCP to TLS"); log::debug!("Connection successfully upgraded from TCP to TLS");
Ok(()) 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 { fn get_transport_mut(&mut self) -> &mut TcpTransport {
self.inner.get_transport_mut() self.inner.get_transport_mut()
} }
} }
impl ADBDeviceExt for ADBTcpDevice { impl ADBDeviceExt for ADBTcpDevice {
fn shell_command<S: ToString, W: std::io::Write>( #[inline]
&mut self, fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.inner.shell_command(command, output) self.inner.shell_command(command, output)
} }
fn shell<R: std::io::Read, W: std::io::Write + Send + 'static>( #[inline]
&mut self, fn shell(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
reader: R,
writer: W,
) -> Result<()> {
self.inner.shell(reader, writer) self.inner.shell(reader, writer)
} }
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> { fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path) self.inner.stat(remote_path)
} }
fn pull<A: AsRef<str>, W: std::io::Write>(&mut self, source: A, output: W) -> Result<()> { #[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output) self.inner.pull(source, output)
} }
fn push<R: std::io::Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { #[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path) self.inner.push(stream, path)
} }
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> { fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type) self.inner.reboot(reboot_type)
} }
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> { #[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path) 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 { impl Drop for ADBTcpDevice {

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::RustADBError; use crate::{Result, RustADBError, device::adb_message_device};
use super::models::MessageCommand; use super::models::MessageCommand;
@@ -58,24 +58,24 @@ impl ADBTransportMessageHeader {
} }
pub(crate) fn compute_crc32(data: &[u8]) -> u32 { pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
data.iter().map(|&x| x as u32).sum() data.iter().map(|&x| u32::from(x)).sum()
} }
fn compute_magic(command: MessageCommand) -> u32 { fn compute_magic(command: MessageCommand) -> u32 {
let command_u32 = command as u32; let command_u32 = command as u32;
command_u32 ^ 0xFFFFFFFF command_u32 ^ 0xFFFF_FFFF
} }
pub fn as_bytes(&self) -> Result<Vec<u8>, RustADBError> { pub fn as_bytes(&self) -> Result<Vec<u8>> {
bincode::serialize(&self).map_err(|_e| RustADBError::ConversionError) adb_message_device::bincode_serialize_to_vec(self)
} }
} }
impl ADBTransportMessage { impl ADBTransportMessage {
pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: Vec<u8>) -> Self { pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: &[u8]) -> Self {
Self { Self {
header: ADBTransportMessageHeader::new(command, arg0, arg1, &data), header: ADBTransportMessageHeader::new(command, arg0, arg1, data),
payload: data, payload: data.to_vec(),
} }
} }
@@ -88,6 +88,18 @@ impl ADBTransportMessage {
&& ADBTransportMessageHeader::compute_crc32(&self.payload) == self.header.data_crc32 && 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 { pub fn header(&self) -> &ADBTransportMessageHeader {
&self.header &self.header
} }
@@ -104,7 +116,7 @@ impl ADBTransportMessage {
impl TryFrom<[u8; 24]> for ADBTransportMessageHeader { impl TryFrom<[u8; 24]> for ADBTransportMessageHeader {
type Error = RustADBError; type Error = RustADBError;
fn try_from(value: [u8; 24]) -> Result<Self, Self::Error> { fn try_from(value: [u8; 24]) -> Result<Self> {
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError) adb_message_device::bincode_deserialize_from_slice(&value)
} }
} }

View File

@@ -1,34 +1,40 @@
use rusb::Device; use rusb::Device;
use rusb::DeviceDescriptor; use rusb::DeviceDescriptor;
use rusb::UsbContext; use rusb::UsbContext;
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
use std::fs::read_to_string; use std::fs::read_to_string;
use std::io::Read;
use std::io::Write;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::Duration;
use super::adb_message_device::ADBMessageDevice; use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand; use super::models::MessageCommand;
use super::{ADBRsaKey, ADBTransportMessage}; use super::{ADBRsaKey, ADBTransportMessage};
use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::ADBDeviceExt; use crate::ADBDeviceExt;
use crate::ADBMessageTransport; use crate::ADBMessageTransport;
use crate::ADBTransport; use crate::ADBTransport;
use crate::{Result, RustADBError, USBTransport}; use crate::{Result, RustADBError, USBTransport};
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> { pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
Ok(read_to_string(private_key_path.as_ref()).map(|pk| { // 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) { match ADBRsaKey::new_from_pkcs8(&pk) {
Ok(pk) => Some(pk), Ok(pk) => Ok(Some(pk)),
Err(e) => { Err(e) => Err(e),
log::error!("Error while create RSA private key: {e}");
None
} }
}
})?)
} }
/// Search for adb devices with known interface class and subclass values /// Search for adb devices with known interface class and subclass values
fn search_adb_devices() -> Result<Option<(u16, u16)>> { pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
let mut found_devices = vec![]; let mut found_devices = vec![];
for device in rusb::devices()?.iter() { for device in rusb::devices()?.iter() {
let Ok(des) = device.device_descriptor() else { let Ok(des) = device.device_descriptor() else {
@@ -48,15 +54,13 @@ fn search_adb_devices() -> Result<Option<(u16, u16)>> {
(None, _) => Ok(None), (None, _) => Ok(None),
(Some(identifiers), None) => Ok(Some(*identifiers)), (Some(identifiers), None) => Ok(Some(*identifiers)),
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!( (Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
"Found two Android devices {:04x}:{:04x} and {:04x}:{:04x}", "Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
vid1, pid1, vid2, pid2
))), ))),
} }
} }
fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool { /// Check whether a device with given descriptor is an ADB device
const ADB_CLASS: u8 = 0xff; pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
const ADB_SUBCLASS: u8 = 0x42; const ADB_SUBCLASS: u8 = 0x42;
const ADB_PROTOCOL: u8 = 0x1; const ADB_PROTOCOL: u8 = 0x1;
@@ -75,7 +79,7 @@ fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> b
let class = interface_des.class_code(); let class = interface_des.class_code();
let subcl = interface_des.sub_class_code(); let subcl = interface_des.sub_class_code();
if proto == ADB_PROTOCOL if proto == ADB_PROTOCOL
&& ((class == ADB_CLASS && subcl == ADB_SUBCLASS) && ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS)) || (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
{ {
return true; return true;
@@ -87,9 +91,7 @@ fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> b
} }
pub fn get_default_adb_key_path() -> Result<PathBuf> { pub fn get_default_adb_key_path() -> Result<PathBuf> {
homedir::my_home() std::env::home_dir()
.ok()
.flatten()
.map(|home| home.join(".android").join("adbkey")) .map(|home| home.join(".android").join("adbkey"))
.ok_or(RustADBError::NoHomeDirectory) .ok_or(RustADBError::NoHomeDirectory)
} }
@@ -108,10 +110,10 @@ impl ADBUSBDevice {
} }
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path /// Instantiate a new [`ADBUSBDevice`] using a custom private key path
pub fn new_with_custom_private_key( pub fn new_with_custom_private_key<P: AsRef<Path>>(
vendor_id: u16, vendor_id: u16,
product_id: u16, product_id: u16,
private_key_path: PathBuf, private_key_path: P,
) -> Result<Self> { ) -> Result<Self> {
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path) Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
} }
@@ -126,16 +128,21 @@ impl ADBUSBDevice {
None => get_default_adb_key_path()?, None => get_default_adb_key_path()?,
}; };
Self::new_from_transport_inner(transport, private_key_path) Self::new_from_transport_inner(transport, &private_key_path)
} }
fn new_from_transport_inner( fn new_from_transport_inner<P: AsRef<Path>>(
transport: USBTransport, transport: USBTransport,
private_key_path: PathBuf, private_key_path: P,
) -> Result<Self> { ) -> Result<Self> {
let private_key = match read_adb_private_key(private_key_path)? { let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
Some(pk) => pk, private_key
None => ADBRsaKey::new_random()?, } 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 { let mut s = Self {
@@ -171,119 +178,79 @@ impl ADBUSBDevice {
let message = ADBTransportMessage::new( let message = ADBTransportMessage::new(
MessageCommand::Cnxn, MessageCommand::Cnxn,
0x01000000, 0x0100_0000,
1048576, 1_048_576,
format!("host::{}\0", env!("CARGO_PKG_NAME")) format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
.as_bytes()
.to_vec(),
); );
self.get_transport_mut().write_message(message)?; self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?; let message = self.get_transport_mut().read_message()?;
// If the device returned CNXN instead of AUTH it does not require authentication,
// At this point, we should have received either: // so we can skip the auth steps.
// - an AUTH message with arg0 == 1 if message.header().command() == MessageCommand::Cnxn {
// - a CNXN message
let auth_message = match message.header().command() {
MessageCommand::Auth if message.header().arg0() == AUTH_TOKEN => message,
MessageCommand::Auth if message.header().arg0() != AUTH_TOKEN => {
return Err(RustADBError::ADBRequestFailed(
"Received AUTH message with type != 1".into(),
))
}
c => {
return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
)))
}
};
let sign = self.private_key.sign(auth_message.into_payload())?;
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, sign);
self.get_transport_mut().write_message(message)?;
let received_response = self.get_transport_mut().read_message()?;
if received_response.header().command() == MessageCommand::Cnxn {
log::info!(
"Authentication OK, device info {}",
String::from_utf8(received_response.into_payload())?
);
return Ok(()); return Ok(());
} }
let mut pubkey = self.private_key.android_pubkey_encode()?.into_bytes(); message.assert_command(MessageCommand::Auth)?;
pubkey.push(b'\0'); self.inner.auth_handshake(message, &self.private_key)
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))?;
match response.header().command() {
MessageCommand::Cnxn => log::info!(
"Authentication OK, device info {}",
String::from_utf8(response.into_payload())?
),
_ => {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong response {}",
response.header().command()
)))
}
}
Ok(())
} }
#[inline]
fn get_transport_mut(&mut self) -> &mut USBTransport { fn get_transport_mut(&mut self) -> &mut USBTransport {
self.inner.get_transport_mut() self.inner.get_transport_mut()
} }
} }
impl ADBDeviceExt for ADBUSBDevice { impl ADBDeviceExt for ADBUSBDevice {
fn shell_command<S: ToString, W: std::io::Write>( #[inline]
&mut self, fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.inner.shell_command(command, output) self.inner.shell_command(command, output)
} }
fn shell<R: std::io::Read, W: std::io::Write + Send + 'static>( #[inline]
&mut self, fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
reader: R,
writer: W,
) -> Result<()> {
self.inner.shell(reader, writer) self.inner.shell(reader, writer)
} }
#[inline]
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> { fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path) self.inner.stat(remote_path)
} }
fn pull<A: AsRef<str>, W: std::io::Write>(&mut self, source: A, output: W) -> Result<()> { #[inline]
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
self.inner.pull(source, output) self.inner.pull(source, output)
} }
fn push<R: std::io::Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { #[inline]
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.inner.push(stream, path) self.inner.push(stream, path)
} }
#[inline]
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> { fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type) self.inner.reboot(reboot_type)
} }
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> { #[inline]
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.inner.install(apk_path) 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 { impl Drop for ADBUSBDevice {

View File

@@ -0,0 +1,98 @@
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)
}
}

View File

@@ -1,43 +1,25 @@
use std::fs::File; use std::{fs::File, path::Path};
use rand::Rng;
use crate::{ use crate::{
device::{
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand, MessageWriter,
},
utils::check_extension_is_apk,
ADBMessageTransport, Result, ADBMessageTransport, Result,
device::{MessageWriter, adb_message_device::ADBMessageDevice},
utils::check_extension_is_apk,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn install<P: AsRef<std::path::Path>>(&mut self, apk_path: P) -> Result<()> { pub(crate) fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
let mut apk_file = File::open(&apk_path)?; let mut apk_file = File::open(apk_path)?;
check_extension_is_apk(&apk_path)?; check_extension_is_apk(apk_path)?;
let file_size = apk_file.metadata()?.len(); let file_size = apk_file.metadata()?.len();
let mut rng = rand::thread_rng(); let session =
self.open_session(format!("exec:cmd package 'install' -S {file_size}\0").as_bytes())?;
let local_id = rng.gen();
let message = ADBTransportMessage::new(
MessageCommand::Open,
local_id,
0,
format!("exec:cmd package 'install' -S {}\0", file_size)
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let response = self.get_transport_mut().read_message()?;
let remote_id = response.header().arg0();
let transport = self.get_transport().clone(); let transport = self.get_transport().clone();
let mut writer = MessageWriter::new(transport, local_id, remote_id); let mut writer = MessageWriter::new(transport, session.local_id(), session.remote_id());
std::io::copy(&mut apk_file, &mut writer)?; std::io::copy(&mut apk_file, &mut writer)?;

View File

@@ -0,0 +1,177 @@
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}"),
}
}
}
}

View File

@@ -1,6 +1,9 @@
mod framebuffer;
mod install; mod install;
mod list;
mod pull; mod pull;
mod push; mod push;
mod reboot; mod reboot;
mod shell; mod shell;
mod stat; mod stat;
mod uninstall;

View File

@@ -1,19 +1,20 @@
use std::io::Write; use std::io::Write;
use crate::{ use crate::{
device::{
adb_message_device::ADBMessageDevice, models::MessageSubcommand, ADBTransportMessage,
MessageCommand,
},
ADBMessageTransport, Result, RustADBError, ADBMessageTransport, Result, RustADBError,
device::{
ADBTransportMessage, MessageCommand,
adb_message_device::{self, ADBMessageDevice},
models::MessageSubcommand,
},
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> { pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
let (local_id, remote_id) = self.begin_synchronization()?; let session = self.begin_synchronization()?;
let source = source.as_ref(); let source = source.as_ref();
let adb_stat_response = self.stat_with_explicit_ids(source, local_id, remote_id)?; let adb_stat_response = self.stat_with_explicit_ids(session, source)?;
if adb_stat_response.file_perm == 0 { if adb_stat_response.file_perm == 0 {
return Err(RustADBError::UnknownResponseType( return Err(RustADBError::UnknownResponseType(
@@ -22,28 +23,32 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
} }
self.get_transport_mut().write_message_with_timeout( self.get_transport_mut().write_message_with_timeout(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, "".into()), ADBTransportMessage::new(
MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
),
std::time::Duration::from_secs(4), std::time::Duration::from_secs(4),
)?; )?;
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32); let recv_buffer = MessageSubcommand::Recv.with_arg(u32::try_from(source.len())?);
let recv_buffer = let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?;
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
recv_buffer, &recv_buffer,
))?; ))?;
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
source.into(), source.as_bytes(),
))?; ))?;
self.recv_file(local_id, remote_id, output)?; self.recv_file(session, output)?;
self.end_transaction(local_id, remote_id)?; self.end_transaction(session)?;
Ok(()) Ok(())
} }
} }

View File

@@ -1,34 +1,32 @@
use std::io::Read; use std::io::Read;
use crate::{ use crate::{
ADBMessageTransport, Result,
device::{ device::{
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand, ADBTransportMessage, MessageCommand, MessageSubcommand,
MessageSubcommand, adb_message_device::{self, ADBMessageDevice},
}, },
ADBMessageTransport, Result, RustADBError,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
let (local_id, remote_id) = self.begin_synchronization()?; let session = self.begin_synchronization()?;
let path_header = format!("{},0777", path.as_ref()); let path_header = format!("{},0777", path.as_ref());
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32); let send_buffer = MessageSubcommand::Send.with_arg(u32::try_from(path_header.len())?);
let mut send_buffer = let mut send_buffer = adb_message_device::bincode_serialize_to_vec(&send_buffer)?;
bincode::serialize(&send_buffer).map_err(|_e| RustADBError::ConversionError)?;
send_buffer.append(&mut path_header.as_bytes().to_vec()); send_buffer.append(&mut path_header.as_bytes().to_vec());
self.send_and_expect_okay(ADBTransportMessage::new( self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write, MessageCommand::Write,
local_id, session.local_id(),
remote_id, session.remote_id(),
send_buffer, &send_buffer,
))?; ))?;
self.push_file(local_id, remote_id, stream)?; self.push_file(session, stream)?;
self.end_transaction(session)?;
self.end_transaction(local_id, remote_id)?;
Ok(()) Ok(())
} }

View File

@@ -1,28 +1,14 @@
use rand::Rng;
use crate::{ use crate::{
device::{adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand}, ADBMessageTransport, RebootType, Result,
ADBMessageTransport, RebootType, Result, RustADBError, device::{MessageCommand, adb_message_device::ADBMessageDevice},
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> { pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
let mut rng = rand::thread_rng(); self.open_session(format!("reboot:{reboot_type}\0").as_bytes())?;
let message = ADBTransportMessage::new( self.get_transport_mut()
MessageCommand::Open, .read_message()
rng.gen(), // Our 'local-id' .and_then(|message| message.assert_command(MessageCommand::Okay))
0,
format!("reboot:{}\0", reboot_type).as_bytes().to_vec(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
if message.header().command() != MessageCommand::Okay {
return Err(RustADBError::ADBShellNotSupported);
}
Ok(())
} }
} }

View File

@@ -1,77 +1,56 @@
use rand::Rng; use std::io::{ErrorKind, Read, Write};
use std::io::{Read, Write}; use std::time::Duration;
use crate::device::ShellMessageWriter;
use crate::Result; use crate::Result;
use crate::device::ShellMessageWriter;
use crate::{ use crate::{
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
ADBMessageTransport, RustADBError, ADBMessageTransport, RustADBError,
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Runs 'command' in a shell on the device, and write its output and error streams into [`output`]. /// Runs 'command' in a shell on the device, and write its output and error streams into output.
pub(crate) fn shell_command<S: ToString, W: Write>( pub(crate) fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
&mut self, let session = self.open_session(format!("shell:{}\0", command.join(" "),).as_bytes())?;
command: impl IntoIterator<Item = S>,
mut output: W,
) -> Result<()> {
let message = ADBTransportMessage::new(
MessageCommand::Open,
1,
0,
format!(
"shell:{}\0",
command
.into_iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
)
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let response = self.get_transport_mut().read_message()?; let mut transport = self.get_transport().clone();
if response.header().command() != MessageCommand::Okay {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong command {}",
response.header().command()
)));
}
loop { loop {
let response = self.get_transport_mut().read_message()?; let message = transport.read_message()?;
if response.header().command() != MessageCommand::Write { let command = message.header().command();
if command == MessageCommand::Clse {
break; break;
} }
output.write_all(&response.into_payload())?; 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(()) Ok(())
} }
/// Starts an interactive shell session on the device. /// Starts an interactive shell session on the device.
/// Input data is read from [reader] and write to [writer]. /// Input data is read from [reader] and write to [writer].
/// [W] has a 'static bound as it is internally used in a thread. pub(crate) fn shell(
pub(crate) fn shell<R: Read, W: Write + Send + 'static>(
&mut self, &mut self,
mut reader: R, mut reader: &mut dyn Read,
mut writer: W, mut writer: Box<dyn Write + Send>,
) -> Result<()> { ) -> Result<()> {
let sync_directive = "shell:\0"; let session = self.open_session(b"shell:\0")?;
let mut rng = rand::thread_rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), /* Our 'local-id' */
0,
sync_directive.into(),
);
let message = self.send_and_expect_okay(message)?;
let local_id = message.header().arg1();
let remote_id = message.header().arg0();
let mut transport = self.get_transport().clone(); let mut transport = self.get_transport().clone();
@@ -81,28 +60,33 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let message = transport.read_message()?; let message = transport.read_message()?;
// Acknowledge for more data // Acknowledge for more data
let response = let response = ADBTransportMessage::new(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, vec![]); MessageCommand::Okay,
session.local_id(),
session.remote_id(),
&[],
);
transport.write_message(response)?; transport.write_message(response)?;
match message.header().command() { match message.header().command() {
MessageCommand::Write => {} MessageCommand::Write => {
MessageCommand::Okay => continue,
_ => return Err(RustADBError::ADBShellNotSupported),
}
writer.write_all(&message.into_payload())?; writer.write_all(&message.into_payload())?;
writer.flush()?; writer.flush()?;
} }
MessageCommand::Okay => {}
_ => return Err(RustADBError::ADBShellNotSupported),
}
}
}); });
let transport = self.get_transport().clone(); let transport = self.get_transport().clone();
let mut shell_writer = ShellMessageWriter::new(transport, local_id, remote_id); 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 // 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) { if let Err(e) = std::io::copy(&mut reader, &mut shell_writer) {
match e.kind() { match e.kind() {
std::io::ErrorKind::BrokenPipe => return Ok(()), ErrorKind::BrokenPipe => return Ok(()),
_ => return Err(RustADBError::IOError(e)), _ => return Err(RustADBError::IOError(e)),
} }
} }

View File

@@ -1,12 +1,12 @@
use crate::{ use crate::{
device::adb_message_device::ADBMessageDevice, ADBMessageTransport, AdbStatResponse, Result, ADBMessageTransport, AdbStatResponse, Result, device::adb_message_device::ADBMessageDevice,
}; };
impl<T: ADBMessageTransport> ADBMessageDevice<T> { impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> { pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
let (local_id, remote_id) = self.begin_synchronization()?; let session = self.begin_synchronization()?;
let adb_stat_response = self.stat_with_explicit_ids(remote_path, local_id, remote_id)?; let adb_stat_response = self.stat_with_explicit_ids(session, remote_path)?;
self.end_transaction(local_id, remote_id)?; self.end_transaction(session)?;
Ok(adb_stat_response) Ok(adb_stat_response)
} }
} }

View File

@@ -0,0 +1,19 @@
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(),
)?)),
}
}
}

View File

@@ -1,4 +1,4 @@
use std::io::{ErrorKind, Write}; use std::io::{Error, ErrorKind, Result, Write};
use crate::ADBMessageTransport; use crate::ADBMessageTransport;
@@ -24,30 +24,25 @@ impl<T: ADBMessageTransport> MessageWriter<T> {
} }
impl<T: ADBMessageTransport> Write for MessageWriter<T> { impl<T: ADBMessageTransport> Write for MessageWriter<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> Result<usize> {
let message = ADBTransportMessage::new( let message =
MessageCommand::Write, ADBTransportMessage::new(MessageCommand::Write, self.local_id, self.remote_id, buf);
self.local_id,
self.remote_id,
buf.to_vec(),
);
self.transport self.transport
.write_message(message) .write_message(message)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; .map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
match self.transport.read_message() { match self.transport.read_message() {
Ok(response) => match response.header().command() { Ok(response) => {
MessageCommand::Okay => Ok(buf.len()), response
c => Err(std::io::Error::new( .assert_command(MessageCommand::Okay)
ErrorKind::Other, .map_err(Error::other)?;
format!("wrong response received: {c}"), Ok(buf.len())
)), }
}, Err(e) => Err(Error::other(e)),
Err(e) => Err(std::io::Error::new(ErrorKind::Other, e)),
} }
} }
fn flush(&mut self) -> std::io::Result<()> { fn flush(&mut self) -> Result<()> {
Ok(()) Ok(())
} }
} }

View File

@@ -11,7 +11,9 @@ mod shell_message_writer;
use adb_message_device::ADBMessageDevice; use adb_message_device::ADBMessageDevice;
pub use adb_tcp_device::ADBTcpDevice; pub use adb_tcp_device::ADBTcpDevice;
pub use adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader}; pub use adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader};
pub use adb_usb_device::{get_default_adb_key_path, ADBUSBDevice}; pub use adb_usb_device::{
ADBUSBDevice, get_default_adb_key_path, is_adb_device, search_adb_devices,
};
pub use message_writer::MessageWriter; pub use message_writer::MessageWriter;
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand}; pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
pub use shell_message_writer::ShellMessageWriter; pub use shell_message_writer::ShellMessageWriter;

View File

@@ -1,12 +1,12 @@
use crate::{Result, RustADBError}; use crate::{Result, RustADBError};
use base64::{engine::general_purpose::STANDARD, Engine}; use base64::{Engine, engine::general_purpose::STANDARD};
use num_bigint::{BigUint, ModInverse}; use num_bigint::{BigUint, ModInverse};
use num_traits::cast::ToPrimitive;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use rand::rngs::OsRng; use num_traits::cast::ToPrimitive;
use rsa::pkcs8::DecodePrivateKey; use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PublicKeyParts; use rsa::traits::PublicKeyParts;
use rsa::{Pkcs1v15Sign, RsaPrivateKey}; use rsa::{Pkcs1v15Sign, RsaPrivateKey};
use std::fmt::Write;
const ADB_PRIVATE_KEY_SIZE: usize = 2048; const ADB_PRIVATE_KEY_SIZE: usize = 2048;
const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64; const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64;
@@ -52,7 +52,7 @@ pub struct ADBRsaKey {
impl ADBRsaKey { impl ADBRsaKey {
pub fn new_random() -> Result<Self> { pub fn new_random() -> Result<Self> {
Ok(Self { Ok(Self {
private_key: RsaPrivateKey::new(&mut OsRng, ADB_PRIVATE_KEY_SIZE)?, private_key: RsaPrivateKey::new(&mut rsa::rand_core::OsRng, ADB_PRIVATE_KEY_SIZE)?,
}) })
} }
@@ -93,15 +93,16 @@ impl ADBRsaKey {
.to_u32() .to_u32()
.ok_or(RustADBError::ConversionError)?; .ok_or(RustADBError::ConversionError)?;
Ok(self.encode_public_key(adb_rsa_pubkey.into_bytes())) Self::encode_public_key(adb_rsa_pubkey.into_bytes())
} }
fn encode_public_key(&self, pub_key: Vec<u8>) -> String { fn encode_public_key(pub_key: Vec<u8>) -> Result<String> {
let mut encoded = STANDARD.encode(pub_key); let mut encoded = STANDARD.encode(pub_key);
encoded.push(' '); encoded.push(' ');
encoded.push_str(&format!("adb_client@{}", env!("CARGO_PKG_VERSION"))); write!(encoded, "adb_client@{}", env!("CARGO_PKG_VERSION"))
.map_err(|_| RustADBError::ConversionError)?;
encoded Ok(encoded)
} }
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> { pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
@@ -125,7 +126,7 @@ fn set_bit(n: usize) -> Result<BigUint> {
#[test] #[test]
fn test_pubkey_gen() { fn test_pubkey_gen() {
const DEFAULT_PRIV_KEY: &'static str = r"-----BEGIN PRIVATE KEY----- const DEFAULT_PRIV_KEY: &str = r"-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4Dyn85cxDJnjM MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4Dyn85cxDJnjM
uYXQl/w469MDKdlGdviLfmFMWeYLVfL2Mz1AVyvKqscrtlhbbgMQ/M+3lDvEdHS0 uYXQl/w469MDKdlGdviLfmFMWeYLVfL2Mz1AVyvKqscrtlhbbgMQ/M+3lDvEdHS0
14RIGAwWRtrlTTmhLvM2/IO+eSKSYeCrCVc4KLG3E3WRryUXbs2ynA29xjTJVw+Z 14RIGAwWRtrlTTmhLvM2/IO+eSKSYeCrCVc4KLG3E3WRryUXbs2ynA29xjTJVw+Z

View File

@@ -0,0 +1,23 @@
/// 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
}
}

View File

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

View File

@@ -1,5 +1,7 @@
mod adb_rsa_key; mod adb_rsa_key;
mod adb_session;
mod message_commands; mod message_commands;
pub use adb_rsa_key::ADBRsaKey; pub use adb_rsa_key::ADBRsaKey;
pub(crate) use adb_session::ADBSession;
pub use message_commands::{MessageCommand, MessageSubcommand}; pub use message_commands::{MessageCommand, MessageSubcommand};

View File

@@ -2,7 +2,7 @@ use std::io::Write;
use crate::ADBMessageTransport; use crate::ADBMessageTransport;
use super::{models::MessageCommand, ADBTransportMessage}; use super::{ADBTransportMessage, models::MessageCommand};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands. /// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
pub struct ShellMessageWriter<T: ADBMessageTransport> { pub struct ShellMessageWriter<T: ADBMessageTransport> {
@@ -23,12 +23,8 @@ impl<T: ADBMessageTransport> ShellMessageWriter<T> {
impl<T: ADBMessageTransport> Write for ShellMessageWriter<T> { impl<T: ADBMessageTransport> Write for ShellMessageWriter<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let message = ADBTransportMessage::new( let message =
MessageCommand::Write, ADBTransportMessage::new(MessageCommand::Write, self.local_id, self.remote_id, buf);
self.local_id,
self.remote_id,
buf.to_vec(),
);
self.transport self.transport
.write_message(message) .write_message(message)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

View File

@@ -15,23 +15,22 @@ static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
pub struct ADBEmulatorDevice { pub struct ADBEmulatorDevice {
/// Unique device identifier. /// Unique device identifier.
pub identifier: String, pub identifier: String,
/// Internal [TCPEmulatorTransport] /// Internal [`TCPEmulatorTransport`]
transport: TCPEmulatorTransport, transport: TCPEmulatorTransport,
} }
impl ADBEmulatorDevice { impl ADBEmulatorDevice {
/// Instantiates a new [ADBEmulatorDevice] /// Instantiates a new [`ADBEmulatorDevice`]
pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> { pub fn new(identifier: String, ip_address: Option<Ipv4Addr>) -> Result<Self> {
let ip_address = match ip_address { let ip_address = match ip_address {
Some(ip_address) => ip_address, Some(ip_address) => ip_address,
None => Ipv4Addr::new(127, 0, 0, 1), None => Ipv4Addr::LOCALHOST,
}; };
let groups = EMULATOR_REGEX let groups = EMULATOR_REGEX
.captures(&identifier) .captures(&identifier)
.ok_or(RustADBError::DeviceNotFound(format!( .ok_or(RustADBError::DeviceNotFound(format!(
"Device {} is likely not an emulator", "Device {identifier} is likely not an emulator"
identifier
)))?; )))?;
let port = groups let port = groups
@@ -65,10 +64,15 @@ 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> {
ADBEmulatorDevice::new( match &value.identifier {
value.identifier.clone(), Some(device_identifier) => ADBEmulatorDevice::new(
Some(*value.get_transport().get_socketaddr().ip()), device_identifier.clone(),
) Some(*value.transport.get_socketaddr().ip()),
),
None => Err(RustADBError::DeviceNotFound(
"cannot connect to an emulator device without knowing its identifier".to_string(),
)),
}
} }
} }

View File

@@ -1,10 +1,8 @@
use crate::{models::ADBEmulatorCommand, ADBEmulatorDevice, Result}; use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
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 rotate(&mut self) -> Result<()> { pub fn rotate(&mut self) -> Result<()> {
let transport = self.connect()?; self.connect()?.send_command(&ADBEmulatorCommand::Rotate)
transport.send_command(ADBEmulatorCommand::Rotate)?;
Ok(())
} }
} }

View File

@@ -1,13 +1,11 @@
use crate::{models::ADBEmulatorCommand, ADBEmulatorDevice, Result}; use crate::{ADBEmulatorDevice, Result, emulator_device::ADBEmulatorCommand};
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<()> {
let transport = self.connect()?; self.connect()?.send_command(&ADBEmulatorCommand::Sms(
transport.send_command(ADBEmulatorCommand::Sms(
phone_number.to_string(), phone_number.to_string(),
content.to_string(), content.to_string(),
))?; ))
Ok(())
} }
} }

View File

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

View File

@@ -1,6 +1,6 @@
use std::fmt::Display; use std::fmt::Display;
pub(crate) enum ADBEmulatorCommand { pub enum ADBEmulatorCommand {
Authenticate(String), Authenticate(String),
Sms(String, String), Sms(String, String),
Rotate, Rotate,
@@ -24,8 +24,7 @@ impl ADBEmulatorCommand {
pub(crate) fn skip_response_lines(&self) -> u8 { pub(crate) fn skip_response_lines(&self) -> u8 {
match self { match self {
ADBEmulatorCommand::Authenticate(_) => 1, ADBEmulatorCommand::Authenticate(_) => 1,
ADBEmulatorCommand::Sms(_, _) => 0, ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
ADBEmulatorCommand::Rotate => 0,
} }
} }
} }

View File

@@ -0,0 +1,2 @@
mod adb_emulator_command;
pub use adb_emulator_command::ADBEmulatorCommand;

View File

@@ -15,6 +15,9 @@ 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),
@@ -39,6 +42,9 @@ pub enum RustADBError {
/// Indicates that an error occurred when converting a value. /// Indicates that an error occurred when converting a value.
#[error("Conversion error")] #[error("Conversion error")]
ConversionError, ConversionError,
/// Indicates an error with the integer conversion.
#[error(transparent)]
IntegerConversionError(#[from] std::num::TryFromIntError),
/// Remote ADB server does not support shell feature. /// Remote ADB server does not support shell feature.
#[error("Remote ADB server does not support shell feature")] #[error("Remote ADB server does not support shell feature")]
ADBShellNotSupported, ADBShellNotSupported,
@@ -58,13 +64,13 @@ pub enum RustADBError {
#[error("Unimplemented framebuffer image version: {0}")] #[error("Unimplemented framebuffer image version: {0}")]
UnimplementedFramebufferImageVersion(u32), UnimplementedFramebufferImageVersion(u32),
/// An error occurred while getting user's home directory /// An error occurred while getting user's home directory
#[error(transparent)] #[error("Cannot get user home directory")]
HomeError(#[from] homedir::GetHomeError), HomeError,
/// Cannot get home directory /// Cannot get home directory
#[error("Cannot get home directory")] #[error("Cannot get home directory")]
NoHomeDirectory, NoHomeDirectory,
/// Generic USB error /// Generic USB error
#[error(transparent)] #[error("USB Error: {0}")]
UsbError(#[from] rusb::Error), UsbError(#[from] rusb::Error),
/// USB device not found /// USB device not found
#[error("USB Device not found: {0} {1}")] #[error("USB Device not found: {0} {1}")]
@@ -109,11 +115,19 @@ pub enum RustADBError {
#[error("upgrade error: {0}")] #[error("upgrade error: {0}")]
UpgradeError(String), UpgradeError(String),
/// An error occurred while getting mdns devices /// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)] #[error(transparent)]
MDNSError(#[from] mdns_sd::Error), MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel /// An error occurred while sending data to channel
#[error(transparent)] #[error("error sending data to channel")]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>), SendError,
/// An unknown transport has been provided
#[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 { impl<T> From<std::sync::PoisonError<T>> for RustADBError {

View File

@@ -3,13 +3,23 @@
#![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_device_ext;
mod constants; mod constants;
mod device; mod device;
mod emulator_device; mod emulator_device;
mod error; mod error;
mod mdns;
/// 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 server_device;
@@ -17,13 +27,10 @@ mod transports;
mod utils; mod utils;
pub use adb_device_ext::ADBDeviceExt; pub use adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice}; pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice; pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError}; pub use error::{Result, RustADBError};
pub use mdns::*; pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use models::{
AdbStatResponse, AdbVersion, DeviceLong, DeviceShort, DeviceState, MDNSBackend, RebootType,
};
pub use server::*; pub use server::*;
pub use server_device::ADBServerDevice; pub use server_device::ADBServerDevice;
pub use transports::*; pub use transports::*;

View File

@@ -1,4 +1,10 @@
use std::{collections::HashSet, net::IpAddr}; use std::{
collections::HashSet,
fmt::Display,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
use mdns_sd::{ResolvedService, ScopedIp};
/// Represent a device found from mdns search /// Represent a device found from mdns search
#[derive(Debug)] #[derive(Debug)]
@@ -6,14 +12,58 @@ pub struct MDNSDevice {
/// Full device address when resolved /// Full device address when resolved
pub fullname: String, pub fullname: String,
/// Device IP addresses /// Device IP addresses
pub addresses: HashSet<IpAddr>, addresses: HashSet<IpAddr>,
} }
impl From<mdns_sd::ServiceInfo> for MDNSDevice { impl MDNSDevice {
fn from(value: mdns_sd::ServiceInfo) -> Self { /// 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 { Self {
fullname: value.get_fullname().to_string(), fullname: value.fullname,
addresses: value.get_addresses().to_owned(), addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
} }
} }
} }
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(())
}
}

View File

@@ -1,7 +1,8 @@
use mdns_sd::{ServiceDaemon, ServiceEvent}; use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle}; use std::{sync::mpsc::Sender, thread::JoinHandle};
use crate::{MDNSDevice, Result, RustADBError}; use super::MDNSDevice;
use crate::{Result, RustADBError};
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local."; const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
@@ -29,11 +30,12 @@ impl MDNSDiscoveryService {
}) })
} }
/// Start discovery by spawning a new thread responsible of getting events. /// Start discovery by spawning a new background thread responsible of getting events.
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> { pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?; let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
let handle: JoinHandle<Result<()>> = std::thread::spawn(move || loop { let handle: JoinHandle<Result<()>> = std::thread::spawn(move || {
loop {
while let Ok(event) = receiver.recv() { while let Ok(event) = receiver.recv() {
match event { match event {
ServiceEvent::SearchStarted(_) ServiceEvent::SearchStarted(_)
@@ -41,11 +43,14 @@ impl MDNSDiscoveryService {
| ServiceEvent::ServiceFound(_, _) | ServiceEvent::ServiceFound(_, _)
| ServiceEvent::SearchStopped(_) => { | ServiceEvent::SearchStopped(_) => {
// Ignoring these events. We are only interesting in found devices // Ignoring these events. We are only interesting in found devices
continue;
} }
ServiceEvent::ServiceResolved(service_info) => { ServiceEvent::ServiceResolved(service_info) => {
if let Err(e) = sender.send(MDNSDevice::from(service_info)) { sender
return Err(e.into()); .send(MDNSDevice::from(service_info))
.map_err(|_| RustADBError::SendError)?;
}
e => {
log::warn!("received unknown event type {e:?}");
} }
} }
} }

View File

@@ -1,5 +1,7 @@
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;
@@ -20,9 +22,11 @@ pub(crate) enum AdbServerCommand {
MDNSServices, MDNSServices,
ServerStatus, ServerStatus,
ReconnectOffline, ReconnectOffline,
Uninstall(String),
Install(u64), Install(u64),
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
// Local commands // Local commands
ShellCommand(String), ShellCommand(String, Vec<String>),
Shell, Shell,
FrameBuffer, FrameBuffer,
Sync, Sync,
@@ -47,10 +51,14 @@ 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) => match std::env::var("TERM") { AdbServerCommand::ShellCommand(command, args) => {
Ok(term) => write!(f, "shell,TERM={term},raw:{command}"), let args_s = args.join(",");
Err(_) => write!(f, "shell,raw:{command}"), write!(
}, 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:"),
@@ -59,8 +67,8 @@ impl Display for AdbServerCommand {
AdbServerCommand::Reboot(reboot_type) => { AdbServerCommand::Reboot(reboot_type) => {
write!(f, "reboot:{reboot_type}") write!(f, "reboot:{reboot_type}")
} }
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{}", addr), AdbServerCommand::Connect(addr) => write!(f, "host:connect:{addr}"),
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{}", addr), AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{addr}"),
AdbServerCommand::Pair(addr, code) => { AdbServerCommand::Pair(addr, code) => {
write!(f, "host:pair:{code}:{addr}") write!(f, "host:pair:{code}:{addr}")
} }
@@ -83,6 +91,15 @@ impl Display for AdbServerCommand {
} }
AdbServerCommand::Usb => write!(f, "usb:"), AdbServerCommand::Usb => write!(f, "usb:"),
AdbServerCommand::Install(size) => write!(f, "exec:cmd package 'install' -S {size}"), 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}"
)
}
} }
} }
} }

View File

@@ -0,0 +1,97 @@
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)?,
})
}
}

View File

@@ -0,0 +1,25 @@
#[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,
}

View File

@@ -1,28 +1,17 @@
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_stat_response;
mod adb_version; mod framebuffer_info;
mod device_long;
mod device_short;
mod device_state;
mod host_features; mod host_features;
mod mdns_services; mod list_info;
mod reboot_type; mod reboot_type;
mod server_status;
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_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 mdns_services::MDNSServices; pub use list_info::{ADBListItem, ADBListItemType};
pub use reboot_type::RebootType; pub use reboot_type::RebootType;
pub use server_status::MDNSBackend;
pub use server_status::ServerStatus;
pub use sync_command::SyncCommand; pub use sync_command::SyncCommand;

View File

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

View File

@@ -9,21 +9,64 @@ use std::process::Command;
/// Represents an ADB Server /// Represents an ADB Server
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct ADBServer { pub struct ADBServer {
/// Internal [TcpStream], lazily initialized /// Internal [`TcpStream`], lazily initialized
pub(crate) transport: Option<TCPServerTransport>, pub(crate) transport: Option<TCPServerTransport>,
/// Address to connect to /// Address to connect to
pub(crate) socket_addr: Option<SocketAddrV4>, pub(crate) socket_addr: Option<SocketAddrV4>,
/// adb-server start envs /// adb-server start envs
pub(crate) envs: HashMap<String, String>, pub(crate) envs: HashMap<String, String>,
/// Path to adb binary
/// If not set, will use adb from PATH
pub(crate) adb_path: Option<String>,
} }
impl ADBServer { impl ADBServer {
/// Instantiates a new [ADBServer] /// Instantiates a new [`ADBServer`]
#[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(), 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}"),
} }
} }
@@ -52,22 +95,7 @@ impl ADBServer {
}; };
if is_local_ip { if is_local_ip {
// ADB Server is local, we start it if not already running Self::start(&self.envs, &self.adb_path);
let mut command = Command::new("adb");
command.arg("start-server");
for (env_k, env_v) in self.envs.iter() {
command.env(env_k, env_v);
}
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}"),
}
} }
transport.connect()?; transport.connect()?;
@@ -79,7 +107,7 @@ impl ADBServer {
impl Drop for ADBServer { impl Drop for ADBServer {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(ref mut transport) = &mut self.transport { if let Some(transport) = &mut self.transport {
let _ = transport.disconnect(); let _ = transport.disconnect();
} }
} }

View File

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

View File

@@ -1,8 +1,8 @@
use std::io::Read; use std::io::Read;
use crate::{ use crate::{
models::{AdbServerCommand, DeviceShort}, ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, DeviceShort, Result, RustADBError,
ADBEmulatorDevice, ADBServer, ADBServerDevice, DeviceLong, Result, RustADBError, models::AdbServerCommand,
}; };
impl ADBServer { impl ADBServer {
@@ -36,7 +36,7 @@ impl ADBServer {
break; break;
} }
vec_devices.push(DeviceLong::try_from(device.to_vec())?); vec_devices.push(DeviceLong::try_from(device)?);
} }
Ok(vec_devices) Ok(vec_devices)
@@ -69,12 +69,12 @@ impl ADBServer {
.filter(|d| d.identifier.as_str() == name) .filter(|d| d.identifier.as_str() == name)
.collect::<Vec<DeviceShort>>() .collect::<Vec<DeviceShort>>()
.len(); .len();
if nb_devices != 1 { if nb_devices == 1 {
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
} else {
Err(RustADBError::DeviceNotFound(format!( Err(RustADBError::DeviceNotFound(format!(
"could not find device {name}" "could not find device {name}"
))) )))
} else {
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
} }
} }
@@ -97,7 +97,12 @@ impl ADBServer {
.get_raw_connection()? .get_raw_connection()?
.read_exact(&mut body)?; .read_exact(&mut body)?;
callback(DeviceShort::try_from(body)?)?; for device in body.split(|x| x.eq(&b'\n')) {
if device.is_empty() {
break;
}
callback(DeviceShort::try_from(device.to_vec())?)?;
}
} }
} }
} }

View File

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

View File

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

View File

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

View File

@@ -7,3 +7,4 @@ mod pair;
mod reconnect; mod reconnect;
mod server_status; mod server_status;
mod version; mod version;
mod wait_for_device;

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
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()
}
}

View File

@@ -1,4 +1,6 @@
mod adb_server; mod adb_server;
mod commands; mod commands;
mod models;
pub use adb_server::ADBServer; pub use adb_server::ADBServer;
pub use models::*;

View File

@@ -15,7 +15,8 @@ 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,

View File

@@ -6,7 +6,7 @@ use crate::{DeviceState, RustADBError};
use regex::bytes::Regex; use regex::bytes::Regex;
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| { static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(?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") Regex::new(r"^(?P<identifier>\S+)\s+(?P<state>\w+)\s+(usb:(?P<usb1>\S+)|(?P<usb2>\S+))?\s*(product:(?P<product>\S+)\s+model:(?P<model>\w+)\s+device:(?P<device>\S+)\s+)?transport_id:(?P<transport_id>\d+)$").expect("cannot build devices long regex")
}); });
/// Represents a new device with more informations. /// Represents a new device with more informations.
@@ -44,12 +44,12 @@ impl Display for DeviceLong {
} }
} }
impl TryFrom<Vec<u8>> for DeviceLong { impl TryFrom<&[u8]> for DeviceLong {
type Error = RustADBError; type Error = RustADBError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> { fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let groups = DEVICES_LONG_REGEX let groups = DEVICES_LONG_REGEX
.captures(&value) .captures(value)
.ok_or(RustADBError::RegexParsingError)?; .ok_or(RustADBError::RegexParsingError)?;
Ok(DeviceLong { Ok(DeviceLong {
@@ -86,15 +86,28 @@ impl TryFrom<Vec<u8>> for DeviceLong {
None => "Unk".to_string(), None => "Unk".to_string(),
Some(device) => String::from_utf8(device.as_bytes().to_vec())?, Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
}, },
transport_id: u32::from_str_radix( transport_id: (str::from_utf8(
str::from_utf8(
groups groups
.name("transport_id") .name("transport_id")
.ok_or(RustADBError::RegexParsingError)? .ok_or(RustADBError::RegexParsingError)?
.as_bytes(), .as_bytes(),
)?, )?)
16, .parse::<u32>()?,
)?,
}) })
} }
} }
#[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())
.unwrap_or_else(|_| panic!("cannot parse input: '{input}'"));
}
}

View File

@@ -0,0 +1,15 @@
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};

View File

@@ -48,11 +48,11 @@ impl Display for UsbBackend {
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default)]
pub enum MDNSBackend { pub enum MDNSBackend {
#[default] #[default]
/// Unknown /// `Unknown`
Unknown = 0, Unknown = 0,
/// Bonjour /// `Bonjour`
Bonjour = 1, Bonjour = 1,
/// OpenScreen /// `OpenScreen`
OpenScreen = 2, OpenScreen = 2,
} }
@@ -91,14 +91,23 @@ impl Display for MDNSBackend {
/// Structure representing current server status /// Structure representing current server status
#[derive(Debug, Clone, Default, PartialEq)] #[derive(Debug, Clone, Default, PartialEq)]
pub struct ServerStatus { pub struct ServerStatus {
/// Currently active USB backend
pub usb_backend: UsbBackend, pub usb_backend: UsbBackend,
/// Is USB backend forced ?
pub usb_backend_forced: bool, pub usb_backend_forced: bool,
/// Currently active MDNS backend
pub mdns_backend: MDNSBackend, pub mdns_backend: MDNSBackend,
/// Is MDNS backend forced ?
pub mdns_backend_forced: bool, pub mdns_backend_forced: bool,
/// Server version
pub version: String, pub version: String,
/// Server build information
pub build: String, pub build: String,
/// Server executable absolute path
pub executable_absolute_path: String, pub executable_absolute_path: String,
/// Server logs absolute path
pub log_absolute_path: String, pub log_absolute_path: String,
/// OS server is running on
pub os: String, pub os: String,
} }

View File

@@ -0,0 +1,62 @@
use std::{fmt::Display, str::FromStr};
use crate::RustADBError;
#[derive(Clone, Debug, Default)]
/// List of available transports to wait for.
pub enum WaitForDeviceTransport {
/// USB transport
Usb,
/// Local transport
Local,
/// Any transport (default value)
#[default]
Any,
}
impl Display for WaitForDeviceTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WaitForDeviceTransport::Usb => write!(f, "usb"),
WaitForDeviceTransport::Local => write!(f, "local"),
WaitForDeviceTransport::Any => write!(f, "any"),
}
}
}
impl FromStr for WaitForDeviceTransport {
type Err = RustADBError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"usb" => Ok(Self::Usb),
"local" => Ok(Self::Local),
"any" => Ok(Self::Any),
t => Err(RustADBError::UnknownTransport(t.to_string())),
}
}
}
#[derive(Debug)]
/// List of available states to wait for.
pub enum WaitForDeviceState {
/// Device in "device" state
Device,
/// Device in "recovery" state
Recovery,
/// Device in "sideload" state
Sideload,
/// Device in "bootloader" state
Bootloader,
}
impl Display for WaitForDeviceState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WaitForDeviceState::Device => write!(f, "device"),
WaitForDeviceState::Recovery => write!(f, "recovery"),
WaitForDeviceState::Sideload => write!(f, "sideload"),
WaitForDeviceState::Bootloader => write!(f, "bootloader"),
}
}
}

View File

@@ -1,43 +1,56 @@
use crate::{ADBTransport, Result, TCPServerTransport}; use crate::{ADBTransport, Result, TCPServerTransport, models::AdbServerCommand};
use std::net::SocketAddrV4; use std::net::SocketAddrV4;
/// Represents a device connected to the ADB server. /// Represents a device connected to the ADB server.
#[derive(Debug)] #[derive(Debug)]
pub struct ADBServerDevice { pub struct ADBServerDevice {
/// Unique device identifier. /// Unique device identifier.
pub identifier: String, pub identifier: Option<String>,
/// Internal [TCPServerTransport] /// Internal [`TCPServerTransport`]
transport: TCPServerTransport, pub(crate) transport: TCPServerTransport,
} }
impl ADBServerDevice { impl ADBServerDevice {
/// Instantiates a new [ADBServerDevice] /// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
pub fn new(identifier: String, socket_addr: Option<SocketAddrV4>) -> Self { #[must_use]
let transport = if let Some(addr) = socket_addr { pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
TCPServerTransport::new(addr) let transport = TCPServerTransport::new_or_default(server_addr);
} else {
TCPServerTransport::default()
};
Self { Self {
identifier, identifier: Some(identifier),
transport, transport,
} }
} }
pub(crate) fn get_transport(&self) -> &TCPServerTransport { /// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
&self.transport #[must_use]
} pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr);
pub(crate) fn get_transport_mut(&mut self) -> &mut TCPServerTransport { Self {
&mut self.transport identifier: None,
transport,
}
} }
/// Connect to underlying transport /// Connect to underlying transport
pub(crate) fn connect(&mut self) -> Result<&mut TCPServerTransport> { pub(crate) fn connect(&mut self) -> Result<&mut TCPServerTransport> {
self.transport.connect()?; self.transport.connect()?;
Ok(self.get_transport_mut()) Ok(&mut self.transport)
}
/// Set device connection to use serial transport
pub(crate) fn set_serial_transport(&mut self) -> Result<()> {
let identifier = self.identifier.clone();
let transport = self.connect()?;
if let Some(serial) = identifier {
transport.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
} else {
transport.send_adb_request(AdbServerCommand::TransportAny)?;
}
Ok(())
} }
} }

View File

@@ -1,22 +1,18 @@
use std::{ use std::{
io::{Read, Write}, io::{ErrorKind, Read, Write},
path::Path, path::Path,
}; };
use crate::{ use crate::{
ADBDeviceExt, Result, RustADBError,
constants::BUFFER_SIZE, constants::BUFFER_SIZE,
models::{AdbServerCommand, AdbStatResponse, HostFeatures}, models::{AdbServerCommand, AdbStatResponse, HostFeatures},
ADBDeviceExt, Result, RustADBError,
}; };
use super::ADBServerDevice; use super::ADBServerDevice;
impl ADBDeviceExt for ADBServerDevice { impl ADBDeviceExt for ADBServerDevice {
fn shell_command<S: ToString, W: Write>( fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
&mut self,
command: impl IntoIterator<Item = S>,
mut output: W,
) -> Result<()> {
let supported_features = self.host_features()?; let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2) if !supported_features.contains(&HostFeatures::ShellV2)
&& !supported_features.contains(&HostFeatures::Cmd) && !supported_features.contains(&HostFeatures::Cmd)
@@ -24,32 +20,35 @@ impl ADBDeviceExt for ADBServerDevice {
return Err(RustADBError::ADBShellNotSupported); return Err(RustADBError::ADBShellNotSupported);
} }
let serial = self.identifier.clone(); self.set_serial_transport()?;
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; // Prepare shell command arguments
let mut args = Vec::new();
let command_string = command.join(" ");
// Add v2 mode if supported
if supported_features.contains(&HostFeatures::ShellV2) {
log::debug!("using shell_v2 feature");
args.push("v2".to_string());
}
// Include terminal information if available
if let Ok(term) = std::env::var("TERM") {
args.push(format!("TERM={term}"));
}
// Send the request
self.transport
.send_adb_request(AdbServerCommand::ShellCommand(command_string, args))?;
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
loop { loop {
let mut buffer = [0; BUFFER_SIZE]; match self.transport.get_raw_connection()?.read(&mut buffer) {
match self
.get_transport_mut()
.get_raw_connection()?
.read(&mut buffer)
{
Ok(size) => { Ok(size) => {
if size == 0 { if size == 0 {
return Ok(()); return Ok(());
} else {
output.write_all(&buffer[..size])?;
} }
output.write_all(&buffer[..size])?;
} }
Err(e) => { Err(e) => {
return Err(RustADBError::IOError(e)); return Err(RustADBError::IOError(e));
@@ -62,10 +61,10 @@ impl ADBDeviceExt for ADBServerDevice {
self.stat(remote_path) self.stat(remote_path)
} }
fn shell<R: Read, W: Write + Send + 'static>( fn shell(
&mut self, &mut self,
mut reader: R, mut reader: &mut dyn Read,
mut writer: W, mut writer: Box<dyn Write + Send>,
) -> Result<()> { ) -> Result<()> {
let supported_features = self.host_features()?; let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2) if !supported_features.contains(&HostFeatures::ShellV2)
@@ -74,20 +73,18 @@ impl ADBDeviceExt for ADBServerDevice {
return Err(RustADBError::ADBShellNotSupported); return Err(RustADBError::ADBShellNotSupported);
} }
let serial = self.identifier.clone(); self.set_serial_transport()?;
self.connect()? self.transport.send_adb_request(AdbServerCommand::Shell)?;
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Shell)?;
let mut read_stream = self.get_transport_mut().get_raw_connection()?.try_clone()?; let mut read_stream = self.transport.get_raw_connection()?.try_clone()?;
let mut write_stream = read_stream.try_clone()?; let mut write_stream = read_stream.try_clone()?;
// Reading thread, reads response from adb-server // Reading thread, reads response from adb-server
std::thread::spawn(move || -> Result<()> { std::thread::spawn(move || -> Result<()> {
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
loop { loop {
let mut buffer = [0; BUFFER_SIZE];
match read_stream.read(&mut buffer) { match read_stream.read(&mut buffer) {
Ok(0) => { Ok(0) => {
read_stream.shutdown(std::net::Shutdown::Both)?; read_stream.shutdown(std::net::Shutdown::Both)?;
@@ -107,7 +104,7 @@ impl ADBDeviceExt for ADBServerDevice {
// Read from given reader (that could be stdin e.g), and write content to server socket // Read from given reader (that could be stdin e.g), and write content to server socket
if let Err(e) = std::io::copy(&mut reader, &mut write_stream) { if let Err(e) = std::io::copy(&mut reader, &mut write_stream) {
match e.kind() { match e.kind() {
std::io::ErrorKind::BrokenPipe => return Ok(()), ErrorKind::BrokenPipe => return Ok(()),
_ => return Err(RustADBError::IOError(e)), _ => return Err(RustADBError::IOError(e)),
} }
} }
@@ -115,7 +112,7 @@ impl ADBDeviceExt for ADBServerDevice {
Ok(()) Ok(())
} }
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, mut output: W) -> Result<()> { fn pull(&mut self, source: &dyn AsRef<str>, mut output: &mut dyn Write) -> Result<()> {
self.pull(source, &mut output) self.pull(source, &mut output)
} }
@@ -123,11 +120,23 @@ impl ADBDeviceExt for ADBServerDevice {
self.reboot(reboot_type) self.reboot(reboot_type)
} }
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> { fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
self.push(stream, path) self.push(stream, path)
} }
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> { fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
self.install(apk_path) 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)
}
} }

View File

@@ -1,24 +1,20 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result}; use crate::{ADBServerDevice, Result, models::AdbServerCommand};
impl ADBServerDevice { impl ADBServerDevice {
/// Forward socket connection /// Forward socket connection
pub fn forward(&mut self, remote: String, local: String) -> Result<()> { pub fn forward(&mut self, remote: String, local: String) -> Result<()> {
let serial = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.get_transport_mut() self.transport
.proxy_connection(AdbServerCommand::Forward(remote, local), false) .proxy_connection(AdbServerCommand::Forward(remote, local), false)
.map(|_| ()) .map(|_| ())
} }
/// Remove all previously applied forward rules /// Remove all previously applied forward rules
pub fn forward_remove_all(&mut self) -> Result<()> { pub fn forward_remove_all(&mut self) -> Result<()> {
let serial = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.get_transport_mut() self.transport
.proxy_connection(AdbServerCommand::ForwardRemoveAll, false) .proxy_connection(AdbServerCommand::ForwardRemoveAll, false)
.map(|_| ()) .map(|_| ())
} }

View File

@@ -1,134 +1,23 @@
use std::{ use std::io::Read;
io::{Read, Seek, Write},
iter::Map,
path::Path,
slice::ChunksExact,
};
use byteorder::{LittleEndian, ReadBytesExt}; use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, ImageFormat, Rgba}; use image::{ImageBuffer, Rgba};
use crate::{models::AdbServerCommand, utils, ADBServerDevice, Result, RustADBError}; use crate::{
ADBServerDevice, Result, RustADBError,
type U32ChunkIter<'a> = Map<ChunksExact<'a, u8>, fn(&[u8]) -> Result<u32>>; models::{AdbServerCommand, FrameBufferInfoV1, FrameBufferInfoV2},
};
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 { impl ADBServerDevice {
/// Dump framebuffer of this device into given ['path']
/// 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())?)
}
/// Dump framebuffer of this device and return corresponding bytes.
///
/// Output data format is currently only `PNG`.
pub fn framebuffer_bytes<W: Write + Seek>(&mut self, mut writer: W) -> Result<()> {
let img = self.framebuffer_inner()?;
Ok(img.write_to(&mut writer, ImageFormat::Png)?)
}
/// Inner method requesting framebuffer from Android device /// Inner method requesting framebuffer from Android device
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> { pub(crate) fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
let serial: String = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut() self.transport
.send_adb_request(AdbServerCommand::FrameBuffer)?; .send_adb_request(AdbServerCommand::FrameBuffer)?;
let version = self let version = self
.get_transport_mut() .transport
.get_raw_connection()? .get_raw_connection()?
.read_u32::<LittleEndian>()?; .read_u32::<LittleEndian>()?;
@@ -137,51 +26,49 @@ impl ADBServerDevice {
1 => { 1 => {
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV1>()]; let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV1>()];
self.get_transport_mut() self.transport.get_raw_connection()?.read_exact(&mut buf)?;
.get_raw_connection()?
.read_exact(&mut buf)?;
let h: FrameBufferInfoV1 = buf.try_into()?; let framebuffer_info: FrameBufferInfoV1 = buf.try_into()?;
let mut data = vec![ let mut data = vec![
0_u8; 0_u8;
h.size framebuffer_info
.size
.try_into() .try_into()
.map_err(|_| RustADBError::ConversionError)? .map_err(|_| RustADBError::ConversionError)?
]; ];
self.get_transport_mut() self.transport.get_raw_connection()?.read_exact(&mut data)?;
.get_raw_connection()?
.read_exact(&mut data)?;
Ok( Ok(ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(h.width, h.height, data) framebuffer_info.width,
.ok_or_else(|| RustADBError::FramebufferConversionError)?, framebuffer_info.height,
data,
) )
.ok_or_else(|| RustADBError::FramebufferConversionError)?)
} }
// RGBX_8888 // RGBX_8888
2 => { 2 => {
let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV2>()]; let mut buf = [0u8; std::mem::size_of::<FrameBufferInfoV2>()];
self.get_transport_mut() self.transport.get_raw_connection()?.read_exact(&mut buf)?;
.get_raw_connection()?
.read_exact(&mut buf)?;
let h: FrameBufferInfoV2 = buf.try_into()?; let framebuffer_info: FrameBufferInfoV2 = buf.try_into()?;
let mut data = vec![ let mut data = vec![
0_u8; 0_u8;
h.size framebuffer_info
.size
.try_into() .try_into()
.map_err(|_| RustADBError::ConversionError)? .map_err(|_| RustADBError::ConversionError)?
]; ];
self.get_transport_mut() self.transport.get_raw_connection()?.read_exact(&mut data)?;
.get_raw_connection()?
.read_exact(&mut data)?;
Ok( Ok(ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(
ImageBuffer::<Rgba<u8>, Vec<u8>>::from_vec(h.width, h.height, data) framebuffer_info.width,
.ok_or_else(|| RustADBError::FramebufferConversionError)?, framebuffer_info.height,
data,
) )
.ok_or_else(|| RustADBError::FramebufferConversionError)?)
} }
v => Err(RustADBError::UnimplementedFramebufferImageVersion(v)), v => Err(RustADBError::UnimplementedFramebufferImageVersion(v)),
} }

View File

@@ -1,17 +1,15 @@
use crate::{ use crate::{
models::{AdbServerCommand, HostFeatures},
ADBServerDevice, Result, ADBServerDevice, Result,
models::{AdbServerCommand, HostFeatures},
}; };
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>> {
let serial = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
let features = self let features = self
.get_transport_mut() .transport
.proxy_connection(AdbServerCommand::HostFeatures, true)?; .proxy_connection(AdbServerCommand::HostFeatures, true)?;
Ok(features Ok(features

View File

@@ -1,7 +1,7 @@
use std::{fs::File, io::Read, path::Path}; use std::{fs::File, io::Read, path::Path};
use crate::{ use crate::{
models::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk, Result, Result, models::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk,
}; };
impl ADBServerDevice { impl ADBServerDevice {
@@ -13,19 +13,17 @@ impl ADBServerDevice {
let file_size = apk_file.metadata()?.len(); let file_size = apk_file.metadata()?.len();
let serial: String = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut() self.transport
.send_adb_request(AdbServerCommand::Install(file_size))?; .send_adb_request(AdbServerCommand::Install(file_size))?;
let mut raw_connection = self.get_transport_mut().get_raw_connection()?; let mut raw_connection = self.transport.get_raw_connection()?;
std::io::copy(&mut apk_file, &mut raw_connection)?; std::io::copy(&mut apk_file, &mut raw_connection)?;
let mut data = [0; 1024]; let mut data = [0; 1024];
let read_amount = self.get_transport().get_raw_connection()?.read(&mut data)?; let read_amount = self.transport.get_raw_connection()?.read(&mut data)?;
match &data[0..read_amount] { match &data[0..read_amount] {
b"Success\n" => { b"Success\n" => {

View File

@@ -1,8 +1,8 @@
use crate::{ use crate::{
models::{AdbServerCommand, SyncCommand}, ADBServerDevice, Result, RustADBError,
ADBServerDevice, Result, models::{ADBListItem, ADBListItemType, AdbServerCommand, SyncCommand},
}; };
use byteorder::{ByteOrder, LittleEndian}; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
str, str,
@@ -10,67 +10,75 @@ use std::{
impl ADBServerDevice { impl ADBServerDevice {
/// Lists files in path on the device. /// Lists files in path on the device.
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<()> { /// note: path uses internal file paths, so Documents is at /storage/emulated/0/Documents
let serial = self.identifier.clone(); pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
self.connect()? self.set_serial_transport()?;
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
// Set device in SYNC mode // Set device in SYNC mode
self.get_transport_mut() self.transport.send_adb_request(AdbServerCommand::Sync)?;
.send_adb_request(AdbServerCommand::Sync)?;
// Send a list command // Send a list command
self.get_transport_mut() self.transport.send_sync_request(&SyncCommand::List)?;
.send_sync_request(SyncCommand::List)?;
self.handle_list_command(path) self.handle_list_command(path)
} }
// This command does not seem to work correctly. The devices I test it on just resturn fn handle_list_command<A: AsRef<str>>(&mut self, path: A) -> Result<Vec<ADBListItem>> {
// 'DONE' directly without listing anything. // TODO: use LIS2 to support files over 2.14 GB in size.
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> { // SEE: https://github.com/cstyan/adbDocumentation?tab=readme-ov-file#adb-list
let mut len_buf = [0_u8; 4]; let mut len_buf = [0_u8; 4];
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32); LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
// 4 bytes of command name is already sent by send_sync_request // 4 bytes of command name is already sent by send_sync_request
self.get_transport_mut() self.transport.get_raw_connection()?.write_all(&len_buf)?;
.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 // List send the string of the directory to list, and then the server send a list of files
self.get_transport_mut() self.transport
.get_raw_connection()? .get_raw_connection()?
.write_all(path.as_ref().to_string().as_bytes())?; .write_all(path.as_ref().to_string().as_bytes())?;
let mut list_items = Vec::new();
// Reads returned status code from ADB server // Reads returned status code from ADB server
let mut response = [0_u8; 4]; let mut response = [0_u8; 4];
loop { loop {
self.get_transport_mut() self.transport
.get_raw_connection()? .get_raw_connection()?
.read_exact(&mut response)?; .read_exact(&mut response)?;
match str::from_utf8(response.as_ref())? { match str::from_utf8(response.as_ref())? {
"DENT" => { "DENT" => {
// TODO: Move this to a struct that extract this data, but as the device let mut connection = self.transport.get_raw_connection()?;
// 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()?; let mode = connection.read_u32::<LittleEndian>()?;
connection.read_exact(&mut file_mod)?; let size = connection.read_u32::<LittleEndian>()?;
connection.read_exact(&mut file_size)?; let time = connection.read_u32::<LittleEndian>()?;
connection.read_exact(&mut mod_time)?; let name_len = connection.read_u32::<LittleEndian>()?;
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]; let mut name_buf = vec![0_u8; name_len as usize];
connection.read_exact(&mut name_buf)?; connection.read_exact(&mut name_buf)?;
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" => { "DONE" => {
return Ok(()); return Ok(list_items);
} }
x => log::error!("Got an unknown response {}", x), x => log::error!("Got an unknown response {x}"),
} }
} }
} }

View File

@@ -23,21 +23,26 @@ impl<W: Write> LogFilter<W> {
impl<W: Write> Write for LogFilter<W> { impl<W: Write> Write for LogFilter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Add newly received bytes to the internal buffer
self.buffer.extend_from_slice(buf); self.buffer.extend_from_slice(buf);
let buf_clone = self.buffer.clone(); let mut processed = 0;
let mut lines = buf_clone.split_inclusive(|&byte| byte == b'\n').peekable(); while let Some(pos) = self.buffer[processed..].iter().position(|&b| b == b'\n') {
// Found a newline, need to process it
let end = processed + pos + 1; // +1 to include the '\n'
let line = &self.buffer[processed..end];
while let Some(line) = lines.next() {
if lines.peek().is_some() {
if self.should_write(line) { if self.should_write(line) {
self.writer.write_all(line)?; self.writer.write_all(line)?;
} }
} else {
// This is the last (unfinished) element, we keep it for next round processed = end;
self.buffer = line.to_vec();
break;
} }
// Keep only remaining bytes after the last complete line
if processed > 0 {
self.buffer.copy_within(processed.., 0);
self.buffer.truncate(self.buffer.len() - processed);
} }
Ok(buf.len()) Ok(buf.len())
@@ -51,6 +56,6 @@ impl<W: Write> Write for LogFilter<W> {
impl ADBServerDevice { impl ADBServerDevice {
/// Get logs from device /// Get logs from device
pub fn get_logs<W: Write>(&mut self, output: W) -> Result<()> { pub fn get_logs<W: Write>(&mut self, output: W) -> Result<()> {
self.shell_command(["exec logcat"], LogFilter::new(output)) self.shell_command(&["exec logcat"], &mut LogFilter::new(output))
} }
} }

View File

@@ -12,4 +12,5 @@ mod send;
mod stat; mod stat;
mod tcpip; mod tcpip;
mod transport; mod transport;
mod uninstall;
mod usb; mod usb;

View File

@@ -1,16 +1,14 @@
use crate::{ use crate::{
models::{AdbServerCommand, RebootType},
ADBServerDevice, Result, ADBServerDevice, Result,
models::{AdbServerCommand, RebootType},
}; };
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<()> {
let serial = self.identifier.clone(); self.set_serial_transport()?;
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut() self.transport
.proxy_connection(AdbServerCommand::Reboot(reboot_type), false) .proxy_connection(AdbServerCommand::Reboot(reboot_type), false)
.map(|_| ()) .map(|_| ())
} }

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