Compare commits
6 Commits
usb-backen
...
v3.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c469924220 | ||
|
|
84f17a34c5 | ||
|
|
cfcca964a4 | ||
|
|
4fa47e34d3 | ||
|
|
87c880e0cc | ||
|
|
5047114d87 |
8
.github/workflows/rust-build.yml
vendored
8
.github/workflows/rust-build.yml
vendored
@@ -19,11 +19,5 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.10"
|
|
||||||
|
|
||||||
- name: Build project
|
- name: Build project
|
||||||
run: cargo build --release --features rusb,mdns
|
run: cargo build --release --all-features
|
||||||
|
|||||||
6
.github/workflows/rust-quality.yml
vendored
6
.github/workflows/rust-quality.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- run: rustup component add clippy
|
- run: rustup component add clippy
|
||||||
- name: Run clippy
|
- name: Run clippy
|
||||||
run: cargo clippy --features rusb,mdns
|
run: cargo clippy --all-features
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
name: "fmt"
|
name: "fmt"
|
||||||
@@ -33,7 +33,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Run doc
|
- name: Run doc
|
||||||
run: cargo doc --features rusb,mdns --no-deps
|
run: cargo doc --all-features --no-deps
|
||||||
env:
|
env:
|
||||||
RUSTDOCFLAGS: "-D warnings"
|
RUSTDOCFLAGS: "-D warnings"
|
||||||
|
|
||||||
@@ -43,4 +43,4 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test --verbose --features rusb,mdns
|
run: cargo test --verbose --all-features
|
||||||
|
|||||||
11
.github/workflows/rust-release.yml
vendored
11
.github/workflows/rust-release.yml
vendored
@@ -36,7 +36,7 @@ jobs:
|
|||||||
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
|
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
|
||||||
|
|
||||||
- name: Build release
|
- name: Build release
|
||||||
run: cargo build -p adb_cli --release
|
run: cargo build --all-features --release
|
||||||
|
|
||||||
- name: Rename binary
|
- name: Rename binary
|
||||||
run: mv target/release/adb_cli target/release/adb_cli-linux
|
run: mv target/release/adb_cli target/release/adb_cli-linux
|
||||||
@@ -69,7 +69,7 @@ jobs:
|
|||||||
override: true
|
override: true
|
||||||
|
|
||||||
- name: Build release
|
- name: Build release
|
||||||
run: cargo build -p adb_cli --release
|
run: cargo build --all-features --release
|
||||||
|
|
||||||
- name: Rename binary
|
- name: Rename binary
|
||||||
run: mv target/release/adb_cli target/release/adb_cli-macos
|
run: mv target/release/adb_cli target/release/adb_cli-macos
|
||||||
@@ -92,13 +92,8 @@ jobs:
|
|||||||
toolchain: stable
|
toolchain: stable
|
||||||
override: true
|
override: true
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.10"
|
|
||||||
|
|
||||||
- name: Build release
|
- name: Build release
|
||||||
run: cargo build -p adb_cli --release
|
run: cargo build --all-features --release
|
||||||
|
|
||||||
- name: Rename binary
|
- name: Rename binary
|
||||||
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe
|
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ homepage = "https://github.com/cocool97/adb_client"
|
|||||||
keywords = ["adb", "android", "tcp", "usb"]
|
keywords = ["adb", "android", "tcp", "usb"]
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
repository = "https://github.com/cocool97/adb_client"
|
repository = "https://github.com/cocool97/adb_client"
|
||||||
version = "2.1.18"
|
version = "2.1.16"
|
||||||
rust-version = "1.85.1"
|
rust-version = "1.85.1"
|
||||||
|
|
||||||
# To build locally when working on a new release
|
# To build locally when working on a new release
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ rust-version.workspace = true
|
|||||||
version.workspace = true
|
version.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
adb_client = { version = "^2.1.17", features = ["mdns", "rusb"] }
|
adb_client = { version = "^2.0.0", features = ["mdns", "usb"] }
|
||||||
anyhow = { version = "1.0.100" }
|
anyhow = { version = "1.0.94" }
|
||||||
clap = { version = "4.5.51", features = ["derive"] }
|
clap = { version = "4.5.23", features = ["derive"] }
|
||||||
env_logger = { version = "0.11.8" }
|
env_logger = { version = "0.11.5" }
|
||||||
log = { version = "0.4.28" }
|
log = { version = "0.4.26" }
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
termios = { version = "0.3.3" }
|
termios = { version = "0.3.3" }
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ pub struct ADBTermios {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ADBTermios {
|
impl ADBTermios {
|
||||||
pub fn new(fd: &impl AsRawFd) -> Result<Self> {
|
pub fn new(fd: impl AsRawFd) -> Result<Self> {
|
||||||
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
|
let mut new_termios = Termios::from_fd(fd.as_raw_fd())?;
|
||||||
let old_termios = new_termios; // Saves previous state
|
let old_termios = new_termios; // Saves previous state
|
||||||
new_termios.c_lflag = 0;
|
new_termios.c_lflag = 0;
|
||||||
@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
|
|||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Custom drop implementation, restores previous termios structure.
|
// Custom drop implementation, restores previous termios structure.
|
||||||
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
|
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
|
||||||
log::error!("Error while dropping ADBTermios: {e}");
|
log::error!("Error while dropping ADBTermios: {e}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,15 +56,12 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
|
|||||||
let server_status = adb_server.server_status()?;
|
let server_status = adb_server.server_status()?;
|
||||||
match server_status.mdns_backend {
|
match server_status.mdns_backend {
|
||||||
MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
|
MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
|
||||||
MDNSBackend::Bonjour => {
|
MDNSBackend::Bonjour => match check {
|
||||||
if check {
|
true => log::info!("mdns daemon version [Bonjour]"),
|
||||||
log::info!("mdns daemon version [Bonjour]");
|
false => log::info!("ERROR: mdns daemon unavailable"),
|
||||||
} else {
|
},
|
||||||
log::info!("ERROR: mdns daemon unavailable");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MDNSBackend::OpenScreen => {
|
MDNSBackend::OpenScreen => {
|
||||||
log::info!("mdns daemon version [Openscreen discovery 0.0.0]");
|
log::info!("mdns daemon version [Openscreen discovery 0.0.0]")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ pub fn handle_local_commands(
|
|||||||
let features = device
|
let features = device
|
||||||
.host_features()?
|
.host_features()?
|
||||||
.iter()
|
.iter()
|
||||||
.map(ToString::to_string)
|
.map(|v| v.to_string())
|
||||||
.reduce(|a, b| format!("{a},{b}"))
|
.reduce(|a, b| format!("{a},{b}"))
|
||||||
.ok_or(anyhow!("cannot list features"))?;
|
.ok_or(anyhow!("cannot list features"))?;
|
||||||
log::info!("Available host features: {features}");
|
log::info!("Available host features: {features}");
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use adb_client::mdns::MDNSDiscoveryService;
|
|||||||
use adb_client::server::ADBServer;
|
use adb_client::server::ADBServer;
|
||||||
use adb_client::server_device::ADBServerDevice;
|
use adb_client::server_device::ADBServerDevice;
|
||||||
use adb_client::tcp::ADBTcpDevice;
|
use adb_client::tcp::ADBTcpDevice;
|
||||||
use adb_client::usb::ADBRusbDevice;
|
use adb_client::usb::ADBUSBDevice;
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||||
use adb_termios::ADBTermios;
|
use adb_termios::ADBTermios;
|
||||||
@@ -66,12 +66,12 @@ fn main() -> Result<()> {
|
|||||||
MainCommand::Usb(usb_command) => {
|
MainCommand::Usb(usb_command) => {
|
||||||
let device = match (usb_command.vendor_id, usb_command.product_id) {
|
let device = match (usb_command.vendor_id, usb_command.product_id) {
|
||||||
(Some(vid), Some(pid)) => match usb_command.path_to_private_key {
|
(Some(vid), Some(pid)) => match usb_command.path_to_private_key {
|
||||||
Some(pk) => ADBRusbDevice::new_with_custom_private_key(vid, pid, pk)?,
|
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
|
||||||
None => ADBRusbDevice::new(vid, pid)?,
|
None => ADBUSBDevice::new(vid, pid)?,
|
||||||
},
|
},
|
||||||
(None, None) => match usb_command.path_to_private_key {
|
(None, None) => match usb_command.path_to_private_key {
|
||||||
Some(pk) => ADBRusbDevice::autodetect_with_custom_private_key(pk)?,
|
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
|
||||||
None => ADBRusbDevice::autodetect()?,
|
None => ADBUSBDevice::autodetect()?,
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
anyhow::bail!(
|
anyhow::bail!(
|
||||||
@@ -82,10 +82,7 @@ fn main() -> Result<()> {
|
|||||||
(device.boxed(), usb_command.commands)
|
(device.boxed(), usb_command.commands)
|
||||||
}
|
}
|
||||||
MainCommand::Tcp(tcp_command) => {
|
MainCommand::Tcp(tcp_command) => {
|
||||||
let device = match tcp_command.path_to_private_key {
|
let device = ADBTcpDevice::new(tcp_command.address)?;
|
||||||
Some(pk) => ADBTcpDevice::new_with_custom_private_key(tcp_command.address, pk)?,
|
|
||||||
None => ADBTcpDevice::new(tcp_command.address)?,
|
|
||||||
};
|
|
||||||
(device.boxed(), tcp_command.commands)
|
(device.boxed(), tcp_command.commands)
|
||||||
}
|
}
|
||||||
MainCommand::Mdns => {
|
MainCommand::Mdns => {
|
||||||
@@ -100,7 +97,7 @@ fn main() -> Result<()> {
|
|||||||
"Found device {} with addresses {:?}",
|
"Found device {} with addresses {:?}",
|
||||||
device.fullname,
|
device.fullname,
|
||||||
device.addresses
|
device.addresses
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(service.shutdown()?);
|
return Ok(service.shutdown()?);
|
||||||
@@ -114,7 +111,7 @@ fn main() -> Result<()> {
|
|||||||
// Using a scope here would call drop() too early..
|
// Using a scope here would call drop() too early..
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||||
{
|
{
|
||||||
let mut adb_termios = ADBTermios::new(&std::io::stdin())?;
|
let mut adb_termios = ADBTermios::new(std::io::stdin())?;
|
||||||
adb_termios.set_adb_termios()?;
|
adb_termios.set_adb_termios()?;
|
||||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||||
}
|
}
|
||||||
@@ -124,7 +121,7 @@ fn main() -> Result<()> {
|
|||||||
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
device.shell(&mut std::io::stdin(), Box::new(std::io::stdout()))?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let commands: Vec<&str> = commands.iter().map(String::as_str).collect();
|
let commands: Vec<&str> = commands.iter().map(|v| v.as_str()).collect();
|
||||||
device.shell_command(&commands, &mut std::io::stdout())?;
|
device.shell_command(&commands, &mut std::io::stdout())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,7 +139,7 @@ fn main() -> Result<()> {
|
|||||||
}
|
}
|
||||||
DeviceCommands::Reboot { reboot_type } => {
|
DeviceCommands::Reboot { reboot_type } => {
|
||||||
log::info!("Reboots device in mode {reboot_type:?}");
|
log::info!("Reboots device in mode {reboot_type:?}");
|
||||||
device.reboot(reboot_type.into())?;
|
device.reboot(reboot_type.into())?
|
||||||
}
|
}
|
||||||
DeviceCommands::Push { filename, path } => {
|
DeviceCommands::Push { filename, path } => {
|
||||||
let mut input = File::open(Path::new(&filename))?;
|
let mut input = File::open(Path::new(&filename))?;
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ pub enum DeviceCommands {
|
|||||||
/// The package whose activity is to be invoked
|
/// The package whose activity is to be invoked
|
||||||
#[clap(short = 'p', long = "package")]
|
#[clap(short = 'p', long = "package")]
|
||||||
package: String,
|
package: String,
|
||||||
/// The activity to be invoked itself, Usually it is `MainActivity`
|
/// The activity to be invoked itself, Usually it is MainActivity
|
||||||
#[clap(short = 'a', long = "activity")]
|
#[clap(short = 'a', long = "activity")]
|
||||||
activity: String,
|
activity: String,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use super::DeviceCommands;
|
use super::DeviceCommands;
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
pub struct TcpCommand {
|
pub struct TcpCommand {
|
||||||
pub address: SocketAddr,
|
pub address: SocketAddr,
|
||||||
/// Path to a custom private key to use for authentication
|
|
||||||
#[clap(short = 'k', long = "private-key")]
|
|
||||||
pub path_to_private_key: Option<PathBuf>,
|
|
||||||
#[clap(subcommand)]
|
#[clap(subcommand)]
|
||||||
pub commands: DeviceCommands,
|
pub commands: DeviceCommands,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,10 @@
|
|||||||
pub unsafe fn setup_logger(debug: bool) {
|
pub unsafe fn setup_logger(debug: bool) {
|
||||||
// RUST_LOG variable has more priority then "--debug" flag
|
// RUST_LOG variable has more priority then "--debug" flag
|
||||||
if std::env::var("RUST_LOG").is_err() {
|
if std::env::var("RUST_LOG").is_err() {
|
||||||
let level = if debug { "trace" } else { "info" };
|
let level = match debug {
|
||||||
|
true => "trace",
|
||||||
|
false => "info",
|
||||||
|
};
|
||||||
|
|
||||||
unsafe { std::env::set_var("RUST_LOG", level) };
|
unsafe { std::env::set_var("RUST_LOG", level) };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,35 +17,35 @@ rustdoc-args = ["--cfg", "docsrs"]
|
|||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
mdns = ["dep:mdns-sd"]
|
mdns = ["dep:mdns-sd"]
|
||||||
rusb = ["dep:rsa", "dep:rusb"]
|
usb = ["dep:rsa", "dep:rusb"]
|
||||||
webusb = ["dep:webusb-web", "dep:rsa"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
base64 = { version = "0.22.1" }
|
base64 = { version = "0.22.1" }
|
||||||
bincode = { version = "2.0.1", features = ["serde"] }
|
bincode = { version = "1.3.3" }
|
||||||
byteorder = { version = "1.5.0" }
|
byteorder = { version = "1.5.0" }
|
||||||
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
|
chrono = { version = "0.4.40", default-features = false, features = ["std"] }
|
||||||
image = { version = "0.25.8", default-features = false }
|
homedir = { version = "= 0.3.4" }
|
||||||
log = { version = "0.4.28" }
|
image = { version = "0.25.5", default-features = false }
|
||||||
|
log = { version = "0.4.26" }
|
||||||
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
|
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
|
||||||
num-traits = { version = "0.2.19" }
|
num-traits = { version = "0.2.19" }
|
||||||
quick-protobuf = { version = "0.8.1" }
|
quick-protobuf = { version = "0.8.1" }
|
||||||
rand = { version = "0.8.5" }
|
rand = { version = "0.9.0" }
|
||||||
rcgen = { version = "0.13.2", default-features = false, features = [
|
rcgen = { version = "0.13.1", default-features = false, features = [
|
||||||
|
"aws_lc_rs",
|
||||||
"pem",
|
"pem",
|
||||||
"ring"
|
|
||||||
] }
|
] }
|
||||||
regex = { version = "1.12.2", features = ["perf", "std", "unicode"] }
|
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] }
|
||||||
rustls = { version = "0.23.33", default-features = false, features = ["logging", "ring", "std", "tls12"] }
|
rustls = { version = "0.23.27" }
|
||||||
rustls-pki-types = { version = "1.12.0", features = ["web"] }
|
rustls-pki-types = { version = "1.11.0" }
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.216", features = ["derive"] }
|
||||||
serde_repr = { version = "0.1.20" }
|
serde_repr = { version = "0.1.19" }
|
||||||
sha1 = { version = "0.10.6", features = ["oid"] }
|
sha1 = { version = "0.10.6", features = ["oid"] }
|
||||||
thiserror = { version = "2.0.17" }
|
thiserror = { version = "2.0.7" }
|
||||||
|
|
||||||
#########
|
#########
|
||||||
# MDNS dependencies
|
# MDNS-only dependencies
|
||||||
mdns-sd = { version = "0.17.0", default-features = false, features = [
|
mdns-sd = { version = "0.13.9", default-features = false, features = [
|
||||||
"logging",
|
"logging",
|
||||||
], optional = true }
|
], optional = true }
|
||||||
#########
|
#########
|
||||||
@@ -54,16 +54,10 @@ mdns-sd = { version = "0.17.0", default-features = false, features = [
|
|||||||
rsa = { version = "0.9.7", optional = true }
|
rsa = { version = "0.9.7", optional = true }
|
||||||
rusb = { version = "0.9.4", features = ["vendored"], optional = true }
|
rusb = { version = "0.9.4", features = ["vendored"], optional = true }
|
||||||
#########
|
#########
|
||||||
#########
|
|
||||||
# webusb dependencies
|
|
||||||
webusb-web = { version = "0.4.1", optional = true }
|
|
||||||
getrandom = { version = "0.2.16", features = ["js"], optional = true }
|
|
||||||
ring = { version = "0.17.14", features = ["wasm32_unknown_unknown_js"], optional = true }
|
|
||||||
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
anyhow = { version = "1.0.100" }
|
anyhow = { version = "1.0.93" }
|
||||||
criterion = { version = "0.7.0" } # Used for benchmarks
|
criterion = { version = "0.6.0" } # Used for benchmarks
|
||||||
|
|
||||||
[[bench]]
|
[[bench]]
|
||||||
harness = false
|
harness = false
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ adb_client = "*"
|
|||||||
| Feature | Description | Default? |
|
| Feature | Description | Default? |
|
||||||
| :-----: | :---------------------------------------------: | :------: |
|
| :-----: | :---------------------------------------------: | :------: |
|
||||||
| `mdns` | Enables mDNS device discovery on local network. | No |
|
| `mdns` | Enables mDNS device discovery on local network. | No |
|
||||||
| `rusb` | Enables interactions with USB devices. | No |
|
| `usb` | Enables interactions with USB devices. | No |
|
||||||
|
|
||||||
To deactivate some features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
|
To deactivate some features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ use image::{ImageBuffer, ImageFormat, Rgba};
|
|||||||
use crate::models::AdbStatResponse;
|
use crate::models::AdbStatResponse;
|
||||||
use crate::{RebootType, Result};
|
use crate::{RebootType, Result};
|
||||||
|
|
||||||
/// Trait representing all features available on an ADB device, currently used by:
|
/// Trait representing all features available on both [`crate::server_device::ADBServerDevice`] and [`crate::usb::ADBUSBDevice`]
|
||||||
/// - [`crate::server_device::ADBServerDevice`]
|
|
||||||
/// - [`crate::usb::ADBRusbDevice`]
|
|
||||||
/// - [`crate::tcp::ADBTcpDevice`]
|
|
||||||
pub trait ADBDeviceExt {
|
pub trait ADBDeviceExt {
|
||||||
/// Runs command in a shell on the device, and write its output and error streams into output.
|
/// Runs command in a shell on the device, and write its output and error streams into output.
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
|
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()>;
|
||||||
|
|||||||
@@ -18,16 +18,16 @@ 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::LOCALHOST,
|
None => Ipv4Addr::new(127, 0, 0, 1),
|
||||||
};
|
};
|
||||||
|
|
||||||
let groups = EMULATOR_REGEX
|
let groups = EMULATOR_REGEX
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ impl ADBEmulatorCommand {
|
|||||||
pub(crate) fn skip_response_lines(&self) -> u8 {
|
pub(crate) fn skip_response_lines(&self) -> u8 {
|
||||||
match self {
|
match self {
|
||||||
ADBEmulatorCommand::Authenticate(_) => 1,
|
ADBEmulatorCommand::Authenticate(_) => 1,
|
||||||
ADBEmulatorCommand::Sms(_, _) | ADBEmulatorCommand::Rotate => 0,
|
ADBEmulatorCommand::Sms(_, _) => 0,
|
||||||
|
ADBEmulatorCommand::Rotate => 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ use std::{
|
|||||||
net::{SocketAddrV4, TcpStream},
|
net::{SocketAddrV4, TcpStream},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use homedir::my_home;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
|
Result, RustADBError, adb_transport::ADBTransport, emulator::models::ADBEmulatorCommand,
|
||||||
};
|
};
|
||||||
@@ -16,7 +18,7 @@ pub struct TCPEmulatorTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TCPEmulatorTransport {
|
impl TCPEmulatorTransport {
|
||||||
/// Instantiates a new instance of [`TCPEmulatorTransport`]
|
/// Instantiates a new instance of [TCPEmulatorTransport]
|
||||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||||
Self {
|
Self {
|
||||||
socket_addr,
|
socket_addr,
|
||||||
@@ -33,10 +35,11 @@ impl TCPEmulatorTransport {
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return authentication token stored in `$HOME/.emulator_console_auth_token`
|
/// Return authentication token stored in $HOME/.emulator_console_auth_token
|
||||||
pub fn get_authentication_token(&mut self) -> Result<String> {
|
pub fn get_authentication_token(&mut self) -> Result<String> {
|
||||||
let Some(home) = std::env::home_dir() else {
|
let home = match my_home()? {
|
||||||
return Err(RustADBError::NoHomeDirectory);
|
Some(home) => home,
|
||||||
|
None => return Err(RustADBError::NoHomeDirectory),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut f = File::open(home.join(".emulator_console_auth_token"))?;
|
let mut f = File::open(home.join(".emulator_console_auth_token"))?;
|
||||||
@@ -52,7 +55,7 @@ impl TCPEmulatorTransport {
|
|||||||
self.send_command(ADBEmulatorCommand::Authenticate(token))
|
self.send_command(ADBEmulatorCommand::Authenticate(token))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send an [`ADBEmulatorCommand`] to this emulator
|
/// Send an [ADBEmulatorCommand] to this emulator
|
||||||
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> {
|
pub(crate) fn send_command(&mut self, command: ADBEmulatorCommand) -> Result<()> {
|
||||||
let mut connection = self.get_raw_connection()?;
|
let mut connection = self.get_raw_connection()?;
|
||||||
|
|
||||||
@@ -78,11 +81,10 @@ impl TCPEmulatorTransport {
|
|||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
reader.read_line(&mut line)?;
|
reader.read_line(&mut line)?;
|
||||||
|
|
||||||
if line.starts_with("OK") {
|
match line.starts_with("OK") {
|
||||||
return Ok(());
|
true => Ok(()),
|
||||||
|
false => Err(RustADBError::ADBRequestFailed(line)),
|
||||||
}
|
}
|
||||||
|
|
||||||
Err(RustADBError::ADBRequestFailed(line))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,9 +42,6 @@ pub enum RustADBError {
|
|||||||
/// Indicates that an error occurred when converting a value.
|
/// 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,
|
||||||
@@ -64,14 +61,14 @@ pub enum RustADBError {
|
|||||||
#[error("Unimplemented framebuffer image version: {0}")]
|
#[error("Unimplemented framebuffer image version: {0}")]
|
||||||
UnimplementedFramebufferImageVersion(u32),
|
UnimplementedFramebufferImageVersion(u32),
|
||||||
/// An error occurred while getting user's home directory
|
/// An error occurred while getting user's home directory
|
||||||
#[error("Cannot get user home directory")]
|
#[error(transparent)]
|
||||||
HomeError,
|
HomeError(#[from] homedir::GetHomeError),
|
||||||
/// Cannot get home directory
|
/// Cannot get home directory
|
||||||
#[error("Cannot get home directory")]
|
#[error("Cannot get home directory")]
|
||||||
NoHomeDirectory,
|
NoHomeDirectory,
|
||||||
/// Generic USB error
|
/// Generic USB error
|
||||||
#[cfg(feature = "rusb")]
|
#[cfg(feature = "usb")]
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
|
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
|
||||||
#[error("USB Error: {0}")]
|
#[error("USB Error: {0}")]
|
||||||
UsbError(#[from] rusb::Error),
|
UsbError(#[from] rusb::Error),
|
||||||
/// USB device not found
|
/// USB device not found
|
||||||
@@ -90,8 +87,8 @@ pub enum RustADBError {
|
|||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Base64EncodeError(#[from] base64::EncodeSliceError),
|
Base64EncodeError(#[from] base64::EncodeSliceError),
|
||||||
/// An error occurred with RSA engine
|
/// An error occurred with RSA engine
|
||||||
#[cfg(any(feature = "rusb", feature = "webusb"))]
|
#[cfg(feature = "usb")]
|
||||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
|
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
RSAError(#[from] rsa::errors::Error),
|
RSAError(#[from] rsa::errors::Error),
|
||||||
/// Cannot convert given data from slice
|
/// Cannot convert given data from slice
|
||||||
@@ -101,8 +98,8 @@ pub enum RustADBError {
|
|||||||
#[error("wrong file extension: {0}")]
|
#[error("wrong file extension: {0}")]
|
||||||
WrongFileExtension(String),
|
WrongFileExtension(String),
|
||||||
/// An error occurred with PKCS8 data
|
/// An error occurred with PKCS8 data
|
||||||
#[cfg(any(feature = "rusb", feature = "webusb"))]
|
#[cfg(feature = "usb")]
|
||||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
|
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
|
||||||
#[error("error with pkcs8: {0}")]
|
#[error("error with pkcs8: {0}")]
|
||||||
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
|
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
|
||||||
/// Error during certificate generation
|
/// Error during certificate generation
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
use std::{collections::HashSet, net::IpAddr};
|
use std::{collections::HashSet, net::IpAddr};
|
||||||
|
|
||||||
use mdns_sd::{ResolvedService, ScopedIp};
|
|
||||||
|
|
||||||
/// Represent a device found from mdns search
|
/// Represent a device found from mdns search
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MDNSDevice {
|
pub struct MDNSDevice {
|
||||||
@@ -11,11 +9,11 @@ pub struct MDNSDevice {
|
|||||||
pub addresses: HashSet<IpAddr>,
|
pub addresses: HashSet<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Box<ResolvedService>> for MDNSDevice {
|
impl From<mdns_sd::ServiceInfo> for MDNSDevice {
|
||||||
fn from(value: Box<ResolvedService>) -> Self {
|
fn from(value: mdns_sd::ServiceInfo) -> Self {
|
||||||
Self {
|
Self {
|
||||||
fullname: value.fullname,
|
fullname: value.get_fullname().to_string(),
|
||||||
addresses: value.addresses.iter().map(ScopedIp::to_ip_addr).collect(),
|
addresses: value.get_addresses().to_owned(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,15 +42,13 @@ 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) => {
|
||||||
return sender
|
return sender
|
||||||
.send(MDNSDevice::from(service_info))
|
.send(MDNSDevice::from(service_info))
|
||||||
.map_err(|_| RustADBError::SendError);
|
.map_err(|_| RustADBError::SendError);
|
||||||
}
|
}
|
||||||
e => {
|
|
||||||
log::warn!("received unknown event type {e:?}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,18 @@
|
|||||||
use crate::message_devices::adb_message_transport::ADBMessageTransport;
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
use crate::message_devices::adb_rsa_key::ADBRsaKey;
|
use rand::Rng;
|
||||||
use crate::message_devices::adb_transport_message::ADBTransportMessage;
|
|
||||||
use crate::message_devices::message_commands::{MessageCommand, MessageSubcommand};
|
|
||||||
use crate::message_devices::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE};
|
|
||||||
use crate::{AUTH_TOKEN, AdbStatResponse, Result, RustADBError};
|
|
||||||
use bincode::config::{Configuration, Fixint, LittleEndian, NoLimit};
|
|
||||||
use byteorder::ReadBytesExt;
|
|
||||||
use serde::Serialize;
|
|
||||||
use serde::de::DeserializeOwned;
|
|
||||||
use std::io::{Cursor, Read, Seek};
|
use std::io::{Cursor, Read, Seek};
|
||||||
use std::time::Duration;
|
|
||||||
|
use crate::{
|
||||||
|
AdbStatResponse, Result, RustADBError,
|
||||||
|
message_devices::{
|
||||||
|
adb_message_transport::ADBMessageTransport,
|
||||||
|
adb_transport_message::ADBTransportMessage,
|
||||||
|
message_commands::{MessageCommand, MessageSubcommand},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const BUFFER_SIZE: usize = 65535;
|
const BUFFER_SIZE: usize = 65535;
|
||||||
|
|
||||||
const BINCODE_CONFIG: Configuration<LittleEndian, Fixint, NoLimit> = bincode::config::legacy();
|
|
||||||
|
|
||||||
pub(crate) fn bincode_serialize_to_vec<E: Serialize>(val: E) -> Result<Vec<u8>> {
|
|
||||||
bincode::serde::encode_to_vec(val, BINCODE_CONFIG).map_err(|_e| RustADBError::ConversionError)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn bincode_deserialize_from_slice<D: DeserializeOwned>(data: &[u8]) -> Result<D> {
|
|
||||||
let (response, _) = bincode::serde::decode_from_slice(data, BINCODE_CONFIG)
|
|
||||||
.map_err(|_e| RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
|
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
|
||||||
/// Structure is totally agnostic over which transport is truly used.
|
/// Structure is totally agnostic over which transport is truly used.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -53,66 +40,6 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
&mut self.transport
|
&mut self.transport
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn auth_handshake(
|
|
||||||
&mut self,
|
|
||||||
message: ADBTransportMessage,
|
|
||||||
private_key: &ADBRsaKey,
|
|
||||||
) -> Result<()> {
|
|
||||||
match message.header().command() {
|
|
||||||
MessageCommand::Auth => {
|
|
||||||
log::debug!("Authentication required");
|
|
||||||
}
|
|
||||||
_ => return Ok(()),
|
|
||||||
}
|
|
||||||
|
|
||||||
// At this point, we should have received an AUTH message with arg0 == 1
|
|
||||||
let auth_message = match message.header().arg0() {
|
|
||||||
AUTH_TOKEN => message,
|
|
||||||
v => {
|
|
||||||
return Err(RustADBError::ADBRequestFailed(format!(
|
|
||||||
"Received AUTH message with type != 1 ({v})"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let sign = private_key.sign(auth_message.into_payload())?;
|
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, &sign);
|
|
||||||
|
|
||||||
self.get_transport_mut().write_message(message)?;
|
|
||||||
|
|
||||||
let received_response = self.get_transport_mut().read_message()?;
|
|
||||||
|
|
||||||
if received_response.header().command() == MessageCommand::Cnxn {
|
|
||||||
log::info!(
|
|
||||||
"Authentication OK, device info {}",
|
|
||||||
String::from_utf8(received_response.into_payload())?
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pubkey = private_key.android_pubkey_encode()?.into_bytes();
|
|
||||||
pubkey.push(b'\0');
|
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_RSAPUBLICKEY, 0, &pubkey);
|
|
||||||
|
|
||||||
self.get_transport_mut().write_message(message)?;
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.get_transport_mut()
|
|
||||||
.read_message_with_timeout(Duration::from_secs(10))
|
|
||||||
.and_then(|message| {
|
|
||||||
message.assert_command(MessageCommand::Cnxn)?;
|
|
||||||
Ok(message)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
log::info!(
|
|
||||||
"Authentication OK, device info {}",
|
|
||||||
String::from_utf8(response.into_payload())?
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Receive a message and acknowledge it by replying with an `OKAY` command
|
/// Receive a message and acknowledge it by replying with an `OKAY` command
|
||||||
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> {
|
pub(crate) fn recv_and_reply_okay(&mut self) -> Result<ADBTransportMessage> {
|
||||||
let message = self.transport.read_message()?;
|
let message = self.transport.read_message()?;
|
||||||
@@ -150,7 +77,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
match len.take() {
|
match len.take() {
|
||||||
Some(0) | None => {
|
Some(0) | None => {
|
||||||
rdr.seek_relative(4)?;
|
rdr.seek_relative(4)?;
|
||||||
len.replace(u64::from(rdr.read_u32::<byteorder::LittleEndian>()?));
|
len.replace(rdr.read_u32::<LittleEndian>()? as u64);
|
||||||
}
|
}
|
||||||
Some(length) => {
|
Some(length) => {
|
||||||
let remaining_bytes = payload.len() as u64 - rdr.position();
|
let remaining_bytes = payload.len() as u64 - rdr.position();
|
||||||
@@ -166,7 +93,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::<byteorder::LittleEndian>()?
|
.read_u32::<LittleEndian>()?
|
||||||
== MessageSubcommand::Done as u32
|
== MessageSubcommand::Done as u32
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -181,11 +108,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
remote_id: u32,
|
remote_id: u32,
|
||||||
mut reader: R,
|
mut reader: R,
|
||||||
) -> std::result::Result<(), RustADBError> {
|
) -> std::result::Result<(), RustADBError> {
|
||||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
let amount_read = reader.read(&mut buffer)?;
|
let amount_read = reader.read(&mut buffer)?;
|
||||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(amount_read)?);
|
let subcommand_data = MessageSubcommand::Data.with_arg(amount_read as u32);
|
||||||
|
|
||||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
let mut serialized_message =
|
||||||
|
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(
|
||||||
@@ -198,14 +126,16 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
self.send_and_expect_okay(message)?;
|
self.send_and_expect_okay(message)?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
|
|
||||||
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_to_vec(&subcommand_data)?;
|
let serialized_message = bincode::serialize(&subcommand_data)
|
||||||
|
.map_err(|_e| RustADBError::ConversionError)?;
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
let message = ADBTransportMessage::new(
|
||||||
MessageCommand::Write,
|
MessageCommand::Write,
|
||||||
local_id,
|
local_id,
|
||||||
@@ -227,9 +157,10 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(size) => {
|
Ok(size) => {
|
||||||
let subcommand_data = MessageSubcommand::Data.with_arg(u32::try_from(size)?);
|
let subcommand_data = MessageSubcommand::Data.with_arg(size as u32);
|
||||||
|
|
||||||
let mut serialized_message = bincode_serialize_to_vec(&subcommand_data)?;
|
let mut serialized_message = bincode::serialize(&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(
|
||||||
@@ -254,12 +185,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn stat_with_explicit_ids(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
pub(crate) fn stat_with_explicit_ids(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
|
||||||
let stat_buffer = MessageSubcommand::Stat.with_arg(u32::try_from(remote_path.len())?);
|
let stat_buffer = MessageSubcommand::Stat.with_arg(remote_path.len() as u32);
|
||||||
let message = ADBTransportMessage::new(
|
let message = ADBTransportMessage::new(
|
||||||
MessageCommand::Write,
|
MessageCommand::Write,
|
||||||
self.get_local_id()?,
|
self.get_local_id()?,
|
||||||
self.get_remote_id()?,
|
self.get_remote_id()?,
|
||||||
&bincode_serialize_to_vec(&stat_buffer)?,
|
&bincode::serialize(&stat_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||||
);
|
);
|
||||||
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(
|
||||||
@@ -271,8 +202,8 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
let response = self.transport.read_message()?;
|
let response = self.transport.read_message()?;
|
||||||
// Skip first 4 bytes as this is the literal "STAT".
|
// Skip first 4 bytes as this is the literal "STAT".
|
||||||
// Interesting part starts right after
|
// Interesting part starts right after
|
||||||
|
bincode::deserialize(&response.into_payload()[4..])
|
||||||
bincode_deserialize_from_slice(&response.into_payload()[4..])
|
.map_err(|_e| RustADBError::ConversionError)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn end_transaction(&mut self) -> Result<()> {
|
pub(crate) fn end_transaction(&mut self) -> Result<()> {
|
||||||
@@ -281,16 +212,18 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
MessageCommand::Write,
|
MessageCommand::Write,
|
||||||
self.get_local_id()?,
|
self.get_local_id()?,
|
||||||
self.get_remote_id()?,
|
self.get_remote_id()?,
|
||||||
&bincode_serialize_to_vec(&quit_buffer)?,
|
&bincode::serialize(&quit_buffer).map_err(|_e| RustADBError::ConversionError)?,
|
||||||
))?;
|
))?;
|
||||||
let _discard_close = self.transport.read_message()?;
|
let _discard_close = self.transport.read_message()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
|
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
|
||||||
|
let mut rng = rand::rng();
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
let message = ADBTransportMessage::new(
|
||||||
MessageCommand::Open,
|
MessageCommand::Open,
|
||||||
rand::random::<u32>(), // Our 'local-id'
|
rng.random(), // Our 'local-id'
|
||||||
0,
|
0,
|
||||||
data,
|
data,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::{Result, RustADBError, message_devices::message_commands::MessageCommand};
|
||||||
Result, RustADBError,
|
|
||||||
message_devices::{adb_message_device, message_commands::MessageCommand},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ADBTransportMessage {
|
pub struct ADBTransportMessage {
|
||||||
@@ -55,16 +52,16 @@ impl ADBTransportMessageHeader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
|
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
|
||||||
data.iter().map(|&x| u32::from(x)).sum()
|
data.iter().map(|&x| x as u32).sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compute_magic(command: MessageCommand) -> u32 {
|
fn compute_magic(command: MessageCommand) -> u32 {
|
||||||
let command_u32 = command as u32;
|
let command_u32 = command as u32;
|
||||||
command_u32 ^ 0xFFFF_FFFF
|
command_u32 ^ 0xFFFFFFFF
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_bytes(&self) -> Result<Vec<u8>> {
|
pub fn as_bytes(&self) -> Result<Vec<u8>> {
|
||||||
adb_message_device::bincode_serialize_to_vec(self)
|
bincode::serialize(&self).map_err(|_e| RustADBError::ConversionError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,6 +111,6 @@ impl TryFrom<[u8; 24]> for ADBTransportMessageHeader {
|
|||||||
type Error = RustADBError;
|
type Error = RustADBError;
|
||||||
|
|
||||||
fn try_from(value: [u8; 24]) -> Result<Self> {
|
fn try_from(value: [u8; 24]) -> Result<Self> {
|
||||||
adb_message_device::bincode_deserialize_from_slice(&value)
|
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
payload_cursor.read_to_end(&mut framebuffer_data)?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if u32::try_from(framebuffer_data.len())? == framebuffer_info.size {
|
if framebuffer_data.len() as u32 == framebuffer_info.size {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::io::Write;
|
|||||||
use crate::{
|
use crate::{
|
||||||
Result, RustADBError,
|
Result, RustADBError,
|
||||||
message_devices::{
|
message_devices::{
|
||||||
adb_message_device::{self, ADBMessageDevice},
|
adb_message_device::ADBMessageDevice,
|
||||||
adb_message_transport::ADBMessageTransport,
|
adb_message_transport::ADBMessageTransport,
|
||||||
adb_transport_message::ADBTransportMessage,
|
adb_transport_message::ADBTransportMessage,
|
||||||
message_commands::{MessageCommand, MessageSubcommand},
|
message_commands::{MessageCommand, MessageSubcommand},
|
||||||
@@ -31,8 +31,9 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
std::time::Duration::from_secs(4),
|
std::time::Duration::from_secs(4),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let recv_buffer = MessageSubcommand::Recv.with_arg(u32::try_from(source.len())?);
|
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32);
|
||||||
let recv_buffer = adb_message_device::bincode_serialize_to_vec(&recv_buffer)?;
|
let recv_buffer =
|
||||||
|
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
|
||||||
self.send_and_expect_okay(ADBTransportMessage::new(
|
self.send_and_expect_okay(ADBTransportMessage::new(
|
||||||
MessageCommand::Write,
|
MessageCommand::Write,
|
||||||
self.get_local_id()?,
|
self.get_local_id()?,
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Result,
|
Result, RustADBError,
|
||||||
message_devices::{
|
message_devices::{
|
||||||
adb_message_device::{self, ADBMessageDevice},
|
adb_message_device::ADBMessageDevice,
|
||||||
adb_message_transport::ADBMessageTransport,
|
adb_message_transport::ADBMessageTransport,
|
||||||
adb_transport_message::ADBTransportMessage,
|
adb_transport_message::ADBTransportMessage,
|
||||||
message_commands::{MessageCommand, MessageSubcommand},
|
message_commands::{MessageCommand, MessageSubcommand},
|
||||||
@@ -16,8 +16,9 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
|
|
||||||
let path_header = format!("{},0777", path.as_ref());
|
let path_header = format!("{},0777", path.as_ref());
|
||||||
|
|
||||||
let send_buffer = MessageSubcommand::Send.with_arg(u32::try_from(path_header.len())?);
|
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32);
|
||||||
let mut send_buffer = adb_message_device::bincode_serialize_to_vec(&send_buffer)?;
|
let mut 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(
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
|
|||||||
writer.write_all(&message.into_payload())?;
|
writer.write_all(&message.into_payload())?;
|
||||||
writer.flush()?;
|
writer.flush()?;
|
||||||
}
|
}
|
||||||
MessageCommand::Okay => {}
|
MessageCommand::Okay => continue,
|
||||||
_ => return Err(RustADBError::ADBShellNotSupported),
|
_ => return Err(RustADBError::ADBShellNotSupported),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,32 +6,32 @@ use std::fmt::Display;
|
|||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
pub enum MessageCommand {
|
pub enum MessageCommand {
|
||||||
/// Connect to a device
|
/// Connect to a device
|
||||||
Cnxn = 0x4E58_4E43,
|
Cnxn = 0x4E584E43,
|
||||||
/// Close connection to a device
|
/// Close connection to a device
|
||||||
Clse = 0x4553_4C43,
|
Clse = 0x45534C43,
|
||||||
/// Device ask for authentication
|
/// Device ask for authentication
|
||||||
Auth = 0x4854_5541,
|
Auth = 0x48545541,
|
||||||
/// Open a data connection
|
/// Open a data connection
|
||||||
Open = 0x4E45_504F,
|
Open = 0x4E45504F,
|
||||||
/// Write data to connection
|
/// Write data to connection
|
||||||
Write = 0x4554_5257,
|
Write = 0x45545257,
|
||||||
/// Server understood the message
|
/// Server understood the message
|
||||||
Okay = 0x5941_4B4F,
|
Okay = 0x59414B4F,
|
||||||
/// Start a connection using TLS
|
/// Start a connection using TLS
|
||||||
Stls = 0x534C_5453,
|
Stls = 0x534C5453,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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 = 0x5441_5453,
|
Stat = 0x54415453,
|
||||||
Send = 0x444E_4553,
|
Send = 0x444E4553,
|
||||||
Recv = 0x5643_4552,
|
Recv = 0x56434552,
|
||||||
Quit = 0x5449_5551,
|
Quit = 0x54495551,
|
||||||
Fail = 0x4C49_4146,
|
Fail = 0x4C494146,
|
||||||
Done = 0x454E_4F44,
|
Done = 0x454E4F44,
|
||||||
Data = 0x4154_4144,
|
Data = 0x41544144,
|
||||||
List = 0x5453_494C,
|
List = 0x5453494C,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
/// USB-related definitions
|
/// USB-related definitions
|
||||||
|
#[cfg(feature = "usb")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
|
||||||
pub mod usb;
|
pub mod usb;
|
||||||
|
|
||||||
/// Device reachable over TCP related definition
|
/// Device reachable over TCP related definition
|
||||||
pub mod tcp;
|
pub mod tcp;
|
||||||
|
|
||||||
pub(crate) const AUTH_TOKEN: u32 = 1;
|
|
||||||
pub(crate) const AUTH_SIGNATURE: u32 = 2;
|
|
||||||
pub(crate) const AUTH_RSAPUBLICKEY: u32 = 3;
|
|
||||||
|
|
||||||
mod adb_message_device;
|
mod adb_message_device;
|
||||||
mod adb_message_device_commands;
|
mod adb_message_device_commands;
|
||||||
mod adb_message_transport;
|
mod adb_message_transport;
|
||||||
mod adb_rsa_key;
|
|
||||||
mod adb_transport_message;
|
mod adb_transport_message;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod message_commands;
|
mod message_commands;
|
||||||
|
|||||||
@@ -1,47 +1,24 @@
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
use std::{io::Read, net::SocketAddr};
|
use std::{io::Read, net::SocketAddr};
|
||||||
|
|
||||||
use crate::message_devices::adb_message_device::ADBMessageDevice;
|
use crate::message_devices::adb_message_device::ADBMessageDevice;
|
||||||
use crate::message_devices::adb_message_transport::ADBMessageTransport;
|
use crate::message_devices::adb_message_transport::ADBMessageTransport;
|
||||||
use crate::message_devices::adb_rsa_key::ADBRsaKey;
|
|
||||||
use crate::message_devices::adb_transport_message::ADBTransportMessage;
|
use crate::message_devices::adb_transport_message::ADBTransportMessage;
|
||||||
use crate::message_devices::message_commands::MessageCommand;
|
use crate::message_devices::message_commands::MessageCommand;
|
||||||
use crate::tcp::tcp_transport::TcpTransport;
|
use crate::tcp::tcp_transport::TcpTransport;
|
||||||
use crate::usb::read_adb_private_key;
|
|
||||||
use crate::utils::get_default_adb_key_path;
|
|
||||||
use crate::{ADBDeviceExt, ADBTransport, Result};
|
use crate::{ADBDeviceExt, ADBTransport, Result};
|
||||||
|
|
||||||
/// Represent a device reached and available over USB.
|
/// Represent a device reached and available over USB.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ADBTcpDevice {
|
pub struct ADBTcpDevice {
|
||||||
private_key: ADBRsaKey,
|
|
||||||
inner: ADBMessageDevice<TcpTransport>,
|
inner: ADBMessageDevice<TcpTransport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBTcpDevice {
|
impl ADBTcpDevice {
|
||||||
/// Instantiate a new [`ADBTcpDevice`]
|
/// Instantiate a new [`ADBTcpDevice`]
|
||||||
pub fn new(address: SocketAddr) -> Result<Self> {
|
pub fn new(address: SocketAddr) -> Result<Self> {
|
||||||
Self::new_with_custom_private_key(address, get_default_adb_key_path()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Instantiate a new [`ADBTcpDevice`] using a custom private key path
|
|
||||||
pub fn new_with_custom_private_key(
|
|
||||||
address: SocketAddr,
|
|
||||||
private_key_path: PathBuf,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let private_key = if let Some(private_key) = read_adb_private_key(&private_key_path)? {
|
|
||||||
private_key
|
|
||||||
} else {
|
|
||||||
log::warn!(
|
|
||||||
"No private key found at path {}. Using a temporary random one.",
|
|
||||||
private_key_path.display()
|
|
||||||
);
|
|
||||||
ADBRsaKey::new_random()?
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut device = Self {
|
let mut device = Self {
|
||||||
private_key,
|
|
||||||
inner: ADBMessageDevice::new(TcpTransport::new(address)?),
|
inner: ADBMessageDevice::new(TcpTransport::new(address)?),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -56,8 +33,8 @@ impl ADBTcpDevice {
|
|||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
let message = ADBTransportMessage::new(
|
||||||
MessageCommand::Cnxn,
|
MessageCommand::Cnxn,
|
||||||
0x0100_0000,
|
0x01000000,
|
||||||
1_048_576,
|
1048576,
|
||||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -65,28 +42,26 @@ impl ADBTcpDevice {
|
|||||||
|
|
||||||
let message = self.get_transport_mut().read_message()?;
|
let message = self.get_transport_mut().read_message()?;
|
||||||
|
|
||||||
// Check if a client is requesting a secure connection and upgrade it if necessary
|
// Check if client is requesting a secure connection and upgrade it if necessary
|
||||||
match message.header().command() {
|
match message.header().command() {
|
||||||
MessageCommand::Stls => {
|
MessageCommand::Stls => {
|
||||||
self.get_transport_mut()
|
self.get_transport_mut()
|
||||||
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
|
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
|
||||||
self.get_transport_mut().upgrade_connection()?;
|
self.get_transport_mut().upgrade_connection()?;
|
||||||
log::debug!("Connection successfully upgraded from TCP to TLS");
|
log::debug!("Connection successfully upgraded from TCP to TLS");
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
MessageCommand::Cnxn => {
|
MessageCommand::Cnxn => {
|
||||||
log::debug!("Unencrypted connection established");
|
log::debug!("Unencrypted connection established");
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
MessageCommand::Auth => {
|
_ => {
|
||||||
log::debug!("Authentication required");
|
return Err(crate::RustADBError::WrongResponseReceived(
|
||||||
self.inner.auth_handshake(message, &self.private_key)
|
"Expected CNXN or STLS command".to_string(),
|
||||||
|
message.header().command().to_string(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
_ => Err(crate::RustADBError::WrongResponseReceived(
|
|
||||||
"Expected CNXN, STLS or AUTH command".to_string(),
|
|
||||||
message.header().command().to_string(),
|
|
||||||
)),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use std::{
|
|||||||
fs::read_to_string,
|
fs::read_to_string,
|
||||||
io::{Read, Write},
|
io::{Read, Write},
|
||||||
net::{Shutdown, SocketAddr, TcpStream},
|
net::{Shutdown, SocketAddr, TcpStream},
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, Mutex},
|
sync::{Arc, Mutex},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
@@ -79,7 +80,7 @@ impl Write for CurrentConnection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport running on TCP
|
/// Transport running on USB
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct TcpTransport {
|
pub struct TcpTransport {
|
||||||
address: SocketAddr,
|
address: SocketAddr,
|
||||||
@@ -122,15 +123,18 @@ impl TcpTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
|
pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
|
||||||
let Some(current_connection) = self.current_connection.clone() else {
|
let current_connection = match self.current_connection.clone() {
|
||||||
return Err(RustADBError::UpgradeError(
|
Some(current_connection) => current_connection,
|
||||||
"cannot upgrade a non-existing connection...".into(),
|
None => {
|
||||||
));
|
return Err(RustADBError::UpgradeError(
|
||||||
|
"cannot upgrade a non-existing connection...".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut current_conn_locked = current_connection.lock()?;
|
let mut current_conn_locked = current_connection.lock()?;
|
||||||
match &*current_conn_locked {
|
match current_conn_locked.deref() {
|
||||||
CurrentConnection::Tcp(tcp_stream) => {
|
CurrentConnection::Tcp(tcp_stream) => {
|
||||||
// TODO: Check if we cannot be more precise
|
// TODO: Check if we cannot be more precise
|
||||||
|
|
||||||
@@ -191,7 +195,7 @@ impl ADBTransport for TcpTransport {
|
|||||||
log::debug!("disconnecting...");
|
log::debug!("disconnecting...");
|
||||||
if let Some(current_connection) = &self.current_connection {
|
if let Some(current_connection) = &self.current_connection {
|
||||||
let mut lock = current_connection.lock()?;
|
let mut lock = current_connection.lock()?;
|
||||||
match &mut *lock {
|
match lock.deref_mut() {
|
||||||
CurrentConnection::Tcp(tcp_stream) => {
|
CurrentConnection::Tcp(tcp_stream) => {
|
||||||
let _ = tcp_stream.shutdown(Shutdown::Both);
|
let _ = tcp_stream.shutdown(Shutdown::Both);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,6 @@ use std::path::Path;
|
|||||||
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");
|
||||||
let mut input = File::open("/tmp/file.txt").expect("Cannot open file");
|
let mut input = File::open(Path::new("/tmp/file.txt")).expect("Cannot open file");
|
||||||
device.push(&mut input, &"/data/local/tmp");
|
device.push(&mut input, &"/data/local/tmp");
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ 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;
|
||||||
@@ -93,16 +92,15 @@ impl ADBRsaKey {
|
|||||||
.to_u32()
|
.to_u32()
|
||||||
.ok_or(RustADBError::ConversionError)?;
|
.ok_or(RustADBError::ConversionError)?;
|
||||||
|
|
||||||
Self::encode_public_key(adb_rsa_pubkey.into_bytes())
|
Ok(self.encode_public_key(adb_rsa_pubkey.into_bytes()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_public_key(pub_key: Vec<u8>) -> Result<String> {
|
fn encode_public_key(&self, pub_key: Vec<u8>) -> String {
|
||||||
let mut encoded = STANDARD.encode(pub_key);
|
let mut encoded = STANDARD.encode(pub_key);
|
||||||
encoded.push(' ');
|
encoded.push(' ');
|
||||||
write!(encoded, "adb_client@{}", env!("CARGO_PKG_VERSION"))
|
encoded.push_str(&format!("adb_client@{}", env!("CARGO_PKG_VERSION")));
|
||||||
.map_err(|_| RustADBError::ConversionError)?;
|
|
||||||
|
|
||||||
Ok(encoded)
|
encoded
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
use std::{
|
|
||||||
io::{Read, Write},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
ADBDeviceExt, Result, RustADBError,
|
|
||||||
usb::{RusbTransport, adb_usb_device::ADBUSBDevice, search_adb_devices},
|
|
||||||
utils::get_default_adb_key_path,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Implement Android USB device reachable over wired USB
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ADBRusbDevice {
|
|
||||||
inner: ADBUSBDevice<RusbTransport>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBRusbDevice {
|
|
||||||
/// Instantiate a new [`ADBRusbDevice`]
|
|
||||||
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
|
|
||||||
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Instantiate a new [`ADBRusbDevice`] using a custom private key path
|
|
||||||
pub fn new_with_custom_private_key(
|
|
||||||
vendor_id: u16,
|
|
||||||
product_id: u16,
|
|
||||||
private_key_path: PathBuf,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let transport = RusbTransport::new(vendor_id, product_id)?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
inner: ADBUSBDevice::new_from_transport(transport, Some(private_key_path))?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// autodetect connected ADB devices and establish a connection with the first device found
|
|
||||||
pub fn autodetect() -> Result<Self> {
|
|
||||||
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
|
|
||||||
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
|
|
||||||
match search_adb_devices()? {
|
|
||||||
Some((vendor_id, product_id)) => {
|
|
||||||
ADBRusbDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
|
|
||||||
}
|
|
||||||
_ => Err(RustADBError::DeviceNotFound(
|
|
||||||
"cannot find USB devices matching the signature of an ADB device".into(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBDeviceExt for ADBRusbDevice {
|
|
||||||
#[inline]
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.shell_command(command, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
|
||||||
self.inner.shell(reader, writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
|
|
||||||
self.inner.stat(remote_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.pull(source, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
|
|
||||||
self.inner.push(stream, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
|
|
||||||
self.inner.reboot(reboot_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
self.inner.install(apk_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()> {
|
|
||||||
self.inner.uninstall(package)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
|
||||||
self.inner.framebuffer_inner()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +1,152 @@
|
|||||||
|
use rusb::Device;
|
||||||
|
use rusb::DeviceDescriptor;
|
||||||
|
use rusb::UsbContext;
|
||||||
|
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
|
||||||
|
use std::fs::read_to_string;
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::ADBDeviceExt;
|
use crate::ADBDeviceExt;
|
||||||
use crate::AUTH_TOKEN;
|
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
use crate::RustADBError;
|
use crate::RustADBError;
|
||||||
use crate::message_devices::AUTH_RSAPUBLICKEY;
|
use crate::adb_transport::ADBTransport;
|
||||||
use crate::message_devices::AUTH_SIGNATURE;
|
|
||||||
use crate::message_devices::adb_message_device::ADBMessageDevice;
|
use crate::message_devices::adb_message_device::ADBMessageDevice;
|
||||||
use crate::message_devices::adb_message_transport::ADBMessageTransport;
|
use crate::message_devices::adb_message_transport::ADBMessageTransport;
|
||||||
use crate::message_devices::adb_rsa_key::ADBRsaKey;
|
|
||||||
use crate::message_devices::adb_transport_message::ADBTransportMessage;
|
use crate::message_devices::adb_transport_message::ADBTransportMessage;
|
||||||
use crate::message_devices::message_commands::MessageCommand;
|
use crate::message_devices::message_commands::MessageCommand;
|
||||||
use crate::usb::read_adb_private_key;
|
use crate::usb::adb_rsa_key::ADBRsaKey;
|
||||||
|
use crate::usb::usb_transport::USBTransport;
|
||||||
use crate::utils::get_default_adb_key_path;
|
use crate::utils::get_default_adb_key_path;
|
||||||
|
|
||||||
/// Private struct implementing Android USB device logic, depending on a `ADBMessageTransport`.
|
const AUTH_TOKEN: u32 = 1;
|
||||||
#[derive(Debug)]
|
const AUTH_SIGNATURE: u32 = 2;
|
||||||
pub(crate) struct ADBUSBDevice<T: ADBMessageTransport> {
|
const AUTH_RSAPUBLICKEY: u32 = 3;
|
||||||
private_key: ADBRsaKey,
|
|
||||||
inner: ADBMessageDevice<T>,
|
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
|
||||||
|
// Try to read the private key file from given path
|
||||||
|
// If the file is not found, return None
|
||||||
|
// If there is another error while reading the file, return this error
|
||||||
|
// Else, return the private key content
|
||||||
|
let pk = match read_to_string(private_key_path.as_ref()) {
|
||||||
|
Ok(pk) => pk,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
match ADBRsaKey::new_from_pkcs8(&pk) {
|
||||||
|
Ok(pk) => Ok(Some(pk)),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBUSBDevice<T> {
|
/// Search for adb devices with known interface class and subclass values
|
||||||
/// Instantiate a new [`ADBUSBDevice`] from a [`RusbTransport`] and an optional private key path.
|
pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
|
||||||
pub fn new_from_transport(transport: T, private_key_path: Option<PathBuf>) -> Result<Self> {
|
let mut found_devices = vec![];
|
||||||
|
for device in rusb::devices()?.iter() {
|
||||||
|
let Ok(des) = device.device_descriptor() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if is_adb_device(&device, &des) {
|
||||||
|
log::debug!(
|
||||||
|
"Autodetect device {:04x}:{:04x}",
|
||||||
|
des.vendor_id(),
|
||||||
|
des.product_id()
|
||||||
|
);
|
||||||
|
found_devices.push((des.vendor_id(), des.product_id()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match (found_devices.first(), found_devices.get(1)) {
|
||||||
|
(None, _) => Ok(None),
|
||||||
|
(Some(identifiers), None) => Ok(Some(*identifiers)),
|
||||||
|
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
|
||||||
|
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether a device with given descriptor is an ADB device
|
||||||
|
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
|
||||||
|
const ADB_SUBCLASS: u8 = 0x42;
|
||||||
|
const ADB_PROTOCOL: u8 = 0x1;
|
||||||
|
|
||||||
|
// Some devices require choosing the file transfer mode
|
||||||
|
// for usb debugging to take effect.
|
||||||
|
const BULK_CLASS: u8 = 0xdc;
|
||||||
|
const BULK_ADB_SUBCLASS: u8 = 2;
|
||||||
|
|
||||||
|
for n in 0..des.num_configurations() {
|
||||||
|
let Ok(config_des) = device.config_descriptor(n) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for interface in config_des.interfaces() {
|
||||||
|
for interface_des in interface.descriptors() {
|
||||||
|
let proto = interface_des.protocol_code();
|
||||||
|
let class = interface_des.class_code();
|
||||||
|
let subcl = interface_des.sub_class_code();
|
||||||
|
if proto == ADB_PROTOCOL
|
||||||
|
&& ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|
||||||
|
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represent a device reached and available over USB.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ADBUSBDevice {
|
||||||
|
private_key: ADBRsaKey,
|
||||||
|
inner: ADBMessageDevice<USBTransport>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ADBUSBDevice {
|
||||||
|
/// Instantiate a new [`ADBUSBDevice`]
|
||||||
|
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
|
||||||
|
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path
|
||||||
|
pub fn new_with_custom_private_key(
|
||||||
|
vendor_id: u16,
|
||||||
|
product_id: u16,
|
||||||
|
private_key_path: PathBuf,
|
||||||
|
) -> Result<Self> {
|
||||||
|
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Instantiate a new [`ADBUSBDevice`] from a [`USBTransport`] and an optional private key path.
|
||||||
|
pub fn new_from_transport(
|
||||||
|
transport: USBTransport,
|
||||||
|
private_key_path: Option<PathBuf>,
|
||||||
|
) -> Result<Self> {
|
||||||
let private_key_path = match private_key_path {
|
let private_key_path = match private_key_path {
|
||||||
Some(private_key_path) => private_key_path,
|
Some(private_key_path) => private_key_path,
|
||||||
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(transport: T, private_key_path: &PathBuf) -> Result<Self> {
|
fn new_from_transport_inner(
|
||||||
let private_key = if let Some(private_key) = read_adb_private_key(private_key_path)? {
|
transport: USBTransport,
|
||||||
private_key
|
private_key_path: PathBuf,
|
||||||
} else {
|
) -> Result<Self> {
|
||||||
log::warn!(
|
let private_key = match read_adb_private_key(&private_key_path)? {
|
||||||
"No private key found at path {}. Using a temporary random one.",
|
Some(pk) => pk,
|
||||||
private_key_path.display()
|
None => {
|
||||||
);
|
log::warn!(
|
||||||
ADBRsaKey::new_random()?
|
"No private key found at path {}. Using a temporary random one.",
|
||||||
|
private_key_path.display()
|
||||||
|
);
|
||||||
|
ADBRsaKey::new_random()?
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut s = Self {
|
let mut s = Self {
|
||||||
@@ -56,14 +159,31 @@ impl<T: ADBMessageTransport> ADBUSBDevice<T> {
|
|||||||
Ok(s)
|
Ok(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// autodetect connected ADB devices and establish a connection with the first device found
|
||||||
|
pub fn autodetect() -> Result<Self> {
|
||||||
|
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
|
||||||
|
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
|
||||||
|
match search_adb_devices()? {
|
||||||
|
Some((vendor_id, product_id)) => {
|
||||||
|
ADBUSBDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
|
||||||
|
}
|
||||||
|
_ => Err(RustADBError::DeviceNotFound(
|
||||||
|
"cannot find USB devices matching the signature of an ADB device".into(),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Send initial connect
|
/// Send initial connect
|
||||||
pub fn connect(&mut self) -> Result<()> {
|
pub fn connect(&mut self) -> Result<()> {
|
||||||
self.get_transport_mut().connect()?;
|
self.get_transport_mut().connect()?;
|
||||||
|
|
||||||
let message = ADBTransportMessage::new(
|
let message = ADBTransportMessage::new(
|
||||||
MessageCommand::Cnxn,
|
MessageCommand::Cnxn,
|
||||||
0x0100_0000,
|
0x01000000,
|
||||||
1_048_576,
|
1048576,
|
||||||
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
format!("host::{}\0", env!("CARGO_PKG_NAME")).as_bytes(),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -127,12 +247,12 @@ impl<T: ADBMessageTransport> ADBUSBDevice<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn get_transport_mut(&mut self) -> &mut T {
|
fn get_transport_mut(&mut self) -> &mut USBTransport {
|
||||||
self.inner.get_transport_mut()
|
self.inner.get_transport_mut()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> ADBDeviceExt for ADBUSBDevice<T> {
|
impl ADBDeviceExt for ADBUSBDevice {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
||||||
self.inner.shell_command(command, output)
|
self.inner.shell_command(command, output)
|
||||||
@@ -179,7 +299,7 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBUSBDevice<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ADBMessageTransport> Drop for ADBUSBDevice<T> {
|
impl Drop for ADBUSBDevice {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Best effort here
|
// Best effort here
|
||||||
let _ = self.get_transport_mut().disconnect();
|
let _ = self.get_transport_mut().disconnect();
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
use std::{
|
|
||||||
io::{Read, Write},
|
|
||||||
path::Path,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
ADBDeviceExt, Result,
|
|
||||||
usb::{WebUsbTransport, adb_usb_device::ADBUSBDevice},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Implement Android USB device reachable over wired USB
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ADBWebUsbDevice {
|
|
||||||
inner: ADBUSBDevice<WebUsbTransport>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBWebUsbDevice {
|
|
||||||
/// Instantiate a new [`ADBRusb`]
|
|
||||||
pub fn new(_vendor_id: u16, _product_id: u16) -> Result<Self> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBDeviceExt for ADBWebUsbDevice {
|
|
||||||
#[inline]
|
|
||||||
fn shell_command(&mut self, command: &[&str], output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.shell_command(command, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn shell<'a>(&mut self, reader: &mut dyn Read, writer: Box<dyn Write + Send>) -> Result<()> {
|
|
||||||
self.inner.shell(reader, writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
|
|
||||||
self.inner.stat(remote_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn pull(&mut self, source: &dyn AsRef<str>, output: &mut dyn Write) -> Result<()> {
|
|
||||||
self.inner.pull(source, output)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn push(&mut self, stream: &mut dyn Read, path: &dyn AsRef<str>) -> Result<()> {
|
|
||||||
self.inner.push(stream, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
|
|
||||||
self.inner.reboot(reboot_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()> {
|
|
||||||
self.inner.install(apk_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn uninstall(&mut self, package: &str) -> Result<()> {
|
|
||||||
self.inner.uninstall(package)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
|
|
||||||
self.inner.framebuffer_inner()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
#[cfg(feature = "rusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
|
|
||||||
pub mod rusb_transport;
|
|
||||||
|
|
||||||
#[cfg(feature = "webusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
|
|
||||||
pub mod webusb_transport;
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
Result,
|
|
||||||
adb_transport::ADBTransport,
|
|
||||||
message_devices::{
|
|
||||||
adb_message_transport::ADBMessageTransport, adb_transport_message::ADBTransportMessage,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Transport running on USB using `webusb` as a backend.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct WebUsbTransport {}
|
|
||||||
|
|
||||||
impl WebUsbTransport {
|
|
||||||
/// Instantiate a new [`WebUsbTransport`].
|
|
||||||
/// Only the first device with given vendor_id and product_id is returned.
|
|
||||||
pub fn new() -> Self {
|
|
||||||
WebUsbTransport {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBTransport for WebUsbTransport {
|
|
||||||
fn connect(&mut self) -> crate::Result<()> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn disconnect(&mut self) -> crate::Result<()> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ADBMessageTransport for WebUsbTransport {
|
|
||||||
fn read_message_with_timeout(
|
|
||||||
&mut self,
|
|
||||||
_read_timeout: Duration,
|
|
||||||
) -> Result<ADBTransportMessage> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_message_with_timeout(
|
|
||||||
&mut self,
|
|
||||||
message: ADBTransportMessage,
|
|
||||||
write_timeout: std::time::Duration,
|
|
||||||
) -> Result<()> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,78 +1,8 @@
|
|||||||
#![doc = include_str!("./README.md")]
|
#![doc = include_str!("./README.md")]
|
||||||
|
|
||||||
/// Common USB constants for Android Debug Bridge
|
mod adb_rsa_key;
|
||||||
pub mod constants {
|
|
||||||
/// Standard Android vendor ID
|
|
||||||
pub const ANDROID_VENDOR_ID: u16 = 0x18d1;
|
|
||||||
|
|
||||||
/// Common ADB product IDs
|
|
||||||
pub mod product_ids {
|
|
||||||
/// ADB interface
|
|
||||||
pub const ADB: u16 = 0x4ee7;
|
|
||||||
/// ADB + MTP
|
|
||||||
pub const ADB_MTP: u16 = 0x4ee2;
|
|
||||||
/// ADB + RNDIS
|
|
||||||
pub const ADB_RNDIS: u16 = 0x4ee4;
|
|
||||||
/// Fastboot interface
|
|
||||||
pub const FASTBOOT: u16 = 0x4ee0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// USB class codes for ADB detection
|
|
||||||
pub mod class_codes {
|
|
||||||
/// ADB subclass code
|
|
||||||
pub const ADB_SUBCLASS: u8 = 0x42;
|
|
||||||
/// ADB protocol code
|
|
||||||
pub const ADB_PROTOCOL: u8 = 0x1;
|
|
||||||
/// Bulk transfer class
|
|
||||||
pub const BULK_CLASS: u8 = 0xdc;
|
|
||||||
/// Bulk ADB subclass
|
|
||||||
pub const BULK_ADB_SUBCLASS: u8 = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ###################################################
|
|
||||||
// rusb specific modules
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
mod adb_rusb_device;
|
|
||||||
|
|
||||||
// Device implementations
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
|
|
||||||
pub use adb_rusb_device::ADBRusbDevice;
|
|
||||||
|
|
||||||
// Transport implementations
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
|
|
||||||
pub use backends::rusb_transport::RusbTransport;
|
|
||||||
// ###################################################
|
|
||||||
|
|
||||||
// ###################################################
|
|
||||||
// webusb specific modules
|
|
||||||
#[cfg(feature = "webusb")]
|
|
||||||
mod adb_webusb_device;
|
|
||||||
|
|
||||||
// Device implementations
|
|
||||||
#[cfg(feature = "webusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
|
|
||||||
pub use adb_webusb_device::ADBWebUsbDevice;
|
|
||||||
|
|
||||||
// Transport implementations
|
|
||||||
#[cfg(feature = "webusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "webusb")))]
|
|
||||||
pub use backends::webusb_transport::WebUsbTransport;
|
|
||||||
// ###################################################
|
|
||||||
|
|
||||||
mod backends;
|
|
||||||
mod utils;
|
|
||||||
|
|
||||||
#[cfg(any(feature = "rusb", feature = "webusb"))]
|
|
||||||
mod adb_usb_device;
|
mod adb_usb_device;
|
||||||
|
mod usb_transport;
|
||||||
|
|
||||||
// Utility functions
|
pub use adb_usb_device::ADBUSBDevice;
|
||||||
#[cfg(any(feature = "rusb", feature = "webusb"))]
|
pub use usb_transport::USBTransport;
|
||||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "rusb", feature = "webusb"))))]
|
|
||||||
pub use utils::read_adb_private_key;
|
|
||||||
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "rusb")))]
|
|
||||||
pub use utils::{is_adb_device, search_adb_devices};
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ use crate::{
|
|||||||
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader},
|
||||||
message_commands::MessageCommand,
|
message_commands::MessageCommand,
|
||||||
},
|
},
|
||||||
usb::constants::class_codes::ADB_SUBCLASS,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -23,17 +22,17 @@ struct Endpoint {
|
|||||||
max_packet_size: usize,
|
max_packet_size: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport running on USB using `rusb` as a backend.
|
/// Transport running on USB
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct RusbTransport {
|
pub struct USBTransport {
|
||||||
device: Device<GlobalContext>,
|
device: Device<GlobalContext>,
|
||||||
handle: Option<Arc<DeviceHandle<GlobalContext>>>,
|
handle: Option<Arc<DeviceHandle<GlobalContext>>>,
|
||||||
read_endpoint: Option<Endpoint>,
|
read_endpoint: Option<Endpoint>,
|
||||||
write_endpoint: Option<Endpoint>,
|
write_endpoint: Option<Endpoint>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RusbTransport {
|
impl USBTransport {
|
||||||
/// Instantiate a new [`RusbTransport`].
|
/// Instantiate a new [`USBTransport`].
|
||||||
/// Only the first device with given vendor_id and product_id is returned.
|
/// Only the first device with given vendor_id and product_id is returned.
|
||||||
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
|
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
|
||||||
for device in rusb::devices()?.iter() {
|
for device in rusb::devices()?.iter() {
|
||||||
@@ -49,7 +48,7 @@ impl RusbTransport {
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Instantiate a new [`RusbTransport`] from a [`rusb::Device`].
|
/// Instantiate a new [`USBTransport`] from a [`rusb::Device`].
|
||||||
///
|
///
|
||||||
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
|
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
|
||||||
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
|
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
|
||||||
@@ -95,13 +94,14 @@ impl RusbTransport {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_endpoints(handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
fn find_endpoints(&self, handle: &DeviceHandle<GlobalContext>) -> Result<(Endpoint, Endpoint)> {
|
||||||
let mut read_endpoint: Option<Endpoint> = None;
|
let mut read_endpoint: Option<Endpoint> = None;
|
||||||
let mut write_endpoint: Option<Endpoint> = None;
|
let mut write_endpoint: Option<Endpoint> = None;
|
||||||
|
|
||||||
for n in 0..handle.device().device_descriptor()?.num_configurations() {
|
for n in 0..handle.device().device_descriptor()?.num_configurations() {
|
||||||
let Ok(config_desc) = handle.device().config_descriptor(n) else {
|
let config_desc = match handle.device().config_descriptor(n) {
|
||||||
continue;
|
Ok(c) => c,
|
||||||
|
Err(_) => continue,
|
||||||
};
|
};
|
||||||
|
|
||||||
for interface in config_desc.interfaces() {
|
for interface in config_desc.interfaces() {
|
||||||
@@ -109,7 +109,7 @@ impl RusbTransport {
|
|||||||
for endpoint_desc in interface_desc.endpoint_descriptors() {
|
for endpoint_desc in interface_desc.endpoint_descriptors() {
|
||||||
if endpoint_desc.transfer_type() == TransferType::Bulk
|
if endpoint_desc.transfer_type() == TransferType::Bulk
|
||||||
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC
|
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC
|
||||||
&& interface_desc.sub_class_code() == ADB_SUBCLASS
|
&& interface_desc.sub_class_code() == 0x42
|
||||||
&& interface_desc.protocol_code() == 0x01
|
&& interface_desc.protocol_code() == 0x01
|
||||||
{
|
{
|
||||||
let endpoint = Endpoint {
|
let endpoint = Endpoint {
|
||||||
@@ -121,14 +121,16 @@ impl RusbTransport {
|
|||||||
Direction::In => {
|
Direction::In => {
|
||||||
if let Some(write_endpoint) = write_endpoint {
|
if let Some(write_endpoint) = write_endpoint {
|
||||||
return Ok((endpoint, write_endpoint));
|
return Ok((endpoint, write_endpoint));
|
||||||
|
} else {
|
||||||
|
read_endpoint = Some(endpoint);
|
||||||
}
|
}
|
||||||
read_endpoint = Some(endpoint);
|
|
||||||
}
|
}
|
||||||
Direction::Out => {
|
Direction::Out => {
|
||||||
if let Some(read_endpoint) = read_endpoint {
|
if let Some(read_endpoint) = read_endpoint {
|
||||||
return Ok((read_endpoint, endpoint));
|
return Ok((read_endpoint, endpoint));
|
||||||
|
} else {
|
||||||
|
write_endpoint = Some(endpoint);
|
||||||
}
|
}
|
||||||
write_endpoint = Some(endpoint);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -152,7 +154,7 @@ impl RusbTransport {
|
|||||||
let write_amount = handle.write_bulk(endpoint.address, &data[offset..end], timeout)?;
|
let write_amount = handle.write_bulk(endpoint.address, &data[offset..end], timeout)?;
|
||||||
offset += write_amount;
|
offset += write_amount;
|
||||||
|
|
||||||
log::trace!("wrote chunk of size {write_amount} - {offset}/{data_len}",);
|
log::trace!("wrote chunk of size {write_amount} - {offset}/{data_len}",)
|
||||||
}
|
}
|
||||||
|
|
||||||
if offset % max_packet_size == 0 {
|
if offset % max_packet_size == 0 {
|
||||||
@@ -164,11 +166,11 @@ impl RusbTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBTransport for RusbTransport {
|
impl ADBTransport for USBTransport {
|
||||||
fn connect(&mut self) -> crate::Result<()> {
|
fn connect(&mut self) -> crate::Result<()> {
|
||||||
let device = self.device.open()?;
|
let device = self.device.open()?;
|
||||||
|
|
||||||
let (read_endpoint, write_endpoint) = Self::find_endpoints(&device)?;
|
let (read_endpoint, write_endpoint) = self.find_endpoints(&device)?;
|
||||||
|
|
||||||
Self::configure_endpoint(&device, &read_endpoint)?;
|
Self::configure_endpoint(&device, &read_endpoint)?;
|
||||||
log::debug!("got read endpoint: {read_endpoint:?}");
|
log::debug!("got read endpoint: {read_endpoint:?}");
|
||||||
@@ -203,7 +205,7 @@ impl ADBTransport for RusbTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBMessageTransport for RusbTransport {
|
impl ADBMessageTransport for USBTransport {
|
||||||
fn write_message_with_timeout(
|
fn write_message_with_timeout(
|
||||||
&mut self,
|
&mut self,
|
||||||
message: ADBTransportMessage,
|
message: ADBTransportMessage,
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
//! USB utilities that are independent of specific transport implementations
|
|
||||||
|
|
||||||
use crate::message_devices::adb_rsa_key::ADBRsaKey;
|
|
||||||
use crate::{Result, RustADBError};
|
|
||||||
use std::fs::read_to_string;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
use rusb::{Device, DeviceDescriptor, UsbContext};
|
|
||||||
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
use rusb::constants::LIBUSB_CLASS_VENDOR_SPEC;
|
|
||||||
|
|
||||||
use crate::usb::constants::class_codes::{
|
|
||||||
ADB_PROTOCOL, ADB_SUBCLASS, BULK_ADB_SUBCLASS, BULK_CLASS,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Read an ADB private key from a file path
|
|
||||||
///
|
|
||||||
/// Returns `Ok(None)` if the file doesn't exist, `Ok(Some(key))` if the key was successfully loaded,
|
|
||||||
/// or an error if there was a problem reading the file.
|
|
||||||
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
|
|
||||||
// Try to read the private key file from given path
|
|
||||||
// If the file is not found, return None
|
|
||||||
// If there is another error while reading the file, return this error
|
|
||||||
// Else, return the private key content
|
|
||||||
let pk = match read_to_string(private_key_path.as_ref()) {
|
|
||||||
Ok(pk) => pk,
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
|
||||||
Err(e) => return Err(e.into()),
|
|
||||||
};
|
|
||||||
|
|
||||||
match ADBRsaKey::new_from_pkcs8(&pk) {
|
|
||||||
Ok(pk) => Ok(Some(pk)),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Search for ADB devices connected via USB
|
|
||||||
///
|
|
||||||
/// Returns the vendor_id and product_id of the first ADB device found,
|
|
||||||
/// or `None` if no devices are found.
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
pub fn search_adb_devices() -> Result<Option<(u16, u16)>> {
|
|
||||||
let mut found_devices = vec![];
|
|
||||||
for device in rusb::devices()?.iter() {
|
|
||||||
let Ok(des) = device.device_descriptor() else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if is_adb_device(&device, &des) {
|
|
||||||
log::debug!(
|
|
||||||
"Autodetect device {:04x}:{:04x}",
|
|
||||||
des.vendor_id(),
|
|
||||||
des.product_id()
|
|
||||||
);
|
|
||||||
found_devices.push((des.vendor_id(), des.product_id()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match (found_devices.first(), found_devices.get(1)) {
|
|
||||||
(None, _) => Ok(None),
|
|
||||||
(Some(identifiers), None) => Ok(Some(*identifiers)),
|
|
||||||
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
|
|
||||||
"Found two Android devices {vid1:04x}:{pid1:04x} and {vid2:04x}:{pid2:04x}",
|
|
||||||
))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if a USB device is an ADB device
|
|
||||||
///
|
|
||||||
/// This function inspects the device descriptor and configuration to determine
|
|
||||||
/// if it's an Android Debug Bridge device.
|
|
||||||
#[cfg(feature = "rusb")]
|
|
||||||
pub fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
|
|
||||||
// Some devices require choosing the file transfer mode
|
|
||||||
// for usb debugging to take effect.
|
|
||||||
for n in 0..des.num_configurations() {
|
|
||||||
let Ok(config_des) = device.config_descriptor(n) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
for interface in config_des.interfaces() {
|
|
||||||
for interface_des in interface.descriptors() {
|
|
||||||
let proto = interface_des.protocol_code();
|
|
||||||
let class = interface_des.class_code();
|
|
||||||
let subcl = interface_des.sub_class_code();
|
|
||||||
if proto == ADB_PROTOCOL
|
|
||||||
&& ((class == LIBUSB_CLASS_VENDOR_SPEC && subcl == ADB_SUBCLASS)
|
|
||||||
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
false
|
|
||||||
}
|
|
||||||
@@ -9,7 +9,7 @@ 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>,
|
||||||
@@ -21,7 +21,7 @@ pub struct ADBServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ADBServer {
|
impl ADBServer {
|
||||||
/// Instantiates a new [`ADBServer`]
|
/// Instantiates a new [ADBServer]
|
||||||
pub fn new(address: SocketAddrV4) -> Self {
|
pub fn new(address: SocketAddrV4) -> Self {
|
||||||
Self {
|
Self {
|
||||||
transport: None,
|
transport: None,
|
||||||
@@ -31,7 +31,7 @@ impl ADBServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Instantiates a new [`ADBServer`] with a custom adb path
|
/// Instantiates a new [ADBServer] with a custom adb path
|
||||||
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
|
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
transport: None,
|
transport: None,
|
||||||
@@ -46,7 +46,7 @@ impl ADBServer {
|
|||||||
// ADB Server is local, we start it if not already running
|
// ADB Server is local, we start it if not already running
|
||||||
let mut command = Command::new(adb_path.as_deref().unwrap_or("adb"));
|
let mut command = Command::new(adb_path.as_deref().unwrap_or("adb"));
|
||||||
command.arg("start-server");
|
command.arg("start-server");
|
||||||
for (env_k, env_v) in envs {
|
for (env_k, env_v) in envs.iter() {
|
||||||
command.env(env_k, env_v);
|
command.env(env_k, env_v);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ impl ADBServer {
|
|||||||
match child {
|
match child {
|
||||||
Ok(mut child) => {
|
Ok(mut child) => {
|
||||||
if let Err(e) = child.wait() {
|
if let Err(e) = child.wait() {
|
||||||
log::error!("error while starting adb server: {e}");
|
log::error!("error while starting adb server: {e}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => log::error!("error while starting adb server: {e}"),
|
Err(e) => log::error!("error while starting adb server: {e}"),
|
||||||
|
|||||||
@@ -71,12 +71,12 @@ impl ADBServer {
|
|||||||
.filter(|d| d.identifier.as_str() == name)
|
.filter(|d| d.identifier.as_str() == name)
|
||||||
.collect::<Vec<DeviceShort>>()
|
.collect::<Vec<DeviceShort>>()
|
||||||
.len();
|
.len();
|
||||||
if nb_devices == 1 {
|
if nb_devices != 1 {
|
||||||
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
|
||||||
} else {
|
|
||||||
Err(RustADBError::DeviceNotFound(format!(
|
Err(RustADBError::DeviceNotFound(format!(
|
||||||
"could not find device {name}"
|
"could not find device {name}"
|
||||||
)))
|
)))
|
||||||
|
} else {
|
||||||
|
Ok(ADBServerDevice::new(name.to_string(), self.socket_addr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ pub struct AdbVersion {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AdbVersion {
|
impl AdbVersion {
|
||||||
/// Instantiates a new [`AdbVersion`].
|
/// Instantiates a new [AdbVersion].
|
||||||
pub fn new(minor: u32, revision: u32) -> Self {
|
pub fn new(minor: u32, revision: u32) -> Self {
|
||||||
Self {
|
Self {
|
||||||
major: 1,
|
major: 1,
|
||||||
|
|||||||
@@ -87,13 +87,15 @@ impl TryFrom<&[u8]> for DeviceLong {
|
|||||||
None => "Unk".to_string(),
|
None => "Unk".to_string(),
|
||||||
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
Some(device) => String::from_utf8(device.as_bytes().to_vec())?,
|
||||||
},
|
},
|
||||||
transport_id: (str::from_utf8(
|
transport_id: u32::from_str_radix(
|
||||||
groups
|
str::from_utf8(
|
||||||
.name("transport_id")
|
groups
|
||||||
.ok_or(RustADBError::RegexParsingError)?
|
.name("transport_id")
|
||||||
.as_bytes(),
|
.ok_or(RustADBError::RegexParsingError)?
|
||||||
)?)
|
.as_bytes(),
|
||||||
.parse::<u32>()?,
|
)?,
|
||||||
|
16,
|
||||||
|
)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::fmt::Display;
|
|||||||
|
|
||||||
use crate::RustADBError;
|
use crate::RustADBError;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug)]
|
||||||
/// List of available transports to wait for.
|
/// List of available transports to wait for.
|
||||||
pub enum WaitForDeviceTransport {
|
pub enum WaitForDeviceTransport {
|
||||||
/// USB transport
|
/// USB transport
|
||||||
@@ -10,10 +10,15 @@ pub enum WaitForDeviceTransport {
|
|||||||
/// Local transport
|
/// Local transport
|
||||||
Local,
|
Local,
|
||||||
/// Any transport (default value)
|
/// Any transport (default value)
|
||||||
#[default]
|
|
||||||
Any,
|
Any,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for WaitForDeviceTransport {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::Any
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for WaitForDeviceTransport {
|
impl Display for WaitForDeviceTransport {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use crate::models::{AdbRequestStatus, SyncCommand};
|
|||||||
use crate::server::AdbServerCommand;
|
use crate::server::AdbServerCommand;
|
||||||
use crate::{Result, RustADBError};
|
use crate::{Result, RustADBError};
|
||||||
|
|
||||||
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::LOCALHOST;
|
const DEFAULT_SERVER_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
|
||||||
const DEFAULT_SERVER_PORT: u16 = 5037;
|
const DEFAULT_SERVER_PORT: u16 = 5037;
|
||||||
|
|
||||||
/// Server transport running on top on TCP
|
/// Server transport running on top on TCP
|
||||||
@@ -26,7 +26,7 @@ impl Default for TCPServerTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TCPServerTransport {
|
impl TCPServerTransport {
|
||||||
/// Instantiates a new instance of [`TCPServerTransport`]
|
/// Instantiates a new instance of [TCPServerTransport]
|
||||||
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
pub fn new(socket_addr: SocketAddrV4) -> Self {
|
||||||
Self {
|
Self {
|
||||||
socket_addr,
|
socket_addr,
|
||||||
@@ -34,7 +34,7 @@ impl TCPServerTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Instantiate a new instance of [`TCPServerTransport`] using given address, or default if not specified.
|
/// Instantiate a new instance of [TCPServerTransport] using given address, or default if not specified.
|
||||||
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
|
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
|
||||||
match socket_addr {
|
match socket_addr {
|
||||||
Some(s) => Self::new(s),
|
Some(s) => Self::new(s),
|
||||||
@@ -42,7 +42,7 @@ impl TCPServerTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get underlying [`SocketAddrV4`]
|
/// Get underlying [SocketAddrV4]
|
||||||
pub fn get_socketaddr(&self) -> SocketAddrV4 {
|
pub fn get_socketaddr(&self) -> SocketAddrV4 {
|
||||||
self.socket_addr
|
self.socket_addr
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ impl TCPServerTransport {
|
|||||||
)?)
|
)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send the given [`SyncCommand`] to ADB server, and checks that the request has been taken in consideration.
|
/// Send the given [SyncCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||||
pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> {
|
pub(crate) fn send_sync_request(&mut self, command: SyncCommand) -> Result<()> {
|
||||||
// First 4 bytes are the name of the command we want to send
|
// First 4 bytes are the name of the command we want to send
|
||||||
// (e.g. "SEND", "RECV", "STAT", "LIST")
|
// (e.g. "SEND", "RECV", "STAT", "LIST")
|
||||||
@@ -99,7 +99,7 @@ impl TCPServerTransport {
|
|||||||
.write_all(command.to_string().as_bytes())?)
|
.write_all(command.to_string().as_bytes())?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the body length from a `LittleEndian` value
|
/// Gets the body length from a LittleEndian value
|
||||||
pub(crate) fn get_body_length(&self) -> Result<u32> {
|
pub(crate) fn get_body_length(&self) -> Result<u32> {
|
||||||
let length_buffer = self.read_body_length()?;
|
let length_buffer = self.read_body_length()?;
|
||||||
Ok(LittleEndian::read_u32(&length_buffer))
|
Ok(LittleEndian::read_u32(&length_buffer))
|
||||||
@@ -113,8 +113,8 @@ impl TCPServerTransport {
|
|||||||
Ok(length_buffer)
|
Ok(length_buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send the given [`AdbCommand`] to ADB server, and checks that the request has been taken in consideration.
|
/// Send the given [AdbCommand] to ADB server, and checks that the request has been taken in consideration.
|
||||||
/// If an error occurred, a [`RustADBError`] is returned with the response error string.
|
/// If an error occurred, a [RustADBError] is returned with the response error string.
|
||||||
pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> {
|
pub(crate) fn send_adb_request(&mut self, command: AdbServerCommand) -> Result<()> {
|
||||||
let adb_command_string = command.to_string();
|
let adb_command_string = command.to_string();
|
||||||
let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string);
|
let adb_request = format!("{:04x}{}", adb_command_string.len(), adb_command_string);
|
||||||
|
|||||||
@@ -20,6 +20,6 @@ use std::path::Path;
|
|||||||
|
|
||||||
let mut server = ADBServer::default();
|
let mut server = ADBServer::default();
|
||||||
let mut device = server.get_device().expect("cannot get device");
|
let mut device = server.get_device().expect("cannot get device");
|
||||||
let mut input = File::open("/tmp/file.txt").expect("Cannot open file");
|
let mut input = File::open(Path::new("/tmp/file.txt")).expect("Cannot open file");
|
||||||
device.push(&mut input, "/data/local/tmp");
|
device.push(&mut input, "/data/local/tmp");
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -9,12 +9,12 @@ use std::net::SocketAddrV4;
|
|||||||
pub struct ADBServerDevice {
|
pub struct ADBServerDevice {
|
||||||
/// Unique device identifier.
|
/// Unique device identifier.
|
||||||
pub identifier: Option<String>,
|
pub identifier: Option<String>,
|
||||||
/// Internal [`TCPServerTransport`]
|
/// Internal [TCPServerTransport]
|
||||||
pub(crate) transport: TCPServerTransport,
|
pub(crate) transport: TCPServerTransport,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ADBServerDevice {
|
impl ADBServerDevice {
|
||||||
/// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
|
/// Instantiates a new [ADBServerDevice], knowing its ADB identifier (as returned by `adb devices` command).
|
||||||
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
|
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
|
||||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ impl ADBServerDevice {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
|
/// Instantiates a new [ADBServerDevice], assuming only one is currently connected.
|
||||||
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
|
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
|
||||||
let transport = TCPServerTransport::new_or_default(server_addr);
|
let transport = TCPServerTransport::new_or_default(server_addr);
|
||||||
|
|
||||||
|
|||||||
@@ -27,14 +27,15 @@ impl ADBDeviceExt for ADBServerDevice {
|
|||||||
self.transport
|
self.transport
|
||||||
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
|
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
|
||||||
|
|
||||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
|
||||||
loop {
|
loop {
|
||||||
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
match self.transport.get_raw_connection()?.read(&mut buffer) {
|
match self.transport.get_raw_connection()?.read(&mut buffer) {
|
||||||
Ok(size) => {
|
Ok(size) => {
|
||||||
if size == 0 {
|
if size == 0 {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
} else {
|
||||||
|
output.write_all(&buffer[..size])?;
|
||||||
}
|
}
|
||||||
output.write_all(&buffer[..size])?;
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Err(RustADBError::IOError(e));
|
return Err(RustADBError::IOError(e));
|
||||||
@@ -68,9 +69,8 @@ impl ADBDeviceExt for ADBServerDevice {
|
|||||||
|
|
||||||
// Reading thread, reads response from adb-server
|
// Reading thread, reads response from adb-server
|
||||||
std::thread::spawn(move || -> Result<()> {
|
std::thread::spawn(move || -> Result<()> {
|
||||||
let mut buffer = vec![0; BUFFER_SIZE].into_boxed_slice();
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
let mut buffer = [0; BUFFER_SIZE];
|
||||||
match read_stream.read(&mut buffer) {
|
match read_stream.read(&mut buffer) {
|
||||||
Ok(0) => {
|
Ok(0) => {
|
||||||
read_stream.shutdown(std::net::Shutdown::Both)?;
|
read_stream.shutdown(std::net::Shutdown::Both)?;
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ impl ADBServerDevice {
|
|||||||
// 'DONE' directly without listing anything.
|
// 'DONE' directly without listing anything.
|
||||||
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> {
|
fn handle_list_command<S: AsRef<str>>(&mut self, path: S) -> Result<()> {
|
||||||
let mut len_buf = [0_u8; 4];
|
let mut len_buf = [0_u8; 4];
|
||||||
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
|
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
|
||||||
|
|
||||||
// 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.transport.get_raw_connection()?.write_all(&len_buf)?;
|
self.transport.get_raw_connection()?.write_all(&len_buf)?;
|
||||||
|
|||||||
@@ -23,26 +23,21 @@ 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 mut processed = 0;
|
let buf_clone = self.buffer.clone();
|
||||||
while let Some(pos) = self.buffer[processed..].iter().position(|&b| b == b'\n') {
|
let mut lines = buf_clone.split_inclusive(|&byte| byte == b'\n').peekable();
|
||||||
// Found a newline, need to process it
|
|
||||||
let end = processed + pos + 1; // +1 to include the '\n'
|
|
||||||
let line = &self.buffer[processed..end];
|
|
||||||
|
|
||||||
if self.should_write(line) {
|
while let Some(line) = lines.next() {
|
||||||
self.writer.write_all(line)?;
|
if lines.peek().is_some() {
|
||||||
|
if self.should_write(line) {
|
||||||
|
self.writer.write_all(line)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// This is the last (unfinished) element, we keep it for next round
|
||||||
|
self.buffer = line.to_vec();
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
processed = end;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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())
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::{
|
|||||||
use byteorder::{LittleEndian, ReadBytesExt};
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
use std::io::{BufReader, BufWriter, Read, Write};
|
use std::io::{BufReader, BufWriter, Read, Write};
|
||||||
|
|
||||||
/// Internal structure wrapping a [`std::io::Read`] and hiding underlying protocol logic.
|
/// Internal structure wrapping a [std::io::Read] and hiding underlying protocol logic.
|
||||||
struct ADBRecvCommandReader<R: Read> {
|
struct ADBRecvCommandReader<R: Read> {
|
||||||
inner: R,
|
inner: R,
|
||||||
remaining_data_bytes_to_read: usize,
|
remaining_data_bytes_to_read: usize,
|
||||||
@@ -87,7 +87,7 @@ impl ADBServerDevice {
|
|||||||
|
|
||||||
let from_as_bytes = from.as_ref().as_bytes();
|
let from_as_bytes = from.as_ref().as_bytes();
|
||||||
let mut buffer = Vec::with_capacity(4 + from_as_bytes.len());
|
let mut buffer = Vec::with_capacity(4 + from_as_bytes.len());
|
||||||
buffer.extend_from_slice(&(u32::try_from(from.as_ref().len())?).to_le_bytes());
|
buffer.extend_from_slice(&(from.as_ref().len() as u32).to_le_bytes());
|
||||||
buffer.extend_from_slice(from_as_bytes);
|
buffer.extend_from_slice(from_as_bytes);
|
||||||
raw_connection.write_all(&buffer)?;
|
raw_connection.write_all(&buffer)?;
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use std::{
|
|||||||
time::SystemTime,
|
time::SystemTime,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Internal structure wrapping a [`std::io::Write`] and hiding underlying protocol logic.
|
/// Internal structure wrapping a [std::io::Write] and hiding underlying protocol logic.
|
||||||
struct ADBSendCommandWriter<W: Write> {
|
struct ADBSendCommandWriter<W: Write> {
|
||||||
inner: W,
|
inner: W,
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,7 @@ impl ADBServerDevice {
|
|||||||
// The name of the command is already sent by get_transport()?.send_sync_request
|
// The name of the command is already sent by get_transport()?.send_sync_request
|
||||||
let to_as_bytes = to.as_bytes();
|
let to_as_bytes = to.as_bytes();
|
||||||
let mut buffer = Vec::with_capacity(4 + to_as_bytes.len());
|
let mut buffer = Vec::with_capacity(4 + to_as_bytes.len());
|
||||||
buffer.extend_from_slice(&(u32::try_from(to.len())?).to_le_bytes());
|
buffer.extend_from_slice(&(to.len() as u32).to_le_bytes());
|
||||||
buffer.extend_from_slice(to_as_bytes);
|
buffer.extend_from_slice(to_as_bytes);
|
||||||
raw_connection.write_all(&buffer)?;
|
raw_connection.write_all(&buffer)?;
|
||||||
|
|
||||||
@@ -81,10 +81,9 @@ impl ADBServerDevice {
|
|||||||
|
|
||||||
// Copy is finished, we can now notify as finished
|
// Copy is finished, we can now notify as finished
|
||||||
// Have to send DONE + file mtime
|
// Have to send DONE + file mtime
|
||||||
let Ok(last_modified) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) else {
|
let last_modified = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
|
||||||
return Err(RustADBError::ADBRequestFailed(
|
Ok(n) => n,
|
||||||
"SystemTime before UNIX EPOCH!".into(),
|
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
|
||||||
));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut done_buffer = Vec::with_capacity(8);
|
let mut done_buffer = Vec::with_capacity(8);
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::{
|
|||||||
impl ADBServerDevice {
|
impl ADBServerDevice {
|
||||||
fn handle_stat_command<S: AsRef<str>>(&mut self, path: S) -> Result<AdbStatResponse> {
|
fn handle_stat_command<S: AsRef<str>>(&mut self, path: S) -> Result<AdbStatResponse> {
|
||||||
let mut len_buf = [0_u8; 4];
|
let mut len_buf = [0_u8; 4];
|
||||||
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
|
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
|
||||||
|
|
||||||
// 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.transport.get_raw_connection()?.write_all(&len_buf)?;
|
self.transport.get_raw_connection()?.write_all(&len_buf)?;
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ pub fn check_extension_is_apk<P: AsRef<Path>>(path: P) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_default_adb_key_path() -> Result<PathBuf> {
|
pub fn get_default_adb_key_path() -> Result<PathBuf> {
|
||||||
std::env::home_dir()
|
homedir::my_home()
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
.map(|home| home.join(".android").join("adbkey"))
|
.map(|home| home.join(".android").join("adbkey"))
|
||||||
.ok_or(RustADBError::NoHomeDirectory)
|
.ok_or(RustADBError::NoHomeDirectory)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ doc = false
|
|||||||
name = "stub_gen"
|
name = "stub_gen"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
adb_client = { path = "../adb_client" }
|
adb_client = { path = "../adb_client", features = ["usb"] }
|
||||||
anyhow = { version = "1.0.100" }
|
anyhow = { version = "1.0.95" }
|
||||||
pyo3 = { version = "0.27.1", features = ["abi3-py310", "anyhow"] }
|
pyo3 = { version = "0.25.0", features = ["abi3-py37", "anyhow"] }
|
||||||
pyo3-stub-gen = { version = "0.17.0" }
|
pyo3-stub-gen = "0.7.0"
|
||||||
pyo3-stub-gen-derive = { version = "0.17.0" }
|
pyo3-stub-gen-derive = "0.7.0"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ requires = ["maturin>=1,<2"]
|
|||||||
classifiers = ["Programming Language :: Python", "Programming Language :: Rust"]
|
classifiers = ["Programming Language :: Python", "Programming Language :: Rust"]
|
||||||
dynamic = ["authors", "keywords", "version"]
|
dynamic = ["authors", "keywords", "version"]
|
||||||
name = "pyadb_client"
|
name = "pyadb_client"
|
||||||
requires-python = ">= 3.10"
|
requires-python = ">= 3.7"
|
||||||
|
|
||||||
[tool.maturin]
|
[tool.maturin]
|
||||||
features = ["pyo3/extension-module"]
|
features = ["pyo3/extension-module"]
|
||||||
@@ -16,7 +16,7 @@ pub struct PyADBServer(ADBServer);
|
|||||||
#[pymethods]
|
#[pymethods]
|
||||||
impl PyADBServer {
|
impl PyADBServer {
|
||||||
#[new]
|
#[new]
|
||||||
/// Instantiate a new `PyADBServer` instance
|
/// Instantiate a new PyADBServer instance
|
||||||
pub fn new(address: String) -> PyResult<Self> {
|
pub fn new(address: String) -> PyResult<Self> {
|
||||||
let address = address.parse::<SocketAddrV4>()?;
|
let address = address.parse::<SocketAddrV4>()?;
|
||||||
Ok(ADBServer::new(address).into())
|
Ok(ADBServer::new(address).into())
|
||||||
@@ -24,12 +24,7 @@ impl PyADBServer {
|
|||||||
|
|
||||||
/// List available devices
|
/// List available devices
|
||||||
pub fn devices(&mut self) -> Result<Vec<PyDeviceShort>> {
|
pub fn devices(&mut self) -> Result<Vec<PyDeviceShort>> {
|
||||||
Ok(self
|
Ok(self.0.devices()?.into_iter().map(|v| v.into()).collect())
|
||||||
.0
|
|
||||||
.devices()?
|
|
||||||
.into_iter()
|
|
||||||
.map(std::convert::Into::into)
|
|
||||||
.collect())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a device, assuming that only one is currently connected
|
/// Get a device, assuming that only one is currently connected
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{fs::File, path::PathBuf};
|
use std::{fs::File, path::PathBuf};
|
||||||
|
|
||||||
use adb_client::{ADBDeviceExt, usb::ADBRusbDevice};
|
use adb_client::{ADBDeviceExt, usb::ADBUSBDevice};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use pyo3::{pyclass, pymethods};
|
use pyo3::{pyclass, pymethods};
|
||||||
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
|
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
|
||||||
@@ -8,7 +8,7 @@ use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
|
|||||||
#[gen_stub_pyclass]
|
#[gen_stub_pyclass]
|
||||||
#[pyclass]
|
#[pyclass]
|
||||||
/// Represent a device directly reachable over USB.
|
/// Represent a device directly reachable over USB.
|
||||||
pub struct PyADBUSBDevice(ADBRusbDevice);
|
pub struct PyADBUSBDevice(ADBUSBDevice);
|
||||||
|
|
||||||
#[gen_stub_pymethods]
|
#[gen_stub_pymethods]
|
||||||
#[pymethods]
|
#[pymethods]
|
||||||
@@ -17,7 +17,7 @@ impl PyADBUSBDevice {
|
|||||||
/// Autodetect a device reachable over USB.
|
/// Autodetect a device reachable over USB.
|
||||||
/// This method raises an error if multiple devices or none are connected.
|
/// This method raises an error if multiple devices or none are connected.
|
||||||
pub fn autodetect() -> Result<Self> {
|
pub fn autodetect() -> Result<Self> {
|
||||||
Ok(ADBRusbDevice::autodetect()?.into())
|
Ok(ADBUSBDevice::autodetect()?.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run shell commands on device and return the output (stdout + stderr merged)
|
/// Run shell commands on device and return the output (stdout + stderr merged)
|
||||||
@@ -51,8 +51,8 @@ impl PyADBUSBDevice {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ADBRusbDevice> for PyADBUSBDevice {
|
impl From<ADBUSBDevice> for PyADBUSBDevice {
|
||||||
fn from(value: ADBRusbDevice) -> Self {
|
fn from(value: ADBUSBDevice) -> Self {
|
||||||
Self(value)
|
Self(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user