18 Commits

Author SHA1 Message Date
LIAUD Corentin
cdf062c3e1 bump: version 2.1.9 2025-03-09 19:43:54 +01:00
cocool97
b8e3d02311 feat: do not show prompt on Windows (#98) 2025-03-09 19:42:39 +01:00
cocool97
1b7efc1cc6 feat: ADBServerDevice without serial (#97)
* feat: ADBServerDevice without serial

* chore: bump deps

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

---------

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

View File

@@ -1,47 +1,36 @@
name: Python - Build packages & Release
on:
push: {}
pull_request: {}
push:
branches:
- main
pull_request:
release:
types: [created]
jobs:
build-python-packages:
runs-on: ubuntu-latest
defaults:
run:
working-directory: pyadb_client
steps:
- uses: actions/checkout@v4
- name: Install Python dependencies
run: pip install .
- name: Build Python stubs
run: cargo run --bin stub_gen
- name: Install Python build dependencies
run: pip install maturin==1.8.2
- name: Build Python packages
run: maturin build --release --interpreter "3.8" --interpreter "3.9" --interpreter "3.10" --interpreter "3.11" --interpreter "3.12" --interpreter "3.13"
publish-python-packages:
runs-on: ubuntu-latest
defaults:
run:
working-directory: pyadb_client
needs: [build-python-packages]
if: github.event_name == 'release' && github.event.action == 'created'
steps:
- uses: actions/checkout@v4
- name: Install Python dependencies
run: pip install .
run: maturin build --sdist --release -m pyadb_client/Cargo.toml
- name: Publish Python packages
run: maturin publish --no-interactive
if: github.event_name == 'release' && github.event.action == 'created'
run: maturin publish -m pyadb_client/Cargo.toml --non-interactive
env:
MATURIN_PYPI_TOKEN: ${{ secrets.MATURIN_PYPI_TOKEN }}
- name: "Publish GitHub artefacts"
if: github.event_name == 'release' && github.event.action == 'created'
uses: softprops/action-gh-release@v2
with:
files: |

View File

@@ -1,6 +1,10 @@
name: Rust - Build
on: [push, pull_request]
on:
push:
branches:
- main
pull_request:
env:
CARGO_TERM_COLOR: always

View File

@@ -1,6 +1,10 @@
name: Rust - Quality
on: [push, pull_request]
on:
push:
branches:
- main
pull_request:
env:
CARGO_TERM_COLOR: always

3
.gitignore vendored
View File

@@ -2,4 +2,5 @@ target
/Cargo.lock
/.vscode
venv
/.mypy_cache
/.mypy_cache
pyadb_client/pyadb_client.pyi

View File

@@ -9,7 +9,7 @@ homepage = "https://github.com/cocool97/adb_client"
keywords = ["adb", "android", "tcp", "usb"]
license = "MIT"
repository = "https://github.com/cocool97/adb_client"
version = "2.1.3"
version = "2.1.9"
# To build locally when working on a new release
[patch.crates-io]

View File

@@ -14,7 +14,7 @@ adb_client = { version = "^2.0.0" }
anyhow = { version = "1.0.94" }
clap = { version = "4.5.23", features = ["derive"] }
env_logger = { version = "0.11.5" }
log = { version = "0.4.22" }
log = { version = "0.4.26" }
[target.'cfg(unix)'.dependencies]
termios = { version = "0.3.3" }

View File

@@ -36,7 +36,7 @@ impl Drop for ADBTermios {
fn drop(&mut self) {
// Custom drop implementation, restores previous termios structure.
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
log::error!("Error while droping ADBTermios: {e}")
log::error!("Error while dropping ADBTermios: {e}")
}
}
}

View File

@@ -1,4 +1,4 @@
use adb_client::{ADBServer, DeviceShort, MDNSBackend, Result};
use adb_client::{ADBServer, DeviceShort, MDNSBackend, Result, WaitForDeviceState};
use crate::models::{HostCommand, MdnsCommand, ServerCommand};
@@ -72,6 +72,10 @@ pub fn handle_host_commands(server_command: ServerCommand<HostCommand>) -> Resul
HostCommand::ServerStatus => {
log::info!("{}", adb_server.server_status()?);
}
HostCommand::WaitForDevice { transport } => {
log::info!("waiting for device to be connected...");
adb_server.wait_for_device(WaitForDeviceState::Device, transport)?;
}
}
Ok(())

View File

@@ -7,12 +7,15 @@ mod handlers;
mod models;
mod utils;
use adb_client::{ADBDeviceExt, ADBServer, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService};
use adb_client::{
ADBDeviceExt, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice, MDNSDiscoveryService,
};
use adb_termios::ADBTermios;
use anyhow::Result;
use clap::Parser;
use handlers::{handle_emulator_commands, handle_host_commands, handle_local_commands};
use models::{DeviceCommands, LocalCommand, MainCommand, Opts};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
@@ -30,11 +33,15 @@ fn main() -> Result<()> {
MainCommand::Host(server_command) => return Ok(handle_host_commands(server_command)?),
MainCommand::Emu(emulator_command) => return handle_emulator_commands(emulator_command),
MainCommand::Local(server_command) => {
let mut adb_server = ADBServer::new(server_command.address);
// Must start server to communicate with device, but only if this is a local one.
let server_address_ip = server_command.address.ip();
if server_address_ip.is_loopback() || server_address_ip.is_unspecified() {
ADBServer::start(&HashMap::default());
}
let device = match server_command.serial {
Some(serial) => adb_server.get_device_by_name(&serial)?,
None => adb_server.get_device()?,
Some(serial) => ADBServerDevice::new(serial, Some(server_command.address)),
None => ADBServerDevice::autodetect(Some(server_command.address)),
};
match server_command.command {
@@ -133,6 +140,10 @@ fn main() -> Result<()> {
log::info!("Starting installation of APK {}...", path.display());
device.install(&path)?;
}
DeviceCommands::Uninstall { package } => {
log::info!("Uninstalling the package {}...", package);
device.uninstall(&package)?;
}
DeviceCommands::Framebuffer { path } => {
device.framebuffer(&path)?;
log::info!("Successfully dumped framebuffer at path {path}");

View File

@@ -33,6 +33,11 @@ pub enum DeviceCommands {
/// Path to APK file. Extension must be ".apk"
path: PathBuf,
},
/// Uninstall a package from the device
Uninstall {
/// Name of the package to uninstall
package: String,
},
/// Dump framebuffer of device
Framebuffer {
/// Framebuffer image destination path

View File

@@ -1,7 +1,14 @@
use std::net::SocketAddrV4;
use adb_client::{RustADBError, WaitForDeviceTransport};
use clap::Parser;
fn parse_wait_for_device_device_transport(
value: &str,
) -> Result<WaitForDeviceTransport, RustADBError> {
WaitForDeviceTransport::try_from(value)
}
#[derive(Parser, Debug)]
pub enum HostCommand {
/// Print current ADB version.
@@ -28,6 +35,12 @@ pub enum HostCommand {
},
/// Display server status
ServerStatus,
/// Wait for a device, on optionally given transport
WaitForDevice {
/// Transport on which wait for devices
#[clap(short = 't', long = "transport", value_parser = parse_wait_for_device_device_transport)]
transport: Option<WaitForDeviceTransport>,
},
}
#[derive(Parser, Debug)]

View File

@@ -13,22 +13,22 @@ version.workspace = true
base64 = { version = "0.22.1" }
bincode = { version = "1.3.3" }
byteorder = { version = "1.5.0" }
chrono = { version = "0.4.39" }
chrono = { version = "0.4.40" }
homedir = { version = "0.3.4" }
image = { version = "0.25.5" }
lazy_static = { version = "1.5.0" }
log = { version = "0.4.22" }
mdns-sd = { version = "0.13.1" }
log = { version = "0.4.26" }
mdns-sd = { version = "0.13.2" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
rand = { version = "0.8.5" }
rand = { version = "0.9.0" }
rcgen = { version = "0.13.1" }
regex = { version = "1.11.1", features = ["perf", "std", "unicode"] }
rsa = { version = "0.9.7" }
rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.18" }
rustls-pki-types = "1.10.0"
rustls = { version = "0.23.22" }
rustls-pki-types = "1.11.0"
serde = { version = "1.0.216", features = ["derive"] }
serde_repr = { version = "0.1.19" }
sha1 = { version = "0.10.6", features = ["oid"] }

View File

@@ -41,6 +41,9 @@ pub trait ADBDeviceExt {
/// Install an APK pointed to by `apk_path` on device.
fn install(&mut self, apk_path: &dyn AsRef<Path>) -> Result<()>;
/// Uninstall the package `package` from device.
fn uninstall(&mut self, package: &str) -> Result<()>;
/// Inner method requesting framebuffer from an Android device
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>>;

View File

@@ -213,11 +213,11 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
}
pub(crate) fn open_session(&mut self, data: &[u8]) -> Result<ADBTransportMessage> {
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), // Our 'local-id'
rng.random(), // Our 'local-id'
0,
data,
);

View File

@@ -35,6 +35,10 @@ impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
self.install(apk_path)
}
fn uninstall(&mut self, package: &str) -> Result<()> {
self.uninstall(package)
}
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.framebuffer_inner()
}

View File

@@ -38,18 +38,26 @@ impl ADBTcpDevice {
self.get_transport_mut().write_message(message)?;
// At this point, we should have received a STLS command indicating that the device wants to upgrade connection with TLS
self.get_transport_mut()
.read_message()
.and_then(|message| message.assert_command(MessageCommand::Stls))?;
let message = self.get_transport_mut().read_message()?;
self.get_transport_mut()
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
// Upgrade TCP connection to TLS
self.get_transport_mut().upgrade_connection()?;
log::debug!("Connection successfully upgraded from TCP to TLS");
// Check if client is requesting a secure connection and upgrade it if necessary
match message.header().command() {
MessageCommand::Stls => {
self.get_transport_mut()
.write_message(ADBTransportMessage::new(MessageCommand::Stls, 1, 0, &[]))?;
self.get_transport_mut().upgrade_connection()?;
log::debug!("Connection successfully upgraded from TCP to TLS");
}
MessageCommand::Cnxn => {
log::debug!("Unencrypted connection established");
}
_ => {
return Err(crate::RustADBError::WrongResponseReceived(
"Expected CNXN or STLS command".to_string(),
message.header().command().to_string(),
));
}
}
Ok(())
}
@@ -96,6 +104,11 @@ impl ADBDeviceExt for ADBTcpDevice {
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()

View File

@@ -273,6 +273,11 @@ impl ADBDeviceExt for ADBUSBDevice {
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()

View File

@@ -16,9 +16,9 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let file_size = apk_file.metadata()?.len();
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let local_id = rng.gen();
let local_id = rng.random();
self.open_session(format!("exec:cmd package 'install' -S {}\0", file_size).as_bytes())?;

View File

@@ -5,3 +5,4 @@ mod push;
mod reboot;
mod shell;
mod stat;
mod uninstall;

View File

@@ -0,0 +1,19 @@
use crate::{device::adb_message_device::ADBMessageDevice, ADBMessageTransport, Result};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn uninstall(&mut self, package_name: &str) -> Result<()> {
self.open_session(format!("exec:cmd package 'uninstall' {}\0", package_name).as_bytes())?;
let final_status = self.get_transport_mut().read_message()?;
match final_status.into_payload().as_slice() {
b"Success\n" => {
log::info!("Package {} successfully uninstalled", package_name);
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
d.to_vec(),
)?)),
}
}
}

View File

@@ -3,7 +3,6 @@ use base64::{engine::general_purpose::STANDARD, Engine};
use num_bigint::{BigUint, ModInverse};
use num_traits::cast::ToPrimitive;
use num_traits::FromPrimitive;
use rand::rngs::OsRng;
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PublicKeyParts;
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
@@ -52,7 +51,7 @@ pub struct ADBRsaKey {
impl ADBRsaKey {
pub fn new_random() -> Result<Self> {
Ok(Self {
private_key: RsaPrivateKey::new(&mut OsRng, ADB_PRIVATE_KEY_SIZE)?,
private_key: RsaPrivateKey::new(&mut rsa::rand_core::OsRng, ADB_PRIVATE_KEY_SIZE)?,
})
}

View File

@@ -65,10 +65,15 @@ impl TryFrom<ADBServerDevice> for ADBEmulatorDevice {
type Error = RustADBError;
fn try_from(value: ADBServerDevice) -> std::result::Result<Self, Self::Error> {
ADBEmulatorDevice::new(
value.identifier.clone(),
Some(*value.transport.get_socketaddr().ip()),
)
match &value.identifier {
Some(device_identifier) => ADBEmulatorDevice::new(
device_identifier.clone(),
Some(*value.transport.get_socketaddr().ip()),
),
None => Err(RustADBError::DeviceNotFound(
"cannot connect to an emulator device without knowing its identifier".to_string(),
)),
}
}
}

View File

@@ -117,6 +117,9 @@ pub enum RustADBError {
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
/// An unknown transport has been provided
#[error("unknown transport: {0}")]
UnknownTransport(String),
}
impl<T> From<std::sync::PoisonError<T>> for RustADBError {

View File

@@ -1,5 +1,7 @@
use std::fmt::Display;
use crate::{WaitForDeviceState, WaitForDeviceTransport};
use super::RebootType;
use std::net::SocketAddrV4;
@@ -20,7 +22,9 @@ pub(crate) enum AdbServerCommand {
MDNSServices,
ServerStatus,
ReconnectOffline,
Uninstall(String),
Install(u64),
WaitForDevice(WaitForDeviceState, WaitForDeviceTransport),
// Local commands
ShellCommand(String),
Shell,
@@ -83,6 +87,15 @@ impl Display for AdbServerCommand {
}
AdbServerCommand::Usb => write!(f, "usb:"),
AdbServerCommand::Install(size) => write!(f, "exec:cmd package 'install' -S {size}"),
AdbServerCommand::Uninstall(package) => {
write!(f, "exec:cmd package 'uninstall' {package}")
}
AdbServerCommand::WaitForDevice(wait_for_device_state, wait_for_device_transport) => {
write!(
f,
"host:wait-for-{wait_for_device_transport}-{wait_for_device_state}"
)
}
}
}
}

View File

@@ -27,6 +27,33 @@ impl ADBServer {
}
}
/// Start an instance of `adb-server`
pub fn start(envs: &HashMap<String, String>) {
// ADB Server is local, we start it if not already running
let mut command = Command::new("adb");
command.arg("start-server");
for (env_k, env_v) in envs.iter() {
command.env(env_k, env_v);
}
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
// Do not show a prompt on Windows
command.creation_flags(0x08000000);
}
let child = command.spawn();
match child {
Ok(mut child) => {
if let Err(e) = child.wait() {
log::error!("error while starting adb server: {e}")
}
}
Err(e) => log::error!("error while starting adb server: {e}"),
}
}
/// Returns the current selected transport
pub(crate) fn get_transport(&mut self) -> Result<&mut TCPServerTransport> {
self.transport
@@ -52,22 +79,7 @@ impl ADBServer {
};
if is_local_ip {
// ADB Server is local, we start it if not already running
let mut command = Command::new("adb");
command.arg("start-server");
for (env_k, env_v) in self.envs.iter() {
command.env(env_k, env_v);
}
let child = command.spawn();
match child {
Ok(mut child) => {
if let Err(e) = child.wait() {
log::error!("error while starting adb server: {e}")
}
}
Err(e) => log::error!("error while starting adb server: {e}"),
}
Self::start(&self.envs);
}
transport.connect()?;

View File

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

View File

@@ -0,0 +1,20 @@
use crate::{
models::AdbServerCommand, ADBServer, Result, WaitForDeviceState, WaitForDeviceTransport,
};
impl ADBServer {
/// Wait for a device in a given state to be connected
pub fn wait_for_device(
&mut self,
state: WaitForDeviceState,
transport: Option<WaitForDeviceTransport>,
) -> Result<()> {
let transport = transport.unwrap_or_default();
self.connect()?
.send_adb_request(AdbServerCommand::WaitForDevice(state, transport))?;
// Server should respond with an "OKAY" response
self.get_transport()?.read_adb_response()
}
}

View File

@@ -6,7 +6,7 @@ use crate::{DeviceState, RustADBError};
use regex::bytes::Regex;
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(?P<identifier>\\S+)\\s+(?P<state>\\w+) ((usb:(?P<usb1>.*)|(?P<usb2>\\d-\\d)) )?(product:(?P<product>\\w+) model:(?P<model>\\w+) device:(?P<device>\\w+) )?transport_id:(?P<transport_id>\\d+)$").expect("cannot build devices long regex")
Regex::new(r"^(?P<identifier>\S+)\s+(?P<state>\w+)\s+(usb:(?P<usb1>\S+)|(?P<usb2>\S+))?\s*(product:(?P<product>\w+)\s+model:(?P<model>\w+)\s+device:(?P<device>\w+)\s+)?transport_id:(?P<transport_id>\d+)$").expect("cannot build devices long regex")
});
/// Represents a new device with more informations.

View File

@@ -4,6 +4,7 @@ mod device_short;
mod device_state;
mod mdns_services;
mod server_status;
mod wait_for_device;
pub use adb_version::AdbVersion;
pub use device_long::DeviceLong;
@@ -11,3 +12,4 @@ pub use device_short::DeviceShort;
pub use device_state::DeviceState;
pub use mdns_services::MDNSServices;
pub use server_status::{MDNSBackend, ServerStatus};
pub use wait_for_device::{WaitForDeviceState, WaitForDeviceTransport};

View File

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

View File

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

View File

@@ -20,9 +20,8 @@ impl ADBDeviceExt for ADBServerDevice {
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.send_adb_request(AdbServerCommand::ShellCommand(command.join(" ")))?;
@@ -59,9 +58,7 @@ impl ADBDeviceExt for ADBServerDevice {
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport.send_adb_request(AdbServerCommand::Shell)?;
let mut read_stream = self.transport.get_raw_connection()?.try_clone()?;
@@ -115,6 +112,10 @@ impl ADBDeviceExt for ADBServerDevice {
self.install(apk_path)
}
fn uninstall(&mut self, package: &str) -> Result<()> {
self.uninstall(package)
}
fn framebuffer_inner(&mut self) -> Result<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> {
self.framebuffer_inner()
}

View File

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

View File

@@ -11,9 +11,7 @@ use crate::{
impl ADBServerDevice {
/// Inner method requesting framebuffer from Android device
pub(crate) fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
let serial: String = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.send_adb_request(AdbServerCommand::FrameBuffer)?;

View File

@@ -6,9 +6,7 @@ use crate::{
impl ADBServerDevice {
/// Lists available ADB server features.
pub fn host_features(&mut self) -> Result<Vec<HostFeatures>> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
let features = self
.transport

View File

@@ -13,9 +13,7 @@ impl ADBServerDevice {
let file_size = apk_file.metadata()?.len();
let serial: String = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.send_adb_request(AdbServerCommand::Install(file_size))?;

View File

@@ -11,9 +11,7 @@ use std::{
impl ADBServerDevice {
/// Lists files in path on the device.
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
// Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?;

View File

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

View File

@@ -6,9 +6,7 @@ use crate::{
impl ADBServerDevice {
/// Reboots the device
pub fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::Reboot(reboot_type), false)

View File

@@ -3,9 +3,7 @@ use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Reconnect device
pub fn reconnect(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::Reconnect, false)

View File

@@ -71,9 +71,7 @@ impl<R: Read> Read for ADBRecvCommandReader<R> {
impl ADBServerDevice {
/// Receives path to stream from the device.
pub fn pull(&mut self, path: &dyn AsRef<str>, stream: &mut dyn Write) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
// Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?;

View File

@@ -3,9 +3,7 @@ use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Reverse socket connection
pub fn reverse(&mut self, remote: String, local: String) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::Reverse(remote, local), false)
@@ -14,9 +12,7 @@ impl ADBServerDevice {
/// Remove all reverse rules
pub fn reverse_remove_all(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::ReverseRemoveAll, false)

View File

@@ -45,9 +45,7 @@ impl ADBServerDevice {
/// Send stream to path on the device.
pub fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
log::info!("Sending data to {}", path.as_ref());
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
// Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?;

View File

@@ -39,9 +39,7 @@ impl ADBServerDevice {
/// Stat file given as path on the device.
pub fn stat<A: AsRef<str>>(&mut self, path: A) -> Result<AdbStatResponse> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
// Set device in SYNC mode
self.transport.send_adb_request(AdbServerCommand::Sync)?;

View File

@@ -3,9 +3,7 @@ use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Set adb daemon to tcp/ip mode
pub fn tcpip(&mut self, port: u16) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::TcpIp(port), false)

View File

@@ -0,0 +1,26 @@
use std::io::Read;
use crate::{models::AdbServerCommand, server_device::ADBServerDevice, Result};
impl ADBServerDevice {
/// Uninstall a package from device
pub fn uninstall(&mut self, package_name: &str) -> Result<()> {
self.set_serial_transport()?;
self.transport
.send_adb_request(AdbServerCommand::Uninstall(package_name.to_string()))?;
let mut data = [0; 1024];
let read_amount = self.transport.get_raw_connection()?.read(&mut data)?;
match &data[0..read_amount] {
b"Success\n" => {
log::info!("Package {} successfully uninstalled", package_name);
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
d.to_vec(),
)?)),
}
}
}

View File

@@ -3,10 +3,7 @@ use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Set adb daemon to usb mode
pub fn usb(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.set_serial_transport()?;
self.transport
.proxy_connection(AdbServerCommand::Usb, false)
.map(|_| ())

View File

@@ -33,6 +33,14 @@ impl TCPServerTransport {
}
}
/// Instantiate a new instance of [TCPServerTransport] using given address, or default if not specified.
pub fn new_or_default(socket_addr: Option<SocketAddrV4>) -> Self {
match socket_addr {
Some(s) => Self::new(s),
None => Self::default(),
}
}
/// Get underlying [SocketAddrV4]
pub fn get_socketaddr(&self) -> SocketAddrV4 {
self.socket_addr
@@ -113,6 +121,11 @@ impl TCPServerTransport {
self.get_raw_connection()?
.write_all(adb_request.as_bytes())?;
self.read_adb_response()
}
/// Read a response from ADB server
pub(crate) fn read_adb_response(&mut self) -> Result<()> {
// Reads returned status code from ADB server
let mut request_status = [0; 4];
self.get_raw_connection()?.read_exact(&mut request_status)?;

View File

@@ -1,7 +1,7 @@
use adb_client::ADBServer;
use anyhow::Result;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use rand::{thread_rng, Rng};
use rand::{rng, Rng};
use std::fs::File;
use std::io::Write;
use std::process::Command;
@@ -14,7 +14,7 @@ const REMOTE_TEST_FILE_PATH: &str = "/data/local/tmp/test_file.bin";
fn generate_test_file(size_in_bytes: usize) -> Result<()> {
let mut test_file = File::create(LOCAL_TEST_FILE_PATH)?;
let mut rng = thread_rng();
let mut rng = rng();
const BUFFER_SIZE: usize = 64 * 1024;
let mut buffer = [0u8; BUFFER_SIZE];

View File

@@ -1,20 +1,30 @@
[package]
name = "pyadb_client"
description = "Python wrapper for adb_client library"
authors.workspace = true
description = "Python wrapper for adb_client library"
edition.workspace = true
homepage.workspace = true
keywords.workspace = true
license.workspace = true
name = "pyadb_client"
readme = "README.md"
repository.workspace = true
version.workspace = true
readme = "README.md"
[lib]
crate-type = ["cdylib", "rlib"]
name = "pyadb_client"
crate-type = ["cdylib"]
[[bin]]
doc = false
name = "stub_gen"
[dependencies]
anyhow = { version = "1.0.94" }
adb_client = { version = "2.0.6" }
pyo3 = { version = "0.23.3", features = ["extension-module", "anyhow"] }
adb_client = { path = "../adb_client" }
anyhow = { version = "1.0.95" }
pyo3 = { version = "0.23.4", features = [
"abi3-py37",
"anyhow",
"extension-module",
] }
pyo3-stub-gen = "0.7.0"
pyo3-stub-gen-derive = "0.7.0"

View File

@@ -2,12 +2,20 @@
Python library to communicate with ADB devices. Built on top of Rust `adb_client` library.
## Installation
```bash
pip install pyadb_client
```
## Examples
### Use ADB server
```python
server = pyadb_client.PyADBServer("127.0.0.1:5037")
from pyadb_client import PyADBServer
server = PyADBServer("127.0.0.1:5037")
for i, device in enumerate(server.devices()):
print(i, device.identifier, device.state)
@@ -19,6 +27,8 @@ print(device, device.identifier)
### Push a file on device
```python
from pyadb_client import PyADBUSBDevice
usb_device = PyADBUSBDevice.autodetect()
usb_device.push("file.txt", "/data/local/tmp/file.txt")
```
@@ -31,14 +41,15 @@ cd pyadb_client
python3 -m venv .venv
source .venv/bin/activate
# Install needed dependencies
pip install -e .
# Install needed build dependencies
pip install maturin
# Build development package
maturin develop
# Build release Python package
maturin build --release
# Build stub file (.pyi)
cargo run --bin stub_gen
# Publish Python package
```
# Build release Python package
maturin build --release -m pyadb_client/Cargo.toml
```

View File

@@ -1,13 +1,12 @@
[build-system]
requires = ["maturin>=1,<2"]
build-backend = "maturin"
requires = ["maturin>=1,<2"]
[project]
classifiers = ["Programming Language :: Python", "Programming Language :: Rust"]
dynamic = ["authors", "keywords", "version"]
name = "pyadb_client"
dependencies = ["maturin", "patchelf"]
dynamic = ["version"] # Let the build system automatically set package version
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
requires-python = ">= 3.7"
[tool.maturin]
features = ["pyo3/extension-module"]

View File

@@ -3,28 +3,36 @@ use std::net::SocketAddrV4;
use adb_client::ADBServer;
use anyhow::Result;
use pyo3::{pyclass, pymethods, PyResult};
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
use crate::{PyADBServerDevice, PyDeviceShort};
#[gen_stub_pyclass]
#[pyclass]
/// Represent an instance of an ADB Server
pub struct PyADBServer(ADBServer);
#[gen_stub_pymethods]
#[pymethods]
impl PyADBServer {
#[new]
/// Instantiate a new PyADBServer instance
pub fn new(address: String) -> PyResult<Self> {
let address = address.parse::<SocketAddrV4>()?;
Ok(ADBServer::new(address).into())
}
/// List available devices
pub fn devices(&mut self) -> Result<Vec<PyDeviceShort>> {
Ok(self.0.devices()?.into_iter().map(|v| v.into()).collect())
}
/// Get a device, assuming that only one is currently connected
pub fn get_device(&mut self) -> Result<PyADBServerDevice> {
Ok(self.0.get_device()?.into())
}
/// Get a device by its name, as shown in `.devices()` output
pub fn get_device_by_name(&mut self, name: String) -> Result<PyADBServerDevice> {
Ok(self.0.get_device_by_name(&name)?.into())
}

View File

@@ -1,18 +1,24 @@
use adb_client::{ADBDeviceExt, ADBServerDevice};
use anyhow::Result;
use pyo3::{pyclass, pymethods};
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
use std::{fs::File, path::PathBuf};
#[gen_stub_pyclass]
#[pyclass]
/// Represent a device connected to the ADB server
pub struct PyADBServerDevice(pub ADBServerDevice);
#[gen_stub_pymethods]
#[pymethods]
impl PyADBServerDevice {
#[getter]
pub fn identifier(&self) -> String {
/// Device identifier
pub fn identifier(&self) -> Option<String> {
self.0.identifier.clone()
}
/// Run shell commands on device and return the output (stdout + stderr merged)
pub fn shell_command(&mut self, commands: Vec<String>) -> Result<Vec<u8>> {
let mut output = Vec::new();
let commands: Vec<&str> = commands.iter().map(|x| &**x).collect();
@@ -20,15 +26,27 @@ impl PyADBServerDevice {
Ok(output)
}
/// Push a local file from input to dest
pub fn push(&mut self, input: PathBuf, dest: PathBuf) -> Result<()> {
let mut reader = File::open(input)?;
Ok(self.0.push(&mut reader, dest.to_string_lossy())?)
}
/// Pull a file from device located at input, and drop it to dest
pub fn pull(&mut self, input: PathBuf, dest: PathBuf) -> Result<()> {
let mut writer = File::create(dest)?;
Ok(self.0.pull(&input.to_string_lossy(), &mut writer)?)
}
/// Install a package installed on the device
pub fn install(&mut self, apk_path: PathBuf) -> Result<()> {
Ok(self.0.install(&apk_path)?)
}
/// Uninstall a package installed on the device
pub fn uninstall(&mut self, package: &str) -> Result<()> {
Ok(self.0.uninstall(package)?)
}
}
impl From<ADBServerDevice> for PyADBServerDevice {

View File

@@ -3,17 +3,24 @@ use std::{fs::File, path::PathBuf};
use adb_client::{ADBDeviceExt, ADBUSBDevice};
use anyhow::Result;
use pyo3::{pyclass, pymethods};
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
#[gen_stub_pyclass]
#[pyclass]
/// Represent a device directly reachable over USB.
pub struct PyADBUSBDevice(ADBUSBDevice);
#[gen_stub_pymethods]
#[pymethods]
impl PyADBUSBDevice {
#[staticmethod]
/// Autodetect a device reachable over USB.
/// This method raises an error if multiple devices or none are connected.
pub fn autodetect() -> Result<Self> {
Ok(ADBUSBDevice::autodetect()?.into())
}
/// Run shell commands on device and return the output (stdout + stderr merged)
pub fn shell_command(&mut self, commands: Vec<String>) -> Result<Vec<u8>> {
let mut output = Vec::new();
let commands: Vec<&str> = commands.iter().map(|x| &**x).collect();
@@ -21,15 +28,27 @@ impl PyADBUSBDevice {
Ok(output)
}
/// Push a local file from input to dest
pub fn push(&mut self, input: PathBuf, dest: PathBuf) -> Result<()> {
let mut reader = File::open(input)?;
Ok(self.0.push(&mut reader, &dest.to_string_lossy())?)
}
/// Pull a file from device located at input, and drop it to dest
pub fn pull(&mut self, input: PathBuf, dest: PathBuf) -> Result<()> {
let mut writer = File::create(dest)?;
Ok(self.0.pull(&input.to_string_lossy(), &mut writer)?)
}
/// Install a package installed on the device
pub fn install(&mut self, apk_path: PathBuf) -> Result<()> {
Ok(self.0.install(&apk_path)?)
}
/// Uninstall a package installed on the device
pub fn uninstall(&mut self, package: &str) -> Result<()> {
Ok(self.0.uninstall(package)?)
}
}
impl From<ADBUSBDevice> for PyADBUSBDevice {

View File

@@ -0,0 +1,5 @@
use pyo3_stub_gen::Result;
fn main() -> Result<()> {
pyadb_client::stub_info()?.generate()
}

View File

@@ -1,3 +1,6 @@
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
mod adb_server;
mod adb_server_device;
mod adb_usb_device;
@@ -8,6 +11,7 @@ pub use adb_usb_device::*;
pub use models::*;
use pyo3::prelude::*;
use pyo3_stub_gen::StubInfo;
#[pymodule]
fn pyadb_client(m: &Bound<'_, PyModule>) -> PyResult<()> {
@@ -18,3 +22,9 @@ fn pyadb_client(m: &Bound<'_, PyModule>) -> PyResult<()> {
Ok(())
}
/// Get stub informations for this package.
pub fn stub_info() -> anyhow::Result<StubInfo> {
// Need to be run from workspace root directory
StubInfo::from_pyproject_toml(format!("{}/pyproject.toml", env!("CARGO_MANIFEST_DIR")))
}

View File

@@ -1,19 +1,25 @@
use adb_client::DeviceShort;
use pyo3::{pyclass, pymethods};
use pyo3_stub_gen_derive::{gen_stub_pyclass, gen_stub_pymethods};
// Check https://docs.rs/rigetti-pyo3/latest/rigetti_pyo3 to automatically build this code
#[gen_stub_pyclass]
#[pyclass]
/// Represent a device output as shown when running `adb devices`
pub struct PyDeviceShort(DeviceShort);
#[gen_stub_pymethods]
#[pymethods]
impl PyDeviceShort {
#[getter]
/// Device identifier
pub fn identifier(&self) -> String {
self.0.identifier.clone()
}
#[getter]
/// Device state
pub fn state(&self) -> String {
self.0.state.to_string()
}

View File

@@ -42,7 +42,10 @@ mod tests {
#[test]
fn test_static_devices_long() {
let inputs = ["7a5158f05122195aa device 1-5 product:gts210vewifixx model:SM_T813 device:gts210vewifi transport_id:4"];
let inputs = ["7a5158f05122195aa device 1-5 product:gts210vewifixx model:SM_T813 device:gts210vewifi transport_id:4",
"n311r05e device usb:0-1.5 product:alioth model:M2012K11AC device:alioth transport_id:58",
"192.168.100.192:5555 device product:alioth model:M2012K11AC device:alioth transport_id:97",
"emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:101"];
for input in inputs {
DeviceLong::try_from(input.as_bytes().to_vec())
.expect(&format!("cannot parse input: '{input}'"));